@swarmcloud/hls 2.16.3 → 2.16.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/hls-proxy.js +1 -1
- package/hls.light.min.js +1 -1
- package/hls.min.js +1 -1
- package/hlsjs-p2p-engine.min.js +1 -1
- package/p2p-engine.es.min.js +1 -1
- package/p2p-engine.min.js +1 -1
- package/package.json +1 -1
- package/sw-p2p-engine.min.js +1 -1
package/hls.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(this,(()=>(()=>{var e={415:e=>{"use strict";var t,i="object"==typeof Reflect?Reflect:null,r=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function n(){n.init.call(this)}e.exports=n,e.exports.once=function(e,t){return new Promise((function(i,r){function s(i){e.removeListener(t,n),r(i)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&p(e,"error",t,i)}(e,s,{once:!0})}))},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function h(e,t,i,r){var s,n,a,h;if(o(i),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),n=e._events),a=n[t]),void 0===a)a=n[t]=i,++e._eventsCount;else if("function"==typeof a?a=n[t]=r?[i,a]:[a,i]:r?a.unshift(i):a.push(i),(s=l(e))>0&&a.length>s&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,h=u,console&&console.warn&&console.warn(h)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=u.bind(r);return s.listener=i,r.wrapFn=s,s}function c(e,t,i){var r=e._events;if(void 0===r)return[];var s=r[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):g(s,s.length)}function f(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function g(e,t){for(var i=new Array(t),r=0;r<t;++r)i[r]=e[r];return i}function p(e,t,i,r){if("function"==typeof e.on)r.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(n){r.once&&e.removeEventListener(t,s),i(n)}))}}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),n.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var s="error"===e,n=this._events;if(void 0!==n)s=s&&void 0===n.error;else if(!s)return!1;if(s){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var l=n[e];if(void 0===l)return!1;if("function"==typeof l)r(l,this,t);else{var h=l.length,u=g(l,h);for(i=0;i<h;++i)r(u[i],this,t)}return!0},n.prototype.addListener=function(e,t){return h(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return h(this,e,t,!0)},n.prototype.once=function(e,t){return o(t),this.on(e,d(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,d(this,e,t)),this},n.prototype.removeListener=function(e,t){var i,r,s,n,a;if(o(t),void 0===(r=this._events))return this;if(void 0===(i=r[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,n=i.length-1;n>=0;n--)if(i[n]===t||i[n].listener===t){a=i[n].listener,s=n;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(r[e]=i[0]),void 0!==r.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,i,r;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,n=Object.keys(i);for(r=0;r<n.length;++r)"removeListener"!==(s=n[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},n.prototype.listeners=function(e){return c(this,e,!0)},n.prototype.rawListeners=function(e){return c(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return i.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(d)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()},251:e=>{!function t(i){var r;r=function(){"use strict";function e(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function r(t,i,r){return i&&e(t.prototype,i),r&&e(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function s(e,t,i){return(t=c(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},n.apply(null,arguments)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function o(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,d(e,t)}function l(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(l=function(){return!!e})()}function h(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function u(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?h(Object(i),!0).forEach((function(t){s(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):h(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function c(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function f(e){var t="function"==typeof Map?new Map:void 0;return f=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return function(e,t,i){if(l())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var s=new(e.bind.apply(e,r));return i&&d(s,i.prototype),s}(e,arguments,a(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),d(i,e)},f(e)}var g,p,v={exports:{}},m=(g||(g=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,n||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,s,n,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,h,u=this._events[o],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,s),!0;case 5:return u.fn.call(u.context,t,r,s,n),!0;case 6:return u.fn.call(u.context,t,r,s,n,a),!0}for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var c,f=u.length;for(h=0;h<f;h++)switch(u[h].once&&this.removeListener(e,u[h].fn,void 0,!0),d){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,t);break;case 3:u[h].fn.call(u[h].context,t,r);break;case 4:u[h].fn.call(u[h].context,t,r,s);break;default:if(!l)for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u[h].fn.apply(u[h].context,l)}}return!0},o.prototype.on=function(e,t,i){return n(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return n(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,r,s){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||s&&!o.once||r&&o.context!==r||a(this,n);else{for(var l=0,h=[],u=o.length;l<u;l++)(o[l].fn!==t||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(v)),v.exports),y=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(m),E={exports:{}},S=(p||(p=1,function(e,t){var i,r,s,n,a;i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return i.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(d)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(E)),E.exports),T=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},_=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=L},L=Number.MAX_SAFE_INTEGER||9007199254740991,b=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),A=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),I=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({}),R="manifest",P="level",k="audioTrack",D="subtitleTrack",w="main",C="audio",M="subtitle",O=function(){function e(e,t,i){void 0===t&&(t=0),void 0===i&&(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}var t=e.prototype;return t.sample=function(e,t){var i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),x=function(){function e(e,t,i,r){void 0===r&&(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 O(e),this.fast_=new O(t),this.defaultTTFB_=r,this.ttfb_=new O(e)}var t=e.prototype;return t.update=function(e,t){var i=this.slow_,r=this.fast_,s=this.ttfb_;i.halfLife!==e&&(this.slow_=new O(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new O(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new O(e,s.getEstimate(),s.getTotalWeight()))},t.sample=function(e,t){var i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)},t.sampleTTFB=function(e){var t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},r(e,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),F=function(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="["+e+"]:";this.trace=N,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)},N=function(){},B={trace:N,debug:N,log:N,warn:N,info:N,error:N};function U(){return n({},B)}function G(e,t,i){return t[e]?t[e].bind(t):function(e,t){var i=self.console[e];return i?i.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):N}(e,i)}var H=U();function K(e,t,i){var r=U();if("object"==typeof console&&!0===e||"object"==typeof e){var s=["debug","log","info","warn","error"];s.forEach((function(t){r[t]=G(t,e,i)}));try{r.log('Debug logs enabled for "'+t+'" in hls.js version 1.6.12')}catch(e){return U()}s.forEach((function(t){H[t]=G(t,e)}))}else n(H,r);return r}var V=H;function $(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function W(e,t){var i=Object.keys(e),r=Object.keys(t),s=i.length,n=r.length;return!s||!n||s===n&&!i.some((function(e){return-1===r.indexOf(e)}))}function q(e,t){if(void 0===t&&(t=!1),"undefined"!=typeof TextDecoder){var i=new TextDecoder("utf-8").decode(e);if(t){var r=i.indexOf("\0");return-1!==r?i.substring(0,r):i}return i.replace(/\0/g,"")}for(var s,n,a,o=e.length,l="",h=0;h<o;){if(0===(s=e[h++])&&t)return l;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(s);break;case 12:case 13:n=e[h++],l+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=e[h++],a=e[h++],l+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&a)}}return l}function j(e){for(var t="",i=0;i<e.length;i++){var r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t}function Y(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var z=function(){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}},X="audio",Q="video",J="audiovideo",Z=function(){function e(e){var t;this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,(t=re(this,"stats"))&&(t.enumerable=!0,Object.defineProperty(this,"stats",t))}var t=e.prototype;return t.setByteRange=function(e,t){var i,r=e.split("@",2);i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]},t.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[X]=null,e[Q]=null,e[J]=null},r(e,[{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){var e;return null===this._streams&&(this._streams=((e={})[X]=null,e[Q]=null,e[J]=null,e)),this._streams},set:function(e){this._streams=e}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new z),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=S.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}])}();function ee(e){return"initSegment"!==e.sn}var te=function(e){function t(t,i){var r;return(r=e.call(this,i)||this)._decryptdata=null,r._programDateTime=null,r._ref=null,r._bitrate=void 0,r.rawProgramDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.playlistOffset=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=t,r}o(t,e);var i=t.prototype;return i.addStart=function(e){this.setStart(this.start+e)},i.setStart=function(e){this.start=e,this._ref&&(this._ref.start=e)},i.setDuration=function(e){this.duration=e,this._ref&&(this._ref.duration=e)},i.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},i.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},i.setElementaryStreamInfo=function(e,t,i,r,s,n){void 0===n&&(n=!1);var a=this.elementaryStreams,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:n}},r(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],i=this.byteRange[1];if(T(t)&&T(i))return i-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{var t=Object.keys(this.levelkeys);if(1===t.length){var i=this._decryptdata=this.levelkeys[t[0]]||null;if(i)return i.getDecryptData(this.sn)}}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=T(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,i=Object.keys(this.levelkeys),r=i.length;if(r>1||1===r&&null!=(t=this.levelkeys[i[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){T(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return ee(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(Z),ie=function(e){function t(t,i,r,s,n){var a;(a=e.call(this,r)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.duration=t.decimalFloatingPoint("DURATION"),a.gap=t.bool("GAP"),a.independent=t.bool("INDEPENDENT"),a.relurl=t.enumeratedString("URI"),a.fragment=i,a.index=s;var o=t.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,n),n&&(a.fragOffset=n.fragOffset+n.duration),a}return o(t,e),r(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}])}(Z);function re(e,t){var i=Object.getPrototypeOf(e);if(i)return Object.getOwnPropertyDescriptor(i,t)||re(i,t)}var se=Math.pow(2,32)-1,ne=[].push,ae={video:1,audio:2,id3:3,text:4};function oe(e){return String.fromCharCode.apply(null,e)}function le(e,t){var i=e[t]<<8|e[t+1];return i<0?65536+i:i}function he(e,t){var i=de(e,t);return i<0?4294967296+i:i}function ue(e,t){var i=he(e,t);return(i*=Math.pow(2,32))+he(e,t+4)}function de(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ce(e,t){var i=[];if(!t.length)return i;for(var r=e.byteLength,s=0;s<r;){var n=he(e,s),a=n>1?s+n:r;if(oe(e.subarray(s+4,s+8))===t[0])if(1===t.length)i.push(e.subarray(s+8,a));else{var o=ce(e.subarray(s+8,a),t.slice(1));o.length&&ne.apply(i,o)}s=a}return i}function fe(e){var t=[],i=e[0],r=8,s=he(e,r);r+=4;var n=0,a=0;0===i?(n=he(e,r),a=he(e,r+4),r+=8):(n=ue(e,r),a=ue(e,r+8),r+=16),r+=2;var o=e.length+a,l=le(e,r);r+=2;for(var h=0;h<l;h++){var u=r,d=he(e,u);u+=4;var c=2147483647&d;if(1==(2147483648&d)>>>31)return V.warn("SIDX has hierarchical references (not supported)"),null;var f=he(e,u);u+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+c-1}}),o+=c,r=u+=4}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:t}}function ge(e){for(var t=[],i=ce(e,["moov","trak"]),r=0;r<i.length;r++){var s=i[r],n=ce(s,["tkhd"])[0];if(n){var a=n[0],o=he(n,0===a?12:20),l=ce(s,["mdia","mdhd"])[0];if(l){var h=he(l,0===(a=l[0])?12:20),d=ce(s,["mdia","hdlr"])[0];if(d){var c=oe(d.subarray(8,12)),f={soun:X,vide:Q}[c],g=pe(ce(s,["mdia","minf","stbl","stsd"])[0]);f?(t[o]={timescale:h,type:f,stsd:g},t[f]=u({timescale:h,id:o},g)):t[o]={timescale:h,type:c,stsd:g}}}}}return ce(e,["moov","mvex","trex"]).forEach((function(e){var i=he(e,4),r=t[i];r&&(r.default={duration:he(e,12),flags:he(e,20)})})),t}function pe(e){var t,i=e.subarray(8),r=i.subarray(86),s=oe(i.subarray(4,8)),n=s,a="enca"===s||"encv"===s;if(a){var o=ce(i,[s])[0];ce(o.subarray("enca"===s?28:78),["sinf"]).forEach((function(e){var t=ce(e,["schm"])[0];if(t){var i=oe(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=ce(e,["frma"])[0];r&&(n=oe(r))}}}))}var l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":var h=ce(r,["avcC"])[0];h&&h.length>3&&(n+="."+ye(h[1])+ye(h[2])+ye(h[3]),t=ve("avc1"===l?"dva1":"dvav",r));break;case"mp4a":var u=ce(i,[s])[0],d=ce(u.subarray(28),["esds"])[0];if(d&&d.length>7){var c=4;if(3!==d[c++])break;c=me(d,c),c+=2;var f=d[c++];if(128&f&&(c+=2),64&f&&(c+=d[c++]),4!==d[c++])break;c=me(d,c);var g=d[c++];if(64!==g)break;if(n+="."+ye(g),c+=12,5!==d[c++])break;c=me(d,c);var p=d[c++],v=(248&p)>>3;31===v&&(v+=1+((7&p)<<3)+((224&d[c])>>5)),n+="."+v}break;case"hvc1":case"hev1":var m=ce(r,["hvcC"])[0];if(m&&m.length>12){var y=m[1],E=["","A","B","C"][y>>6],S=31&y,T=he(m,2),_=(32&y)>>5?"H":"L",L=m[12],b=m.subarray(6,12);n+="."+E+S,n+="."+function(e){for(var t=0,i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}(T).toString(16).toUpperCase(),n+="."+_+L;for(var A="",I=b.length;I--;){var R=b[I];(R||A)&&(A="."+R.toString(16).toUpperCase()+A)}n+=A}t=ve("hev1"==l?"dvhe":"dvh1",r);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ve(n,r)||n;break;case"vp09":var P=ce(r,["vpcC"])[0];if(P&&P.length>6){var k=P[4],D=P[5],w=P[6]>>4&15;n+="."+Ee(k)+"."+Ee(D)+"."+Ee(w)}break;case"av01":var C=ce(r,["av1C"])[0];if(C&&C.length>2){var M=C[1]>>>5,O=31&C[1],x=C[2]>>>7?"H":"M",F=(64&C[2])>>6,N=(32&C[2])>>5,B=2===M&&F?N?12:10:F?10:8,U=(16&C[2])>>4,G=(8&C[2])>>3,H=(4&C[2])>>2,K=3&C[2];n+="."+M+"."+Ee(O)+x+"."+Ee(B)+"."+U+"."+G+H+K+"."+Ee(1)+"."+Ee(1)+"."+Ee(1)+".0",t=ve("dav1",r)}}return{codec:n,encrypted:a,supplemental:t}}function ve(e,t){var i=ce(t,["dvvC"]),r=i.length?i[0]:ce(t,["dvcC"])[0];if(r){var s=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return e+"."+Ee(s)+"."+Ee(n)}}function me(e,t){for(var i=t+5;128&e[t++]&&t<i;);return t}function ye(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ee(e){return(e<10?"0":"")+e}function Se(e){var t=ce(e,["schm"])[0];if(t){var i=oe(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return ce(e,["schi","tenc"])[0]}return null}function Te(e,t){var i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function _e(e,t){var i=[],r=t.samples,s=t.timescale,n=t.id,a=!1;return ce(r,["moof"]).map((function(o){var l=o.byteOffset-8;ce(o,["traf"]).map((function(o){var h=ce(o,["tfdt"]).map((function(e){var t=e[0],i=he(e,4);return 1===t&&(i*=Math.pow(2,32),i+=he(e,8)),i/s}))[0];return void 0!==h&&(e=h),ce(o,["tfhd"]).map((function(h){var u=he(h,4),d=16777215&he(h,0),c=0,f=!!(16&d),g=0,p=!!(32&d),v=8;u===n&&(!!(1&d)&&(v+=8),!!(2&d)&&(v+=4),!!(8&d)&&(c=he(h,v),v+=4),f&&(g=he(h,v),v+=4),p&&(v+=4),"video"===t.type&&(a=Le(t.codec)),ce(o,["trun"]).map((function(n){var o=n[0],h=16777215&he(n,0),u=!!(1&h),d=0,f=!!(4&h),p=!!(256&h),v=0,m=!!(512&h),y=0,E=!!(1024&h),S=!!(2048&h),T=0,_=he(n,4),L=8;u&&(d=he(n,L),L+=4),f&&(L+=4);for(var b=d+l,A=0;A<_;A++){if(p?(v=he(n,L),L+=4):v=c,m?(y=he(n,L),L+=4):y=g,E&&(L+=4),S&&(T=0===o?he(n,L):de(n,L),L+=4),t.type===Q)for(var I=0;I<y;){var R=he(r,b);be(a,r[b+=4])&&Ae(r.subarray(b,b+R),a?2:1,e+T/s,i),b+=R,I+=R+4}e+=v/s}})))}))}))})),i}function Le(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function be(e,t){if(e){var i=t>>1&63;return 39===i||40===i}return 6==(31&t)}function Ae(e,t,i,r){var s=Ie(e),n=0;n+=t;for(var a=0,o=0,l=0;n<s.length;){a=0;do{if(n>=s.length)break;a+=l=s[n++]}while(255===l);o=0;do{if(n>=s.length)break;o+=l=s[n++]}while(255===l);var h=s.length-n,u=n;if(o<h)n+=o;else if(o>h){V.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===s[u++]){var d=le(s,u);if(u+=2,49===d){var c=he(s,u);if(u+=4,1195456820===c){var f=s[u++];if(3===f){var g=s[u++],p=64&g,v=p?2+3*(31&g):0,m=new Uint8Array(v);if(p){m[0]=g;for(var y=1;y<v;y++)m[y]=s[u++]}r.push({type:f,payloadType:a,pts:i,bytes:m})}}}}}else if(5===a&&o>16){for(var E=[],S=0;S<16;S++){var T=s[u++].toString(16);E.push(1==T.length?"0"+T:T),3!==S&&5!==S&&7!==S&&9!==S||E.push("-")}for(var _=o-16,L=new Uint8Array(_),b=0;b<_;b++)L[b]=s[u++];r.push({payloadType:a,pts:i,uuid:E.join(""),userData:q(L),userDataBytes:L})}}}function Ie(e){for(var t=e.byteLength,i=[],r=1;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;var s=t-i.length,n=new Uint8Array(s),a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=e[a];return n}function Re(e){var t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};var s=e.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:t};var n=e.buffer,a=j(new Uint8Array(n,i+12,16)),o=null,l=0;if(0===s)l=28;else{var h=e.getUint32(28);if(!h||r<32+16*h)return{offset:i,size:t};o=[];for(var u=0;u<h;u++)o.push(new Uint8Array(n,i+32+16*u,16));l=32+16*h}if(!l)return{offset:i,size:t};var d=e.getUint32(l);return t-32<d?{offset:i,size:t}:{version:s,systemId:a,kids:o,data:new Uint8Array(n,i+l+4,d),offset:i,size:t}}var Pe=function(){return/\(Windows.+Firefox\//i.test(navigator.userAgent)},ke={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,dav1:.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 De(e,t){var i=ke[t];return!!i&&!!i[e.slice(0,4)]}function we(e,t,i){return void 0===i&&(i=!0),!e.split(",").some((function(e){return!Ce(e,t,i)}))}function Ce(e,t,i){var r;void 0===i&&(i=!0);var s=$(i);return null!=(r=null==s?void 0:s.isTypeSupported(Me(e,t)))&&r}function Me(e,t){return t+"/mp4;codecs="+e}function Oe(e){if(e){var t=e.substring(0,4);return ke.video[t]}return 2}function xe(e){var t=Pe();return e.split(",").reduce((function(e,i){var r=t&&Le(i)?9:ke.video[i];return r?(2*r+e)/(e?3:2):(ke.audio[i]+e)/(e?2:1)}),0)}var Fe={},Ne=/flac|opus|mp4a\.40\.34/i;function Be(e,t){return void 0===t&&(t=!0),e.replace(Ne,(function(e){return function(e,t){if(void 0===t&&(t=!0),Fe[e])return Fe[e];for(var i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],r=0;r<i.length;r++){var s;if(Ce(i[r],"audio",t))return Fe[e]=i[r],i[r];if("mp3"===i[r]&&null!=(s=$(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)}))}function Ue(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(Ge(e,"audio")||Ge(e,"video")))return e;if(t){var i=t.split(",");if(i.length>1){if(e)for(var r=i.length;r--;)if(i[r].substring(0,4)===e.substring(0,4))return i[r];return i[0]}}return t||e}function Ge(e,t){return De(e,t)&&Ce(e,t)}function He(e){if(e.startsWith("av01.")){for(var t=e.split("."),i=["0","111","01","01","01","0"],r=t.length;r>4&&r<10;r++)t[r]=i[r-4];return t.join(".")}return e}function Ke(e){var t=$(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ve(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var $e={supported:!1,smooth:!1,powerEfficient:!1},We={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function qe(e,t){return{supported:!1,configurations:t,decodingInfoResults:[$e],error:e}}function je(e,t,i,r){void 0===r&&(r={});var s=e.videoCodec;if(!s&&!e.audioCodec||!i)return Promise.resolve(We);for(var n=[],a=function(e){var t,i=null==(t=e.videoCodec)?void 0:t.split(","),r=ze(e),s=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map((function(e){var t={contentType:Me(He(e),"video"),width:s,height:n,bitrate:r,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t})):[]}(e),o=a.length,l=function(e,t,i){var r,s=null==(r=e.audioCodec)?void 0:r.split(","),n=ze(e);return s&&e.audioGroups?e.audioGroups.reduce((function(e,r){var a,o=r?null==(a=t.groups[r])?void 0:a.tracks:null;return o?o.reduce((function(e,t){if(t.groupId===r){var a=parseFloat(t.channels||"");s.forEach((function(t){var r={contentType:Me(t,"audio"),bitrate:i?Ye(t,n):n};a&&(r.channels=""+a),e.push(r)}))}return e}),e):e}),[]):[]}(e,t,o>0),h=l.length,u=o||1*h||1;u--;){var d={type:"media-source"};if(o&&(d.video=a[u%o]),h){d.audio=l[u%h];var c=d.audio.bitrate;d.video&&c&&(d.video.bitrate-=c)}n.push(d)}if(s){var f=navigator.userAgent;if(s.split(",").some((function(e){return Le(e)}))&&Pe())return Promise.resolve(qe(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: ("+f+")"),n))}return Promise.all(n.map((function(e){var t,s,n,a,o=(s="",n=(t=e).audio,(a=t.video)&&(s+=Ve(a.contentType)+"_r"+a.height+"x"+a.width+"f"+Math.ceil(a.framerate)+(a.transferFunction||"sd")+"_"+Math.ceil(a.bitrate/1e5)),n&&(s+=(a?"_":"")+Ve(n.contentType)+"_c"+n.channels),s);return r[o]||(r[o]=i.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:n,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:n,decodingInfoResults:[],error:e}}))}function Ye(e,t){if(t<=1)return 1;var i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}function ze(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}var Xe=["NONE","TYPE-0","TYPE-1",null],Qe=["SDR","PQ","HLG"];function Je(e){var t=e.canSkipUntil,i=e.canSkipDateRanges,r=e.age;return t&&r<t/2?i?"v2":"YES":""}var Ze=function(){function e(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}return e.prototype.addDirectives=function(e){var t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href},e}(),et=function(){function e(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((function(e){return!!e})).map((function(e){return e.substring(0,4)})).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;var i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=","+i.substring(0,4))}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}var t=e.prototype;return t.hasAudioGroup=function(e){return tt(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return tt(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(t)&&i.push(t)}else if("text"===e){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(t)&&r.push(t)}},t.addFallback=function(){},r(e,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}}])}();function tt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}var it=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(i,r){if(e&&(r=e(i,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}}(t))};function rt(e,t){V.log('[abr] start candidates with "'+e+'" ignored because '+t)}function st(e){return e.reduce((function(e,t){var i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);var 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 nt(e){if(!e)return e;var t=e;return{lang:t.lang,assocLang:t.assocLang,characteristics:t.characteristics,channels:t.channels,audioCodec:t.audioCodec}}function at(e,t,i){if("attrs"in e){var r=t.indexOf(e);if(-1!==r)return r}for(var s=0;s<t.length;s++)if(ot(e,t[s],i))return s;return-1}function ot(e,t,i){var r,s,n=e.groupId,a=e.name,o=e.lang,l=e.assocLang,h=e.default,u=e.forced;return(void 0===n||t.groupId===n)&&(void 0===a||t.name===a)&&(void 0===o||(r=o,void 0===(s=t.lang)&&(s="--"),r.length===s.length?r===s:r.startsWith(s)||s.startsWith(r)))&&(void 0===o||t.assocLang===l)&&(void 0===h||t.default===h)&&(void 0===u||t.forced===u)&&(!("characteristics"in e)||function(e,t){void 0===t&&(t="");var i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some((function(e){return-1===r.indexOf(e)}))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function lt(e,t){var i=e.audioCodec,r=e.channels;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function ht(e,t,i){for(var r=t;r>-1;r--)if(i(e[r]))return r;for(var s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function ut(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}var dt=function(e){function t(t){var i;return(i=e.call(this,"abr",t.logger)||this).hls=void 0,i.lastLevelLoadSec=0,i.lastLoadedFragLevel=-1,i.firstSelection=-1,i._nextAutoLevel=-1,i.nextAutoLevelKey="",i.audioTracksByGroup=null,i.codecTiers=null,i.timer=-1,i.fragCurrent=null,i.partCurrent=null,i.bitrateTestDelay=0,i.rebufferNotice=-1,i.supportedCache={},i.bwEstimator=void 0,i._abandonRulesCheck=function(e){var t,r=i,s=r.fragCurrent,n=r.partCurrent,a=r.hls,o=a.autoLevelEnabled,l=a.media;if(s&&l){var h=performance.now(),u=n?n.stats:s.stats,d=n?n.duration:s.duration,c=h-u.loading.start,f=a.minAutoLevel,g=s.level,p=i._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f)return i.clearTimer(),void(i._nextAutoLevel=-1);if(o){var v=p>-1&&p!==g,m=!!e||v;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=a.mainForwardBufferInfo;if(m||null!==y){var E=i.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(!(c<=Math.max(E,d/(2*S)*1e3))){var _=y?y.len/S:0,L=u.loading.first?u.loading.first-u.loading.start:-1,b=u.loaded&&L>-1,A=i.getBwEstimate(),R=a.levels,P=R[g],k=Math.max(u.loaded,Math.round(d*(s.bitrate||P.averageBitrate)/8)),D=b?c-L:c;D<1&&b&&(D=Math.min(c,8*u.loaded/A));var w=b?1e3*u.loaded/D:0,C=E/1e3,M=w?(k-u.loaded)/w:8*k/A+C;if(!(M<=_)){var O,x=w?8*w:A,F=!0===(null==(t=(null==e?void 0:e.details)||i.hls.latestLevelDetails)?void 0:t.live),N=i.hls.config.abrBandWidthUpFactor,B=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){var U=R[O].maxBitrate,G=!R[O].details||F;if((B=i.getTimeToLoadFrag(C,x,d*U,G))<Math.min(_,d+C))break}if(!(B>=M||B>10*d)){b?i.bwEstimator.sample(c-Math.min(E,L),u.loaded):i.bwEstimator.sampleTTFB(c);var H=R[O].maxBitrate;i.getBwEstimate()*N>H&&i.resetEstimator(H);var K=i.findBestLevel(H,f,O,0,_,1,1);K>-1&&(O=K),i.warn("Fragment "+s.sn+(n?" part "+n.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+s.duration.toFixed(3)+"\n Time to underbuffer: "+_.toFixed(3)+" s\n Estimated load time for current fragment: "+M.toFixed(3)+" s\n Estimated load time for down switch fragment: "+B.toFixed(3)+" s\n TTFB estimate: "+(0|L)+" ms\n Current BW estimate: "+(T(A)?0|A:"Unknown")+" bps\n New BW estimate: "+(0|i.getBwEstimate())+" bps\n Switching to level "+O+" @ "+(0|H)+" bps"),a.nextLoadLevel=a.nextAutoLevel=O,i.clearTimer();var V=function(){if(i.clearTimer(),i.fragCurrent===s&&i.hls.loadLevel===O&&O>0){var e=i.getStarvationDelay();if(i.warn("Aborting inflight request "+(O>0?"and switching down":"")+"\n Fragment duration: "+s.duration.toFixed(3)+" s\n Time to underbuffer: "+e.toFixed(3)+" s"),s.abortRequests(),i.fragCurrent=i.partCurrent=null,O>f){var t=i.findBestLevel(i.hls.levels[f].bitrate,f,O,0,e,1,1);-1===t&&(t=f),i.hls.nextLoadLevel=i.hls.nextAutoLevel=t,i.resetEstimator(i.hls.levels[t].bitrate)}}};v||M>2*B?V():i.timer=self.setInterval(V,1e3*B),a.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:u})}}}}}}}},i.hls=t,i.bwEstimator=i.initEstimator(),i.registerListeners(),i}o(t,e);var i=t.prototype;return i.resetEstimator=function(e){e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},i.initEstimator=function(){var e=this.hls.config;return new x(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},i.registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(I.ERROR,this.onError,this))},i.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null},i.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},i.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},i.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},i.onFragLoading=function(e,t){var i,r=t.frag;this.ignoreFragment(r)||(r.bitrateTest||(this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},i.onLevelSwitching=function(e,t){this.clearTimer()},i.onError=function(e,t){if(!t.fatal)switch(t.details){case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case A.FRAG_LOAD_TIMEOUT:var i=t.frag,r=this.fragCurrent,s=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var n=performance.now(),a=s?s.stats:i.stats,o=n-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){var h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}}},i.getTimeToLoadFrag=function(e,t,i,r){return e+i/t+(r?e+this.lastLevelLoadSec:0)},i.onLevelLoaded=function(e,t){var i=this.hls.config,r=t.stats.loading,s=r.end-r.first;T(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},i.onFragLoaded=function(e,t){var i=t.frag,r=t.part,s=r?r.stats:i.stats;if(i.type===w&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var n=r?r.duration:i.duration,a=this.hls.levels[i.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(i.bitrateTest){var h={stats:s,frag:i,part:r,id:i.type};this.onFragBuffered(I.FRAG_BUFFERED,h),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(!s.aborted&&!this.ignoreFragment(i)){var n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},i.ignoreFragment=function(e){return e.type!==w||"initSegment"===e.sn},i.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},i.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},i.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,i=this.hls;if(i.levels.length<=1)return i.loadLevel;var r=i.maxAutoLevel,s=i.config,n=i.minAutoLevel,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=s.abrBandWidthFactor,u=s.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,n,r,l,0,h,u);if(d>=0)return this.rebufferNotice=-1,d}var c=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-f,this.info("bitrate test took "+Math.round(1e3*f)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*c)+" ms"),h=u=1)}var g=this.findBestLevel(o,n,r,l,c,h,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var p=i.levels[n],v=i.loadLevelObj;return v&&(null==p?void 0:p.bitrate)<v.bitrate?n:i.loadLevel},i.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i},i.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},i.findBestLevel=function(e,t,i,r,s,n,a){var o,l=this,h=r+s,u=this.lastLoadedFragLevel,d=-1===u?this.hls.firstLevel:u,c=this.fragCurrent,f=this.partCurrent,g=this.hls,p=g.levels,v=g.allAudioTracks,m=g.loadLevel,y=g.config;if(1===p.length)return 0;var E,S=p[d],_=!(null==(o=this.hls.latestLevelDetails)||!o.live),L=-1===m||-1===u,b="SDR",A=(null==S?void 0:S.frameRate)||0,I=y.audioPreference,R=y.videoPreference,P=this.audioTracksByGroup||(this.audioTracksByGroup=st(v)),k=-1;if(L){if(-1!==this.firstSelection)return this.firstSelection;var D=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce((function(e,i,r){if(!i.codecSet)return e;var s=i.audioGroups,n=e[i.codecSet];n||(e[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);var a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,s&&s.forEach((function(e){if(e){var i=t.groups[e];i&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((function(e){n.channels[e]=(n.channels[e]||0)+i.channels[e]})))}})),e}),{})}(p,P,t,i)),w=function(e,t,i,r,s){for(var n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=null==s?void 0:s.videoCodec,h=a&&2===parseInt(a),u=!1,d=!1,c=1/0,f=1/0,g=1/0,p=1/0,v=0,m=[],y=function(e,t){var i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){var s="SDR"!==(r=t.allowedVideoRanges||Qe.slice(0)).join("")&&!t.videoCodec;(i=void 0!==t.preferHDR?t.preferHDR:s&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}(t,s),E=y.preferHDR,S=y.allowedVideoRanges,_=function(){var t=e[n[L]];u||(u=t.channels[2]>0),c=Math.min(c,t.minHeight),f=Math.min(f,t.minFramerate),g=Math.min(g,t.minBitrate),S.filter((function(e){return t.videoRanges[e]>0})).length>0&&(d=!0)},L=n.length;L--;)_();c=T(c)?c:0,f=T(f)?f:0;var b=Math.max(1080,c),A=Math.max(30,f);g=T(g)?g:i,i=Math.max(g,i),d||(t=void 0);var I=n.length>1;return{codecSet:n.reduce((function(t,r){var s=e[r];if(r===t)return t;if(m=d?S.filter((function(e){return s.videoRanges[e]>0})):[],I){if(s.minBitrate>i)return rt(r,"min bitrate of "+s.minBitrate+" > current estimate of "+i),t;if(!s.hasDefaultAudio)return rt(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return rt(r,'audio codec preference "'+o+'" not found'),t;if(a&&!h){if(!s.channels[a])return rt(r,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(s.channels)+")"),t}else if((!o||h)&&u&&0===s.channels[2])return rt(r,"no renditions with stereo sound found"),t;if(s.minHeight>b)return rt(r,"min resolution of "+s.minHeight+" > maximum of "+b),t;if(s.minFramerate>A)return rt(r,"min framerate of "+s.minFramerate+" > maximum of "+A),t;if(!m.some((function(e){return s.videoRanges[e]>0})))return rt(r,"no variants with VIDEO-RANGE of "+it(m)+" found"),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return rt(r,'video codec preference "'+l+'" not found'),t;if(s.maxScore<v)return rt(r,"max score of "+s.maxScore+" < selected max of "+v),t}return t&&(xe(r)>=xe(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,v=s.maxScore,r)}),void 0),videoRanges:m,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}(D,b,e,I,R),C=w.codecSet,M=w.videoRanges,O=w.minFramerate,x=w.minBitrate,F=w.minIndex,N=w.preferHDR;k=F,E=C,b=N?M[M.length-1]:M[0],A=O,e=Math.max(e,x),this.log("picked start tier "+it(w))}else E=null==S?void 0:S.codecSet,b=null==S?void 0:S.videoRange;for(var B,U=f?f.duration:c?c.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,H=[],K=function(){var t,o=p[V],c=V>d;if(!o)return 0;if(y.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&function(e,t,i,r,s,n){var a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,u=h?parseInt(h):l?1/0:2,d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((function(e,i){if(i){var r=t.groups[i];if(!r)throw new Error("Audio track group "+i+" not found");Object.keys(r.channels).forEach((function(t){e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some((function(e){return Le(e)}))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!d&&T(u)&&Object.keys(d).some((function(e){return parseInt(e)>u}))}(o,P,b,A,e,I)?(o.supportedPromise=je(o,P,g,l.supportedCache),o.supportedPromise.then((function(e){if(l.hls){o.supportedResult=e;var t=l.hls.levels,i=t.indexOf(o);e.error?l.warn('MediaCapabilities decodingInfo error: "'+e.error+'" for level '+i+" "+it(e)):e.supported?e.decodingInfoResults.some((function(e){return!1===e.smooth||!1===e.powerEfficient}))&&l.log("MediaCapabilities decodingInfo for level "+i+" not smooth or powerEfficient: "+it(e)):(l.warn("Unsupported MediaCapabilities decodingInfo result for level "+i+" "+it(e)),i>-1&&t.length>1&&(l.log("Removing unsupported level "+i),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}})).catch((function(e){l.warn("Error handling MediaCapabilities decodingInfo: "+e)}))):o.supportedResult=We}if((E&&o.codecSet!==E||b&&o.videoRange!==b||c&&A>o.frameRate||!c&&A>0&&A<o.frameRate||null!=(t=o.supportedResult)&&null!=(t=t.decodingInfoResults)&&t.some((function(e){return!1===e.smooth})))&&(!L||V!==k))return H.push(V),0;var v,S=o.details,R=(f?null==S?void 0:S.partTarget:null==S?void 0:S.averagetargetduration)||U;v=c?a*e:n*e;var D=U&&r>=2*U&&0===s?o.averageBitrate:o.maxBitrate,w=l.getTimeToLoadFrag(G,v,D*R,void 0===S);if(v>=D&&(V===u||0===o.loadError&&0===o.fragmentError)&&(w<=G||!T(w)||_&&!l.bitrateTestDelay||w<h)){var C=l.forcedAutoLevel;return V===m||-1!==C&&C===m||(H.length&&l.trace("Skipped level(s) "+H.join(",")+" of "+i+' max with CODECS and VIDEO-RANGE:"'+p[H[0]].codecs+'" '+p[H[0]].videoRange+'; not compatible with "'+E+'" '+b),l.info("switch candidate:"+d+"->"+V+" adjustedbw("+Math.round(v)+")-bitrate="+Math.round(v-D)+" ttfb:"+G.toFixed(1)+" avgDuration:"+R.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+w.toFixed(1)+" firstSelection:"+L+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+m)),L&&(l.firstSelection=V),{v:V}}},V=i;V>=t;V--)if(0!==(B=K())&&B)return B.v;return-1},i.deriveNextAutoLevel=function(e){var t=this.hls,i=t.maxAutoLevel,r=t.minAutoLevel;return Math.min(Math.max(e,r),i)},r(t,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,i=e.minAutoLevel,r=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(r,i,t,0,s,1,1);if(n>-1)return n;var a=this.hls.firstLevel,o=Math.min(Math.max(a,i),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+a+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var s=this.hls.levels;if(s.length>Math.max(e,r)&&s[e].loadError<=s[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(F),ct=function(e,t){for(var i=0,r=e.length-1,s=null,n=null;i<=r;){var a=t(n=e[s=(i+r)/2|0]);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function ft(e,t,i,r,s){void 0===i&&(i=0),void 0===r&&(r=0),void 0===s&&(s=.005);var n=null;if(e){n=t[1+e.sn-t[0].sn]||null;var a=e.endDTS-i;a>0&&a<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===gt(i,r,n)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var r=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),i);return e.start<=r}return!1}(n,e,Math.min(s,r))))return n;var o=ct(t,gt.bind(null,i,r));return!o||o===e&&n?n:o}function gt(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=0),i.start<=e&&i.start+i.duration>e)return 0;var r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function pt(e,t,i){var r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}function vt(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){var r,s=e.fragments,n=e.fragmentHint;return n&&(s=s.concat(n)),ct(s,(function(e){return e.cc<t?1:e.cc>t?-1:(r=e,e.end<=i?1:e.start>i?-1:0)})),r||null}return null}function mt(e){switch(e.details){case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_TIMEOUT:case A.LEVEL_LOAD_TIMEOUT:case A.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function yt(e){return e.details.startsWith("key")}function Et(e){return yt(e)&&!!e.frag&&!e.frag.decryptdata}function St(e,t){var i=mt(t);return e.default[(i?"timeout":"error")+"Retry"]}function Tt(e,t){var i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function _t(e){return u(u({},e),{errorRetry:null,timeoutRetry:null})}function Lt(e,t,i,r){if(!e)return!1;var s=null==r?void 0:r.code,n=t<e.maxNumRetry&&(function(e){return bt(e)||!!e&&(e<400||e>499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}function bt(e){return 0===e&&!1===navigator.onLine}var At=function(e){function t(t){var i;return(i=e.call(this,"error-controller",t.logger)||this).hls=void 0,i.playlistError=0,i.hls=t,i.registerListeners(),i}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(I.ERROR,this.onError,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.ERROR,this.onError,this),e.off(I.ERROR,this.onErrorOut,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this))},i.destroy=function(){this.unregisterListeners(),this.hls=null},i.startLoad=function(e){},i.stopLoad=function(){this.playlistError=0},i.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===w?e.level:this.getVariantIndex()},i.getVariantIndex=function(){var e,t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i},i.variantHasKey=function(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;var r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter((function(e){return r.indexOf(e.groupId)>=0})).some((function(e){var i;return null==(i=e.details)?void 0:i.hasKey(t)}))}return!1},i.onManifestLoading=function(){this.playlistError=0},i.onLevelUpdated=function(){this.playlistError=0},i.onError=function(e,t){var i;if(!t.fatal){var r=this.hls,s=t.context;switch(t.details){case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case A.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=It());case A.FRAG_GAP:case A.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=2);case A.LEVEL_EMPTY_ERROR:case A.LEVEL_PARSING_ERROR:var n,a=t.parent===w?t.level:r.loadLevel;return void(t.details===A.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,a)));case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level)));case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.SUBTITLE_LOAD_ERROR:case A.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){var o=r.loadLevelObj;if(o&&(s.type===k&&o.hasAudioGroup(s.groupId)||s.type===D&&o.hasSubtitleGroup(s.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:2,flags:2});case A.KEY_SYSTEM_SESSION_UPDATE_FAILED:case A.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case A.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:2,flags:4});case A.BUFFER_ADD_CODEC_ERROR:case A.REMUX_ALLOC_ERROR:case A.BUFFER_APPEND_ERROR:var l;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(l=t.level)?l:r.loadLevel)));case A.INTERNAL_EXCEPTION:case A.BUFFER_APPENDING_ERROR:case A.BUFFER_FULL_ERROR:case A.LEVEL_SWITCH_ERROR:case A.BUFFER_STALLED_ERROR:case A.BUFFER_SEEK_OVER_HOLE:case A.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=It())}t.type===b.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=It())}},i.getPlaylistRetryOrSwitchAction=function(e,t){var i=St(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Lt(i,r,mt(e),e.response))return{action:5,flags:0,retryConfig:i,retryCount:r};var s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s},i.getFragRetryOrSwitchAction=function(e){var t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],s=t.config,n=s.fragLoadPolicy,a=s.keyLoadPolicy,o=St(yt(e)?a:n,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(r&&(e.details!==A.FRAG_GAP&&r.fragmentError++,!Et(e)&&Lt(o,l,mt(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(e,i);return o&&(h.retryConfig=o,h.retryCount=l),h},i.getLevelSwitchAction=function(e,t){var i=this.hls;null==t&&(t=i.loadLevel);var r=this.hls.levels[t];if(r){var s,n,a=e.details;r.loadError++,a===A.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,h=i.loadLevel,u=i.minAutoLevel,d=i.maxAutoLevel;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);for(var c,f=null==(s=e.frag)?void 0:s.type,g=(f===C&&a===A.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(a===A.BUFFER_ADD_CODEC_ERROR||a===A.BUFFER_APPEND_ERROR))&&l.some((function(e){var t=e.audioCodec;return r.audioCodec!==t})),p="video"===e.sourceBufferName&&(a===A.BUFFER_ADD_CODEC_ERROR||a===A.BUFFER_APPEND_ERROR)&&l.some((function(e){var t=e.codecSet,i=e.audioCodec;return r.codecSet!==t&&r.audioCodec===i})),v=null!=(n=e.context)?n:{},m=v.type,y=v.groupId,E=function(){var t=(S+h)%l.length;if(t!==h&&t>=u&&t<=d&&0===l[t].loadError){var i,s,n=l[t];if(a===A.FRAG_GAP&&f===w&&e.frag){var c=l[t].details;if(c){var v=ft(e.frag,c.fragments,e.frag.start);if(null!=v&&v.gap)return 0}}else{if(m===k&&n.hasAudioGroup(y)||m===D&&n.hasSubtitleGroup(y))return 0;if(f===C&&null!=(i=r.audioGroups)&&i.some((function(e){return n.hasAudioGroup(e)}))||f===M&&null!=(s=r.subtitleGroups)&&s.some((function(e){return n.hasSubtitleGroup(e)}))||g&&r.audioCodec===n.audioCodec||p&&r.codecSet===n.codecSet||!g&&r.codecSet!==n.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(c=E())||1!==c););if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}},i.onErrorOut=function(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===A.FRAG_GAP?/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()):t.fatal=!0}t.fatal&&this.hls.stopLoad()},i.sendAlternateToPenaltyBox=function(e){var t=this.hls,i=e.errorAction;if(i){var r=i.flags,s=i.nextAutoLevel;switch(r){case 0:this.switchLevel(e,s);break;case 2:var n=this.getVariantLevelIndex(e.frag),a=t.levels[n],o=null==a?void 0:a.attrs["HDCP-LEVEL"];if(i.hdcpLevel=o,"NONE"===o)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(o){t.maxHdcpLevel=Xe[Xe.indexOf(o)-1],i.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower');break}case 4:var l=e.decryptdata;if(l){for(var h=this.hls.levels,u=h.length,d=u;d--;){var c,f;this.variantHasKey(h[d],l)&&(this.log("Banned key found in level "+d+" ("+h[d].bitrate+'bps) or audio group "'+(null==(c=h[d].audioGroups)?void 0:c.join(","))+'" ('+(null==(f=e.frag)?void 0:f.type)+" fragment) "+j(l.keyId||[])),h[d].fragmentError++,h[d].loadError++,this.log("Removing level "+d+" with key error ("+e.error+")"),this.hls.removeLevel(d))}var g=e.frag;if(this.hls.levels.length<u)i.resolved=!0;else if(g&&g.type!==w){var p=g.decryptdata;p&&!l.matches(p)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(e,s)}},i.switchLevel=function(e,t){if(void 0!==t&&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,e.details===A.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var i=Ve(e.mimeType),r=this.hls.levels,s=r.length;s--;)r[s][e.sourceBufferName+"Codec"]===i&&(this.log("Removing level "+s+" for "+e.details+' ("'+i+'" not supported)'),this.hls.removeLevel(s))},t}(F);function It(e){var t={action:0,flags:0};return e&&(t.resolved=!0),t}var Rt="NOT_LOADED",Pt="APPENDING",kt="PARTIAL",Dt="OK",wt=function(){function e(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()}var t=e.prototype;return t._registerListeners=function(){var e=this.hls;e&&(e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this))},t._unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this))},t.destroy=function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){var i=this.activePartLists[t];if(i)for(var r=i.length;r--;){var s=i[r];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){return this.getFragAtPos(e,t,!0)},t.getFragAtPos=function(e,t,i){for(var r=this.fragments,s=Object.keys(r),n=s.length;n--;){var a=r[s[n]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){var o=a.body;if(o.start<=e&&e<=o.end)return o}}return null},t.detectEvictedFragments=function(e,t,i,r,s){var n=this;this.timeRanges&&(this.timeRanges[e]=t);var a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(r){var o=n.fragments[r];if(o&&!(a>=o.body.sn))if(o.buffered||o.loaded&&!s){var l=o.range[e];l&&(0!==l.time.length?l.time.some((function(e){var i=!n.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&n.removeFragment(o.body),i})):n.removeFragment(o.body))}else o.body.type===i&&n.removeFragment(o.body)}))},t.detectPartialFragments=function(e){var t=this,i=this.timeRanges;if(i&&"initSegment"!==e.frag.sn){var r=e.frag,s=Mt(r),n=this.fragments[s];if(!(!n||n.buffered&&r.gap)){var a=!r.relurl;Object.keys(i).forEach((function(s){var o=r.elementaryStreams[s];if(o){var l=i[s],h=a||!0===o.partial;n.range[s]=t.getBufferedTimes(r,e.part,h,l)}})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=r.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ct(n)||this.removeParts(r.sn-1,r.type)):this.removeFragment(n.body)}}},t.removeParts=function(e,t){var i=this.activePartLists[t];i&&(this.activePartLists[t]=Ot(i,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var i=Mt(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)},t.getBufferedTimes=function(e,t,i,r){for(var s={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n,h=0;h<r.length;h++){var u=r.start(h)-this.bufferPadding,d=r.end(h)+this.bufferPadding;if(l>=u&&o<=d){s.time.push({startPTS:Math.max(n,r.start(h)),endPTS:Math.min(a,r.end(h))});break}if(n<d&&a>u){var c=Math.max(n,r.start(h)),f=Math.min(a,r.end(h));f>c&&(s.partial=!0,s.time.push({startPTS:c,endPTS:f}))}else if(a<=u)break}return s},t.getPartialFragment=function(e){var t,i,r,s=null,n=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&Ct(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),n<=t&&(s=h.body,n=t)))})),s},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Ct(t))},t.getState=function(e){var t=Mt(e),i=this.fragments[t];return i?i.buffered?Ct(i)?kt:Dt:Pt:Rt},t.isTimeBuffered=function(e,t,i){for(var r,s,n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var i=t.frag,r=t.part?null:t,s=Mt(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var i=t.frag,r=t.part,s=t.timeRanges,n=t.type;if("initSegment"!==i.sn){var a=i.type;if(r){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=s;var l=s[n];this.detectEvictedFragments(n,l,a,r)}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Mt(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,i=Object.keys(t);if(!e)return i.length>0;for(var r=i.length;r--;){var s=t[i[r]];if((null==s?void 0:s.body.type)===e)return!0}return!1},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.removeFragmentsInRange=function(e,t,i,r,s){var n=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=n.fragments[a];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||s)&&n.removeFragment(l)}}))},t.removeFragment=function(e){var t=Mt(e);e.clearElementaryStreamInfo();var i=this.activePartLists[e.type];if(i){var r=e.sn;this.activePartLists[e.type]=Ot(i,(function(e){return e.fragment.sn!==r}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function Ct(e){var t,i,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(r=e.range.audiovideo)&&r.partial)}function Mt(e){return e.type+"_"+e.level+"_"+e.sn}function Ot(e,t){return e.filter((function(e){var i=t(e);return i||e.clearElementaryStreamInfo(),i}))}var xt=function(){function e(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}return e.prototype.decrypt=function(e,t){switch(this.aesMode){case 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},e}(),Ft=function(){function e(){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()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),i=new Uint32Array(4),r=0;r<4;r++)i[r]=t.getUint32(4*r);return i},t.initTable=function(){var e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],u=o[2],d=o[3],c=new Uint32Array(256),f=0,g=0,p=0;for(p=0;p<256;p++)c[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^255&v^99,e[f]=v,t[v]=f;var m=c[f],y=c[m],E=c[y],S=257*c[v]^16843008*v;r[f]=S<<24|S>>>8,s[f]=S<<16|S>>>16,n[f]=S<<8|S>>>24,a[f]=S,S=16843009*E^65537*y^257*m^16843008*f,l[v]=S<<24|S>>>8,h[v]=S<<16|S>>>16,u[v]=S<<8|S>>>24,d[v]=S,f?(f=m^c[c[c[E^m]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;r<t.length&&i;)i=t[r]===this.key[r],r++;if(!i){this.key=t;var s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);var n,a,o,l,h=this.ksRows=4*(s+6+1),u=this.keySchedule=new Uint32Array(h),d=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,p=g[0],v=g[1],m=g[2],y=g[3];for(n=0;n<h;n++)n<s?o=u[n]=t[n]:(l=o,n%s==0?(l=c[(l=l<<8|l>>>24)>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l],l^=f[n/s|0]<<24):s>6&&n%s==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),u[n]=o=(u[n-s]^l)>>>0);for(a=0;a<h;a++)n=h-a,l=3&a?u[n]:u[n-4],d[a]=a<4||n<=4?l:p[c[l>>>24]]^v[c[l>>>16&255]]^m[c[l>>>8&255]]^y[c[255&l]],d[a]=d[a]>>>0}},t.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},t.decrypt=function(e,t,i){for(var r,s,n,a,o,l,h,u,d,c,f,g,p,v,m=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,S=this.invSubMix,T=S[0],_=S[1],L=S[2],b=S[3],A=this.uint8ArrayToUint32Array_(i),I=A[0],R=A[1],P=A[2],k=A[3],D=new Int32Array(e),w=new Int32Array(D.length),C=this.networkToHostOrderSwap;t<D.length;){for(d=C(D[t]),c=C(D[t+1]),f=C(D[t+2]),g=C(D[t+3]),o=d^y[0],l=g^y[1],h=f^y[2],u=c^y[3],p=4,v=1;v<m;v++)r=T[o>>>24]^_[l>>16&255]^L[h>>8&255]^b[255&u]^y[p],s=T[l>>>24]^_[h>>16&255]^L[u>>8&255]^b[255&o]^y[p+1],n=T[h>>>24]^_[u>>16&255]^L[o>>8&255]^b[255&l]^y[p+2],a=T[u>>>24]^_[o>>16&255]^L[l>>8&255]^b[255&h]^y[p+3],o=r,l=s,h=n,u=a,p+=4;r=E[o>>>24]<<24^E[l>>16&255]<<16^E[h>>8&255]<<8^E[255&u]^y[p],s=E[l>>>24]<<24^E[h>>16&255]<<16^E[u>>8&255]<<8^E[255&o]^y[p+1],n=E[h>>>24]<<24^E[u>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[p+2],a=E[u>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&h]^y[p+3],w[t]=C(r^I),w[t+1]=C(a^R),w[t+2]=C(n^P),w[t+3]=C(s^k),I=d,R=c,P=f,k=g,t+=4}return w.buffer},e}(),Nt=function(){function e(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}return e.prototype.expandKey=function(){var e=function(e){switch(e){case 0:return"AES-CBC";case 1:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode "+e)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])},e}(),Bt=function(){function e(e,t){var i=(void 0===t?{}:t).removePKCS7Padding,r=void 0===i||i;if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=r,r)try{var s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}var t=e.prototype;return t.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},t.isSync=function(){return this.useSoftware},t.flush=function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var i,r,s,n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(s=(r=(i=n).byteLength)&&new DataView(i.buffer).getUint8(r-1))?i.slice(0,r-s):i:n},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,i,r){var s=this;return this.useSoftware?new Promise((function(n,a){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);s.softwareDecrypt(o,t,i,r);var l=s.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)},t.softwareDecrypt=function(e,t,i,r){var s=this.currentIV,n=this.currentResult,a=this.remainderData;if(0!==r||16!==t.byteLength)return V.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Te(a,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;s&&(i=s);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ft),l.expandKey(t);var h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null},t.webCryptoDecrypt=function(e,t,i,r){var s=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Nt(this.subtle,t,r)}return this.fastAesKey.expandKey().then((function(t){return s.subtle?(s.logOnce("WebCrypto AES decrypt"),new xt(s.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(n){return V.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+n.name+": "+n.message),s.onWebCryptoError(e,t,i,r)}))},t.onWebCryptoError=function(e,t,i,r){var s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);var n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")},t.getValidChunk=function(e){var t=e,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t},t.logOnce=function(e){this.logEnabled&&(V.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),Ut=Math.pow(2,17),Gt=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t){var i=this,r=e.url;if(!r)return Promise.reject(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,n=s.fLoader,a=s.loader;return new Promise((function(o,l){if(i.loader&&i.loader.destroy(),e.gap){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void l(Kt(e));e.gap=!1}var h=i.loader=n?new n(s):new a(s),d=Ht(e);e.loader=h;var c=_t(s.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Ut};e.stats=h.stats;var g={onSuccess:function(t,r,s,n){i.resetLoader(e,h);var a=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:n})},onError:function(t,s,n,a){i.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:u({url:r,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:n,stats:a}))},onAbort:function(t,r,s){i.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:function(t,r,s){i.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:s,stats:t}))}};t&&(g.onProgress=function(i,r,s,n){return t({frag:e,part:null,payload:s,networkDetails:n})}),h.load(d,f,g)}))},t.loadPart=function(e,t,i){var r=this;this.abort();var s=this.config,n=s.fLoader,a=s.loader;return new Promise((function(o,l){if(r.loader&&r.loader.destroy(),e.gap||t.gap)l(Kt(e,t));else{var h=r.loader=n?new n(s):new a(s),d=Ht(e,t);e.loader=h;var c=_t(s.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ut};t.stats=h.stats,h.load(d,f,{onSuccess:function(s,n,a,l){r.resetLoader(e,h),r.updateStatsFromPart(e,t);var u={frag:e,part:t,payload:s.data,networkDetails:l};i(u),o(u)},onError:function(i,s,n,a){r.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:u({url:d.url,data:void 0},i),error:new Error("HTTP Error "+i.code+" "+i.text),networkDetails:n,stats:a}))},onAbort:function(i,s,n){e.stats.aborted=t.stats.aborted,r.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:n,stats:i}))},onTimeout:function(i,s,n){r.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:i}))}})}}))},t.updateStatsFromPart=function(e,t){var i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){var n=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/s),n),o=(n-a)*Math.round(i.loaded/a);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,h=r.loading;l.start?l.first+=h.first-h.start:(l.start=h.start,l.first=h.first),l.end=h.end},t.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function Ht(e,t){void 0===t&&(t=null);var i,r=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(T(n)&&T(a)){var o,l=n,h=a;if("initSegment"===e.sn&&("AES-128"===(i=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===i)){var u=a-n;u%16&&(h=a+(16-u%16)),0!==n&&(s.resetIV=!0,l=n-16)}s.rangeStart=l,s.rangeEnd=h}return s}function Kt(e,t){var i=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),r={type:b.MEDIA_ERROR,details:A.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Vt(r)}var Vt=function(e){function t(t){var i;return(i=e.call(this,t.error.message)||this).data=void 0,i.data=t,i}return o(t,e),t}(f(Error)),$t=function(e){function t(t,i){var r;return(r=e.call(this,t,i)||this)._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(r),r}o(t,e);var i=t.prototype;return i.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},i.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},i.onHandlerDestroyed=function(){},i.hasInterval=function(){return!!this._tickInterval},i.hasNextTick=function(){return!!this._tickTimer},i.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},i.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},i.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},i.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},i.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},i.doTick=function(){},t}(F),Wt=function(e,t,i,r,s,n){void 0===r&&(r=0),void 0===s&&(s=-1),void 0===n&&(n=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=n},qt={length:0,start:function(){return 0},end:function(){return 0}},jt=function(){function e(){}return e.isBuffered=function(t,i){if(t)for(var r=e.getBuffered(t),s=r.length;s--;)if(i>=r.start(s)&&i<=r.end(s))return!0;return!1},e.bufferedRanges=function(t){if(t){var i=e.getBuffered(t);return e.timeRangesToArray(i)}return[]},e.timeRangesToArray=function(e){for(var t=[],i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t},e.bufferInfo=function(t,i,r){if(t){var s=e.bufferedRanges(t);if(s.length)return e.bufferedInfo(s,i,r)}return{len:0,start:i,end:i,bufferedIndex:-1}},e.bufferedInfo=function(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var r=-1,s=[];if(i)for(var n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(r=n);var a=s.length;if(a){var o=s[a-1].end;e[n].start-o<i?e[n].end>o&&(s[a-1].end=e[n].end):s.push(e[n])}else s.push(e[n])}else s=e;for(var l,h=0,u=t,d=t,c=0;c<s.length;c++){var f=s[c].start,g=s[c].end;if(-1===r&&t>=f&&t<=g&&(r=c),t+i>=f&&t<g)u=f,h=(d=g)-t;else if(t+i<f){l=f;break}}return{len:h,start:u||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:r}},e.getBuffered=function(e){try{return e.buffered||qt}catch(e){return V.log("failed to get media.buffered",e),qt}},e}(),Yt=/\{\$([a-zA-Z0-9-_]+)\}/g;function zt(e){return Yt.test(e)}function Xt(e,t){if(null!==e.variableList||e.hasVariableRefs){var i=e.variableList;return t.replace(Yt,(function(t){var r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+r+'"')),t):s}))}return t}function Qt(e,t,i){var r,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{var a=new self.URL(i).searchParams;if(!a.has(r))throw new Error('"'+r+'" does not match any query parameter in URI: "'+i+'"');s=a.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+t.message))}}else r=t.NAME,s=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+r+'"')):n[r]=s||""}function Jt(e,t,i){var r=t.IMPORT;if(i&&r in i){var s=e.variableList;s||(e.variableList=s={}),s[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+r+'"'))}var Zt=/^(\d+)x(\d+)$/,ei=/(.+?)=(".*?"|.*?)(?:,|$)/g,ti=function(){function e(t,i){"string"==typeof t&&(t=e.parseAttrList(t,i)),n(this,t)}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var i=new Uint8Array(t.length/2),r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(2*r,2*r+2),16);return i}return null},t.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var i=this[e];return i?parseFloat(i):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((function(e,t){return e[t.toLowerCase()]=!0,e}),t)},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=Zt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var i,r={};for(ei.lastIndex=0;null!==(i=ei.exec(e));){var s=i[1].trim(),n=i[2],a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1,o=!1;if(a)n=n.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=Xt(t,n);else if(!o&&!a)switch(s){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":V.warn(e+": attribute "+s+" is missing quotes")}r[s]=n}return r},r(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function ii(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var ri=r((function(e,t,i){var r;if(void 0===i&&(i=0),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:i,t){var s=t.attr;for(var a in s)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==s[a]){V.warn('DATERANGE tag attribute: "'+a+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=a;break}e=n(new ti({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){var o=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);T(o.getTime())&&(this._endDate=o)}}),[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(V.warn('Expected tagAnchor Fragment with PDT set for DateRange "'+this.id+'": '+e),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(T(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&T(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}]),si=function(){function e(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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}var t=e.prototype;return t.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var 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||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1},t.hasKey=function(e){return this.encryptedFragments.some((function(t){var i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)}))},r(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&T(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function ni(e,t){return e.length===t.length&&!e.some((function(e,i){return e!==t[i]}))}function ai(e,t){return!e&&!t||!(!e||!t)&&ni(e,t)}function oi(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function li(e){switch(e){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw new Error("invalid full segment method "+e)}}function hi(e){return Uint8Array.from(atob(e),(function(e){return e.charCodeAt(0)}))}function ui(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}function di(e){var t=function(e,t,i){var r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}var ci="undefined"!=typeof self?self:void 0,fi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},gi="org.w3.clearkey",pi="com.apple.streamingkeydelivery",vi="com.microsoft.playready",mi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function yi(e){switch(e){case pi:return fi.FAIRPLAY;case vi:return fi.PLAYREADY;case mi:return fi.WIDEVINE;case gi:return fi.CLEARKEY}}function Ei(e){switch(e){case fi.FAIRPLAY:return pi;case fi.PLAYREADY:return vi;case fi.WIDEVINE:return mi;case fi.CLEARKEY:return gi}}function Si(e){var t=e.drmSystems,i=e.widevineLicenseUrl,r=t?[fi.FAIRPLAY,fi.WIDEVINE,fi.PLAYREADY,fi.CLEARKEY].filter((function(e){return!!t[e]})):[];return!r[fi.WIDEVINE]&&i&&r.push(fi.WIDEVINE),r}var Ti,_i=null!=ci&&null!=(Ti=ci.navigator)&&Ti.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null,Li={},bi=function(){function e(e,t,i,r,s,n){void 0===r&&(r=[1]),void 0===s&&(s=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!oi(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(Y(n)))}e.clearKeyUriToKeyIdMap=function(){Li={}},e.setKeyIdForUri=function(e,t){Li[e]=t};var t=e.prototype;return t.matches=function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ni(e.keyFormatVersions,this.keyFormatVersions)&&ai(e.iv,this.iv)&&ai(e.keyId,this.keyId)},t.isSupported=function(){if(this.method){if(oi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case pi:case mi:case vi:case gi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},t.getDecryptData=function(t){if(!this.encrypted||!this.uri)return null;if(oi(this.method)){var i=this.iv;return i||("number"!=typeof t&&(V.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0),i=function(e){for(var t=new Uint8Array(16),i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.pssh&&this.keyId)return this;var r=function(e){var t,i,r=e.split(":"),s=null;if("data"===r[0]&&2===r.length){var n=r[1].split(";"),a=n[n.length-1].split(",");if(2===a.length){var o="base64"===a[0],l=a[1];o?(n.splice(-1,1),s=hi(l)):(t=ui(l).subarray(0,16),(i=new Uint8Array(16)).set(t,16-t.length),s=i)}}return s}(this.uri);if(r)switch(this.keyFormat){case mi:if(this.pssh=r,!this.keyId){var s=function(e){var t=[];if(e instanceof ArrayBuffer)for(var i=e.byteLength,r=0;r+32<i;){var s=Re(new DataView(e,r));t.push(s),r+=s.size}return t}(r.buffer);if(s.length){var n,a=s[0];this.keyId=null!=(n=a.kids)&&n.length?a.kids[0]:null}}if(!this.keyId){var o=r.length-22;this.keyId=r.subarray(o,o+16)}break;case vi:var l=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");var r,s;r=new Uint8Array,s=new Uint8Array;var n=new Uint8Array(4);return i.byteLength>0&&new DataView(n.buffer).setUint32(0,i.byteLength,!1),function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var s=i.length,n=8,a=s;a--;)n+=i[a].byteLength;var o=new Uint8Array(n);for(o[0]=n>>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=255&n,o.set(e,4),a=0,n=8;a<s;a++)o.set(i[a],n),n+=i[a].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,s,r,n,i)}(l,0,r),this.keyId=function(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),s=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){var n=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(n){var a=hi(n).subarray(0,16);return di(a),a}}return null}(r);break;default:var h=r.subarray(0,16);if(16!==h.length){var u=new Uint8Array(16);u.set(h,16-h.length),h=u}this.keyId=h}if(!this.keyId||16!==this.keyId.byteLength){var d=Li[this.uri];if(!d){var c=Object.keys(Li).length%Number.MAX_SAFE_INTEGER;d=new Uint8Array(16),new DataView(d.buffer,12,4).setUint32(0,c),e.setKeyIdForUri(this.uri,d)}this.keyId=d}return this},e}(),Ai=/#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,Ii=/#EXT-X-MEDIA:(.*)/g,Ri=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ki=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|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("|")),Di=function(){function e(){}return e.findGroup=function(e,t){for(var i=0;i<e.length;i++){var r=e[i];if(r.id===t)return r}},e.resolve=function(e,t){return S.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.isMediaPlaylist=function(e){return Ri.test(e)},e.parseMasterPlaylist=function(t,i){var r,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:zt(t)},n=[];if(Ai.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;for(;null!=(r=Ai.exec(t));)if(r[1]){var a,o=new ti(r[1],s),l=Xt(s,r[2]),h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,i)},u=o.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),xi(o.CODECS,h);var d=o["SUPPLEMENTAL-CODECS"];d&&(h.supplemental={},xi(d,h.supplemental)),null!=(a=h.unknownCodecs)&&a.length||n.push(h),s.levels.push(h)}else if(r[3]){var c=r[3],f=r[4];switch(c){case"SESSION-DATA":var g=new ti(f,s),p=g["DATA-ID"];p&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[p]=g);break;case"SESSION-KEY":var v=Mi(f,i,s);v.encrypted&&v.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(v)):V.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+f+'"');break;case"DEFINE":Qt(s,new ti(f,s),i);break;case"CONTENT-STEERING":var m=new ti(f,s);s.contentSteering={uri:e.resolve(m["SERVER-URI"],i),pathwayId:m["PATHWAY-ID"]||"."};break;case"START":s.startTimeOffset=Oi(f)}}var y=n.length>0&&n.length<s.levels.length;return s.levels=y?n:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s},e.parseMasterPlaylistMedia=function(t,i,r){var s,n={},a=r.levels,o={AUDIO:a.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),SUBTITLES:a.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),"CLOSED-CAPTIONS":[]},l=0;for(Ii.lastIndex=0;null!==(s=Ii.exec(t));){var h=new ti(s[1],r),u=h.TYPE;if(u){var d=o[u],c=n[u]||[];n[u]=c;var f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],p=h.CHANNELS,v=h.CHARACTERISTICS,m=h["INSTREAM-ID"],y={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:u,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?e.resolve(h.URI,i):""};if(g&&(y.assocLang=g),p&&(y.channels=p),v&&(y.characteristics=v),m&&(y.instreamId=m),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Fi(y,E,"audioCodec"),Fi(y,E,"textCodec")}c.push(y)}}return n},e.parseLevelPlaylist=function(e,t,i,r,s,a){var o,l,h,u,d,c={url:t},f=new si(t),g=f.fragments,p=[],v=null,m=0,y=0,E=0,S=0,_=0,L=null,b=new te(r,c),A=-1,I=!1,R=null;if(Pi.lastIndex=0,f.m3u8=e,f.hasVariableRefs=zt(e),"#EXTM3U"!==(null==(o=Pi.exec(e))?void 0:o[0]))return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;null!==(l=Pi.exec(e));){I&&(I=!1,(b=new te(r,c)).playlistOffset=E,b.setStart(E),b.sn=m,b.cc=S,_&&(b.bitrate=_),b.level=i,v&&(b.initSegment=v,v.rawProgramDateTime&&(b.rawProgramDateTime=v.rawProgramDateTime,v.rawProgramDateTime=null),R&&(b.setByteRange(R),R=null)));var P=l[1];if(P){b.duration=parseFloat(P);var k=(" "+l[2]).slice(1);b.title=k||null,b.tagList.push(k?["INF",P,k]:["INF",P])}else if(l[3]){if(T(b.duration)){b.playlistOffset=E,b.setStart(E),u&&Ui(b,u,f),b.sn=m,b.level=i,b.cc=S,g.push(b);var D=(" "+l[3]).slice(1);b.relurl=Xt(f,D),Ni(b,L,p),L=b,E+=b.duration,m++,y=0,I=!0}}else{if(!(l=l[0].match(ki))){V.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);var w=(" "+l[h]).slice(1),C=(" "+l[h+1]).slice(1),M=l[h+2]?(" "+l[h+2]).slice(1):null;switch(w){case"BYTERANGE":L?b.setByteRange(C,L):b.setByteRange(C);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=C,b.tagList.push(["PROGRAM-DATE-TIME",C]),-1===A&&(A=g.length);break;case"PLAYLIST-TYPE":f.type&&Gi(f,w,l),f.type=C.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?Gi(f,w,l):g.length>0&&Hi(f,w,l),m=f.startSN=parseInt(C);break;case"SKIP":f.skippedSegments&&Gi(f,w,l);var O=new ti(C,f),x=O.decimalInteger("SKIPPED-SEGMENTS");if(T(x)){f.skippedSegments+=x;for(var F=x;F--;)g.push(null);m+=x}var N=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");N&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(N.split("\t")));break;case"TARGETDURATION":0!==f.targetduration&&Gi(f,w,l),f.targetduration=Math.max(parseInt(C),1);break;case"VERSION":null!==f.version&&Gi(f,w,l),f.version=parseInt(C);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":f.live||Gi(f,w,l),f.live=!1;break;case"#":(C||M)&&b.tagList.push(M?[C,M]:[C]);break;case"DISCONTINUITY":S++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([w]);break;case"BITRATE":b.tagList.push([w,C]),_=1e3*parseInt(C),T(_)?b.bitrate=_:_=0;break;case"DATERANGE":var B=new ti(C,f),U=new ri(B,f.dateRanges[B.ID],f.dateRangeTagCount);f.dateRangeTagCount++,U.isValid||f.skippedSegments?f.dateRanges[U.id]=U:V.warn('Ignoring invalid DATERANGE tag: "'+C+'"'),b.tagList.push(["EXT-X-DATERANGE",C]);break;case"DEFINE":var G=new ti(C,f);"IMPORT"in G?Jt(f,G,a):Qt(f,G,t);break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?Gi(f,w,l):g.length>0&&Hi(f,w,l),f.startCC=S=parseInt(C);break;case"KEY":var H=Mi(C,t,f);if(H.isSupported()){if("NONE"===H.method){u=void 0;break}u||(u={});var K=u[H.keyFormat];null!=K&&K.matches(H)||(K&&(u=n({},u)),u[H.keyFormat]=H)}else V.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'+C+'"');break;case"START":f.startTimeOffset=Oi(C);break;case"MAP":var $=new ti(C,f);if(b.duration){var W=new te(r,c);Bi(W,$,i,u),v=W,b.initSegment=v,v.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=v.rawProgramDateTime)}else{var q=b.byteRangeEndOffset;if(q){var j=b.byteRangeStartOffset;R=q-j+"@"+j}else R=null;Bi(b,$,i,u),v=b,I=!0}v.cc=S;break;case"SERVER-CONTROL":d&&Gi(f,w,l),d=new ti(C),f.canBlockReload=d.bool("CAN-BLOCK-RELOAD"),f.canSkipUntil=d.optionalFloat("CAN-SKIP-UNTIL",0),f.canSkipDateRanges=f.canSkipUntil>0&&d.bool("CAN-SKIP-DATERANGES"),f.partHoldBack=d.optionalFloat("PART-HOLD-BACK",0),f.holdBack=d.optionalFloat("HOLD-BACK",0);break;case"PART-INF":f.partTarget&&Gi(f,w,l);var Y=new ti(C);f.partTarget=Y.decimalFloatingPoint("PART-TARGET");break;case"PART":var z=f.partList;z||(z=f.partList=[]);var X=y>0?z[z.length-1]:void 0,Q=y++,J=new ti(C,f),Z=new ie(J,b,c,Q,X);z.push(Z),b.duration+=Z.duration;break;case"PRELOAD-HINT":var ee=new ti(C,f);f.preloadHint=ee;break;case"RENDITION-REPORT":var re=new ti(C,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(re);break;default:V.warn("line parsed but not handled: "+l)}}}L&&!L.relurl?(g.pop(),E-=L.duration,f.partList&&(f.fragmentHint=L)):f.partList&&(Ni(b,L,p),b.cc=S,f.fragmentHint=b,u&&Ui(b,u,f)),f.targetduration||(f.playlistParsingError=new Error("Missing Target Duration"));var se=g.length,ne=g[0],ae=g[se-1];if((E+=f.skippedSegments*f.targetduration)>0&&se&&ae){f.averagetargetduration=E/se;var oe=ae.sn;f.endSN="initSegment"!==oe?oe:0,f.live||(ae.endList=!0),A>0&&(function(e,t){for(var i=e[t],r=t;r--;){var s=e[r];if(!s)return;s.programDateTime=i.programDateTime-1e3*s.duration,i=s}}(g,A),ne&&p.unshift(ne))}return f.fragmentHint&&(E+=f.fragmentHint.duration),f.totalduration=E,p.length&&f.dateRangeTagCount&&ne&&wi(p,f),f.endCC=S,f},e}();function wi(e,t){var i=e.length;if(!i){if(!t.hasProgramDateTime)return;var r=t.fragments[t.fragments.length-1];e.push(r),i++}for(var s=e[i-1],n=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges),o=a.length;o--;){var l=t.dateRanges[a[o]],h=l.startDate.getTime();l.tagAnchor=s.ref;for(var u=i;u--;){var d;if((null==(d=e[u])?void 0:d.sn)<t.startSN)break;var c=Ci(t,h,e,u,n);if(-1!==c){l.tagAnchor=t.fragments[c].ref;break}}}}function Ci(e,t,i,r,s){var n=i[r];if(n){var a,o=n.programDateTime;if((t>=o||0===r)&&t<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||s)-n.start)){var l=i[r].sn-e.startSN;if(l<0)return-1;var h=e.fragments;if(h.length>i.length)for(var u=(i[r+1]||h[h.length-1]).sn-e.startSN;u>l;u--){var d=h[u].programDateTime;if(t>=d&&t<d+1e3*h[u].duration)return u}return l}}return-1}function Mi(e,t,i){var r,s,n=new ti(e,i),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,u=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&V.error("Invalid IV: "+n.IV);var d=o?Di.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new bi(a,d,u,c,l,n.KEYID)}function Oi(e){var t=new ti(e).decimalFloatingPoint("TIME-OFFSET");return T(t)?t:null}function xi(e,t){var i=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var r=i.filter((function(t){return De(t,e)}));r.length&&(t[e+"Codec"]=r.map((function(e){return e.split("/")[0]})).join(","),i=i.filter((function(e){return-1===r.indexOf(e)})))})),t.unknownCodecs=i}function Fi(e,t,i){var r=t[i];r&&(e[i]=r)}function Ni(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Bi(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function Ui(e,t,i){e.levelkeys=t;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||r.push(e)}function Gi(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must not appear more than once ("+i[0]+")")}function Hi(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must appear before the first Media Segment ("+i[0]+")")}function Ki(e,t){var i=t.startPTS;if(T(i)){var r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&r.setDuration(s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Vi(e,t,i,r,s,n,a){r-i<=0&&(a.warn("Fragment should have a positive duration",t),r=i+t.duration,n=s+t.duration);var o=i,l=r,h=t.startPTS,u=t.endPTS;if(T(h)){var d=Math.abs(h-i);e&&d>e.totalduration?a.warn("media timestamps and playlist times differ by "+d+"s for level "+t.level+" "+e.url):T(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,o=Math.max(i,h),i=Math.min(i,h),s=void 0!==t.startDTS?Math.min(s,t.startDTS):s,l=Math.min(r,u),r=Math.max(r,u),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}var c=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=s,t.endPTS=r,t.minEndPTS=l,t.endDTS=n;var f,g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;var p=g-e.startSN,v=e.fragments;for(v[p]=t,f=p;f>0;f--)Ki(v[f],v[f-1]);for(f=p;f<v.length-1;f++)Ki(v[f],v[f+1]);return e.fragmentHint&&Ki(v[v.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function $i(e,t,i){if(e!==t){for(var r,s=null,a=e.fragments,o=a.length-1;o>=0;o--){var l=a[o].initSegment;if(l){s=l;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){for(var r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=s;h<=n;h++){var u=l[a+h],d=o[h];if(r&&!d&&u&&(d=t.fragments[h]=u),u&&d){i(u,d,h,o);var c=u.relurl,f=d.relurl;if(c&&Zi(c,f))return void(t.playlistParsingError=Wi("media sequence mismatch "+d.sn+":",e,t,0,d));if(u.cc!==d.cc)return void(t.playlistParsingError=Wi("discontinuity sequence mismatch ("+u.cc+"!="+d.cc+")",e,t,0,d))}}}(e,t,(function(e,i,n,a){if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){for(var o=e.cc-i.cc,l=n;l<a.length;l++)a[l].cc+=o;t.endCC=a[a.length-1].cc}T(e.startPTS)&&T(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(r=i),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,s=e.initSegment)}));var h=t.fragments,u=t.fragmentHint?h.concat(t.fragmentHint):h;if(s&&u.forEach((function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=s)?void 0:t.relurl)||(e.initSegment=s)})),t.skippedSegments){if(t.deltaUpdateFailed=h.some((function(e){return!e})),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var d=t.skippedSegments;d--;)h.shift();t.startSN=h[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){var r=t.dateRanges,s=t.recentlyRemovedDateranges,a=n({},e);s&&s.forEach((function(e){delete a[e]}));var o=Object.keys(a).length;return o?(Object.keys(r).forEach((function(e){var t=a[e],s=new ri(r[e].attr,t);s.isValid?(a[e]=s,t||(s.tagOrder+=o)):i.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+it(r[e].attr)+'"')})),a):r}(e.dateRanges,t,i));var c=e.fragments.filter((function(e){return e.rawProgramDateTime}));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var f=1;f<u.length;f++)null===u[f].programDateTime&&Ni(u[f],u[f-1],c);wi(c,t)}t.endCC=h[h.length-1].cc}if(!t.startCC){var g,p=zi(e,t.startSN-1);t.startCC=null!=(g=null==p?void 0:p.cc)?g:h[0].cc}!function(e,t,i){if(e&&t)for(var r=0,s=0,n=e.length;s<=n;s++){var a=e[s],o=t[s+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):r--}}(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),r?Vi(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,i):qi(e,t),h.length&&(t.totalduration=t.edge-h[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var v=t.advancedDateTime;if(t.advanced&&v){var m=t.edge;t.driftStart||(t.driftStartTime=v,t.driftStart=m),t.driftEndTime=v,t.driftEnd=m}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Wi(e,t,i,r,s){return new Error(e+" "+s.url+"\nPlaylist starting @"+t.startSN+"\n"+t.m3u8+"\n\nPlaylist starting @"+i.startSN+"\n"+i.m3u8)}function qi(e,t,i){void 0===i&&(i=!0);var r=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,n=r>=0,a=0;if(n&&r<s.length)a=s[r].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}ji(t,a)}function ji(e,t){if(t){for(var i=e.fragments,r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Yi(e,t){void 0===t&&(t=1/0);var i=1e3*e.targetduration;if(e.updated){var r=e.fragments;if(r.length&&4*i>t){var s=1e3*r[r.length-1].duration;s<i&&(i=s)}}else i/=2;return Math.round(i)}function zi(e,t,i){if(!e)return null;var r=e.fragments[t-e.startSN];return r||((r=e.fragmentHint)&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null)}function Xi(e,t,i){return e?Qi(e.partList,t,i):null}function Qi(e,t,i){if(e)for(var r=e.length;r--;){var s=e[r];if(s.index===i&&s.fragment.sn===t)return s}return null}function Ji(e){e.forEach((function(e,t){var i;null==(i=e.details)||i.fragments.forEach((function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function Zi(e,t){return!(e===t||!t)&&er(e)!==er(t)}function er(e){return e.replace(/\?[^?]*$/,"")}function tr(e,t){for(var i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function ir(e,t){var i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function rr(e,t){for(var i=t.fragments,r=0,s=i.length;r<s;r++)ir(i[r],e);t.fragmentHint&&ir(t.fragmentHint,e),t.alignedSliding=!0}function sr(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var i=Math.min(t.endCC,e.endCC),r=tr(t.fragments,i),s=tr(e.fragments,i);r&&s&&(V.log("Aligning playlist at start of dicontinuity sequence "+i),rr(r.start-s.start,e))}}function nr(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i=e.fragments,r=t.fragments;if(i.length&&r.length){var s,n,a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(s=tr(r,a),n=tr(i,a)),s&&n||(n=tr(i,(s=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.length/2)]);var o=s.programDateTime,l=n.programDateTime;o&&l&&rr((l-o)/1e3-(n.start-s.start),e)}}}function ar(e,t,i){or(e,t,i),e.addEventListener(t,i)}function or(e,t,i){e.removeEventListener(t,i)}var lr={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},hr=function(e){function t(t,i,r,s,n){var a;return(a=e.call(this,s,t.logger)||this).hls=void 0,a.fragPrevious=null,a.fragCurrent=null,a.fragmentTracker=void 0,a.transmuxer=null,a._state=lr.STOPPED,a.playlistType=void 0,a.media=null,a.mediaBuffer=null,a.config=void 0,a.bitrateTest=!1,a.lastCurrentTime=0,a.nextLoadPosition=0,a.startPosition=0,a.startTimeOffset=null,a.retryDate=0,a.levels=null,a.fragmentLoader=void 0,a.keyLoader=void 0,a.levelLastLoaded=null,a.startFragRequested=!1,a.decrypter=void 0,a.initPTS=[],a.buffering=!0,a.loadingParts=!1,a.loopSn=void 0,a.onMediaSeeking=function(){var e=a,t=e.config,i=e.fragCurrent,r=e.media,s=e.mediaBuffer,n=e.state,o=r?r.currentTime:0,l=jt.bufferInfo(s||r,o,t.maxBufferHole),h=!l.len;if(a.log("Media seeking to "+(T(o)?o.toFixed(3):o)+", state: "+n+", "+(h?"out of":"in")+" buffer"),a.state===lr.ENDED)a.resetLoadingState();else if(i){var u=t.maxFragLookUpTolerance,d=i.start-u,c=i.start+i.duration+u;if(h||c<l.start||d>l.end){var f=o>c;(o<d||f)&&(f&&i.loader&&(a.log("Cancelling fragment load for seek (sn: "+i.sn+")"),i.abortRequests(),a.resetLoadingState()),a.fragPrevious=null)}}if(r&&(a.fragmentTracker.removeFragmentsInRange(o,1/0,a.playlistType,!0),o>a.lastCurrentTime&&(a.lastCurrentTime=o),!a.loadingParts)){var g=Math.max(l.end,o),p=a.shouldLoadParts(a.getLevelDetails(),g);p&&(a.log("LL-Part loading ON after seeking to "+o.toFixed(2)+" with buffer @"+g.toFixed(2)),a.loadingParts=p)}a.hls.hasEnoughToStart||(a.log("Setting "+(h?"startPosition":"nextLoadPosition")+" to "+o+" for seek without enough to start"),a.nextLoadPosition=o,h&&(a.startPosition=o)),h&&a.state===lr.IDLE&&a.tickImmediate()},a.onMediaEnded=function(){a.log("setting startPosition to 0 because media ended"),a.startPosition=a.lastCurrentTime=0},a.playlistType=n,a.hls=t,a.fragmentLoader=new Gt(t.config),a.keyLoader=r,a.fragmentTracker=i,a.config=t.config,a.decrypter=new Bt(t.config),a}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.ERROR,this.onError,this)},i.doTick=function(){this.onTickEnd()},i.onTickEnd=function(){},i.startLoad=function(e){},i.stopLoad=function(){if(this.state!==lr.STOPPED){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=lr.STOPPED}},i.pauseBuffering=function(){this.buffering=!1},i.resumeBuffering=function(){this.buffering=!0},i._streamEnded=function(e,t){if(t.live||!this.media)return!1;var i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;var s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=jt.bufferedInfo(s,e.start,0));var n=e.nextStart;if(n&&n>r&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var a=t.partList;if(null!=a&&a.length){var o=a[a.length-1];return jt.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)},i.getLevelDetails=function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details},i.onMediaAttached=function(e,t){var i=this.media=this.mediaBuffer=t.media;ar(i,"seeking",this.onMediaSeeking),ar(i,"ended",this.onMediaEnded);var r=this.config;this.levels&&r.autoStartLoad&&this.state===lr.STOPPED&&this.startLoad(r.startPosition)},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),or(r,"seeking",this.onMediaSeeking),or(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},i.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},i.onError=function(e,t){},i.onManifestLoaded=function(e,t){this.startTimeOffset=t.startTimeOffset},i.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),e.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},i.onHandlerDestroyed=function(){this.state=lr.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,e.prototype.onHandlerDestroyed.call(this)},i.loadFragment=function(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)},i._loadFragForPlayback=function(e,t,i){var r=this;this._doFragLoad(e,t,i,(function(e){var t=e.frag;if(r.fragContextChanged(t))return r.warn(t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+r.fragInfo(t,!1,e.part)+") was dropped during download."),void r.fragmentTracker.removeFragment(t);t.stats.chunkCount++,r._handleFragmentLoadProgress(e)})).then((function(e){if(e){var t=r.state,i=e.frag;r.fragContextChanged(i)?(t===lr.FRAG_LOADING||!r.fragCurrent&&t===lr.PARSING)&&(r.fragmentTracker.removeFragment(i),r.state=lr.IDLE):("payload"in e&&(r.log("Loaded "+i.type+" sn: "+i.sn+" of "+r.playlistLabel()+" "+i.level),r.hls.trigger(I.FRAG_LOADED,e)),r._handleFragmentLoadComplete(e))}})).catch((function(t){r.state!==lr.STOPPED&&r.state!==lr.ERROR&&(r.warn("Frag error: "+((null==t?void 0:t.message)||t)),r.resetFragmentLoading(e))}))},i.clearTrackerIfNeeded=function(e){var t,i=this.fragmentTracker;if(i.getState(e)===Pt){var r=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,r),n=Math.max(e.duration,s?s.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?e.sn-a.sn:0)||this.reduceMaxBufferLength(n,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===kt&&i.removeFragment(e))},i.checkLiveUpdate=function(e){if(e.updated&&!e.live){var 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)},i.waitForLive=function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)},i.flushMainBuffer=function(e,t,i){if(void 0===i&&(i=null),e-t){var r={startOffset:e,endOffset:t,type:i};this.hls.trigger(I.BUFFER_FLUSHING,r)}},i._loadInitSegment=function(e,t){var i=this;this._doFragLoad(e,t).then((function(e){var t=null==e?void 0:e.frag;if(!t||i.fragContextChanged(t)||!i.levels)throw new Error("init load aborted");return e})).then((function(e){var t=i.hls,r=e.frag,s=e.payload,n=r.decryptdata;if(s&&s.byteLength>0&&null!=n&&n.key&&n.iv&&oi(n.method)){var a=self.performance.now();return i.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,li(n.method)).catch((function(e){throw t.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e})).then((function(s){var n=self.performance.now();return t.trigger(I.FRAG_DECRYPTED,{frag:r,payload:s,stats:{tstart:a,tdecrypt:n}}),e.payload=s,i.completeInitSegmentLoad(e)}))}return i.completeInitSegmentLoad(e)})).catch((function(t){i.state!==lr.STOPPED&&i.state!==lr.ERROR&&(i.warn(t),i.resetFragmentLoading(e))}))},i.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==lr.STOPPED&&(this.state=lr.IDLE),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()},i.unhandledEncryptionError=function(e,t){var i,r,s=e.tracks;if(s&&!t.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var n=this.media,a=new Error("Encrypted track with no key in "+this.fragInfo(t)+" (media "+(n?"attached mediaKeys: "+n.mediaKeys:"detached")+")");return this.warn(a.message),!(!n||n.mediaKeys||(this.hls.trigger(I.ERROR,{type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,frag:t}),this.resetTransmuxer(),0))}return!1},i.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},i.fragBufferedComplete=function(e,t){var i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+" > buffer:"+(i?function(e){for(var t="",i=e.length,r=0;r<i;r++)t+="["+e.start(r).toFixed(3)+"-"+e.end(r).toFixed(3)+"]";return t}(jt.getBuffered(i)):"(detached)")+")"),ee(e)){var r;if(e.type!==M){var s=e.elementaryStreams;if(!Object.keys(s).some((function(e){return!!s[e]})))return void(this.state=lr.IDLE)}var n=null==(r=this.levels)?void 0:r[e.level];null!=n&&n.fragmentError&&(this.log("Resetting level fragment error count of "+n.fragmentError+" on frag buffered"),n.fragmentError=0)}this.state=lr.IDLE},i._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var i=e.frag,r=e.part,s=e.partsLoaded,n=!s||0===s.length||s.some((function(e){return!e})),a=new Wt(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}},i._handleFragmentLoadProgress=function(e){},i._doFragLoad=function(e,t,i,r){var s,n=this;void 0===i&&(i=null),this.fragCurrent=e;var a=t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var o=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key)e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");else if(this.log("Loading key for "+e.sn+" of ["+a.startSN+"-"+a.endSN+"], "+this.playlistLabel()+" "+e.level),this.state=lr.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(I.KEY_LOADED,e),n.state===lr.KEY_LOADING&&(n.state=lr.IDLE),e})),this.hls.trigger(I.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);var l,h=this.fragPrevious;if(ee(e)&&(!h||e.sn!==h.sn)){var u=this.shouldLoadParts(t.details,e.end);u!==this.loadingParts&&(this.log("LL-Part loading "+(u?"ON":"OFF")+" loading sn "+(null==h?void 0:h.sn)+"->"+e.sn),this.loadingParts=u)}if(i=Math.max(e.start,i||0),this.loadingParts&&ee(e)){var d=a.partList;if(d&&r){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);var c=this.getNextPart(d,e,i);if(c>-1){var f,g=d[c];return e=this.fragCurrent=g.fragment,this.log("Loading "+e.type+" sn: "+e.sn+" part: "+g.index+" ("+c+"/"+(d.length-1)+") of "+this.fragInfo(e,!1,g)+") cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(i.toFixed(3))),this.nextLoadPosition=g.start+g.duration,this.state=lr.FRAG_LOADING,f=o?o.then((function(i){return!i||n.fragContextChanged(i.frag)?null:n.doFragPartsLoad(e,g,t,r)})).catch((function(e){return n.handleFragLoadError(e)})):this.doFragPartsLoad(e,g,t,r).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(I.FRAG_LOADING,{frag:e,part:g,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!e.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}if(ee(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+i.toFixed(2)+" Check buffer at sn: "+e.sn+" loaded parts: "+(null==(l=a.partList)?void 0:l.filter((function(e){return e.loaded})).map((function(e){return"["+e.start+"-"+e.end+"]"})))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log("Loading "+e.type+" sn: "+e.sn+" of "+this.fragInfo(e,!1)+") cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(i.toFixed(3))),T(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=lr.FRAG_LOADING;var p,v=this.config.progressive;return p=v&&o?o.then((function(t){return!t||n.fragContextChanged(t.frag)?null:n.fragmentLoader.load(e,r)})).catch((function(e){return n.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,v?r:void 0),o]).then((function(e){var t=e[0];return!v&&r&&r(t),t})).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):p},i.doFragPartsLoad=function(e,t,i,r){var s=this;return new Promise((function(n,a){var o,l=[],h=null==(o=i.details)?void 0:o.partList,u=function(t){s.fragmentLoader.loadPart(e,t,r).then((function(r){l[t.index]=r;var a=r.part;s.hls.trigger(I.FRAG_LOADED,r);var o=Xi(i.details,e.sn,t.index+1)||Qi(h,e.sn,t.index+1);if(!o)return n({frag:e,part:a,partsLoaded:l});u(o)})).catch(a)};u(t)}))},i.handleFragLoadError=function(e){if("data"in e){var t=e.data;t.frag&&t.details===A.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===b.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(I.ERROR,t)}else this.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},i._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===lr.PARSING){var i=t.frag,r=t.part,s=t.level,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n);var a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+i.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(i,r,s,e.partial)}else this.fragCurrent||this.state===lr.STOPPED||this.state===lr.ERROR||(this.state=lr.IDLE)},i.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i,r,s=e.partList[0];if(s.fragment.type===M)return!1;if(t>=s.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}return!1},i.getCurrentContext=function(e){var t=this.levels,i=this.fragCurrent,r=e.level,s=e.sn,n=e.part;if(null==t||!t[r])return this.warn("Levels object was unset while buffering fragment "+s+" of "+this.playlistLabel()+" "+r+". The current chunk will not be buffered."),null;var a=t[r],o=a.details,l=n>-1?Xi(o,s,n):null,h=l?l.fragment:zi(o,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null},i.bufferFragmentData=function(e,t,i,r,s){if(this.state===lr.PARSING){var n=e.data1,a=e.data2,o=n;if(a&&(o=Te(n,a)),o.length){var l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:i,chunkMeta:r,offset:h,parent:t.type,data:o};if(this.hls.trigger(I.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}}},i.flushBufferGap=function(e){var t=this.media;if(t)if(jt.isBuffered(t,t.currentTime)){var i=t.currentTime,r=jt.bufferInfo(t,i,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,r.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}else this.flushMainBuffer(0,e.start)},i.getFwdBufferInfo=function(e,t){var i,r=this.getLoadPosition();if(!T(r))return null;var s=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,s)},i.getFwdBufferInfoAtPos=function(e,t,i,r){var s=jt.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){var n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(s.nextStart<=n.end||n.gap)){var a=Math.max(Math.min(s.nextStart,n.end)-t,r);return jt.bufferInfo(e,t,a)}}return s},i.getMaxBufferLength=function(e){var t,i=this.config;return t=e?Math.max(8*i.maxBufferSize/e,i.maxBufferLength):i.maxBufferLength,Math.min(t,i.maxMaxBufferLength)},i.reduceMaxBufferLength=function(e,t){var i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn("Reduce max buffer length to "+s+"s"),!0)},i.getAppendedFrag=function(e,t){void 0===t&&(t=w);var i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i},i.getNextFragment=function(e,t){var i=t.fragments,r=i.length;if(!r)return null;var s=this.config,n=i[0].start,a=s.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=s.initialLiveManifestSize;if(r<l)return this.warn("Not enough fragments to start playback (have: "+r+", need: "+l+")"),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var h;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);var u=this.hls.startPosition,d=this.hls.liveSyncPosition,c=o?(-1!==u&&u>=n?u:d)||o.start:e;this.log("Setting startPosition to "+c+" to match start frag at live edge. mainStart: "+u+" liveSyncPosition: "+d+" frag.start: "+(null==(h=o)?void 0:h.start)),this.startPosition=this.nextLoadPosition=c}}else e<=n&&(o=i[0]);if(!o){var f=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,f,t)}var g=this.filterReplacedPrimary(o,t);if(!g&&o){var p=o.sn-t.startSN;g=this.filterReplacedPrimary(i[p+1]||null,t)}return this.mapToInitFragWhenRequired(g)},i.isLoopLoading=function(e,t){var i=this.fragmentTracker.getState(e);return(i===Dt||i===kt&&!!e.gap)&&this.nextLoadPosition>t},i.getNextFragmentLoopLoading=function(e,t,i,r,s){var n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t))&&!n.gap&&i.nextStart){var a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==a&&i.len+a.len>=s){var o=n.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+r+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,n},i.filterReplacedPrimary=function(e,t){if(!e)return e;if(ur(this.config)&&e.type!==M){var i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){var s=r.event;if(s){if(s.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}var n=null==i?void 0:i.playerQueue;if(n)for(var a=n.length;a--;){var o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e},i.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment},i.getNextPart=function(e,t,i){for(var r=-1,s=!1,n=!0,a=0,o=e.length;a<o;a++){var l=e[a];if(n=n&&!l.independent,r>-1&&i<l.start)break;var h=l.loaded;h?r=-1:(s||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn("Need buffer at "+i+" but next unloaded part starts at "+l.start),r=a),s=h}return r},i.loadedEndOfParts=function(e,t){for(var i,r=e.length;r--;){if(!(i=e[r]).loaded)return!1;if(t>i.start)return!0}return!1},i.getInitialLiveFragment=function(e){var t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+i.programDateTime),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!T(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var r=0;r<e.length;++r){var s=e[r];if(pt(t,i,s))return s}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){var n=t[s-e.startSN];i.cc===n.cc&&(r=n,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=vt(e,i.cc,i.end))&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn)}}else{var a=this.hls.liveSyncPosition;null!==a&&(r=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r},i.getFragmentAtPosition=function(e,t,i){var r,s,n=this.config,a=this.fragPrevious,o=i.fragments,l=i.endSN,h=i.fragmentHint,u=n.maxFragLookUpTolerance,d=i.partList,c=!!(this.loadingParts&&null!=d&&d.length&&h);if(c&&!this.bitrateTest&&d[d.length-1].fragment.sn===h.sn&&(o=o.concat(h),l=h.sn),r=e<t?ft(a,o,e,e<this.lastCurrentTime||e>t-u||null!=(s=this.media)&&s.paused||!this.startFragRequested?0:u):o[o.length-1]){var f=r.sn-i.startSN,g=this.fragmentTracker.getState(r);if((g===Dt||g===kt&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!c||d[0].fragment.sn>r.sn||!i.live)&&r.level===a.level){var p=o[f+1];r=r.sn<l&&this.fragmentTracker.getState(p)!==Dt?p:null}}return r},i.alignPlaylists=function(e,t,i){var r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;var s=e.fragmentStart,n=!t,a=e.alignedSliding&&T(s);if(n||!a&&!s){!function(e,t){e&&(sr(t,e),t.alignedSliding||nr(t,e),t.alignedSliding||t.skippedSegments||qi(e,t,!1))}(i,e);var o=e.fragmentStart;return this.log("Live playlist sliding: "+o.toFixed(2)+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" fragments: "+r),o}return s},i.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},i.setStartPosition=function(e,t){var i=this.startPosition;i<t&&(i=-1);var r=this.timelineOffset;if(-1===i){var s=null!==this.startTimeOffset,n=s?this.startTimeOffset:e.startTimeOffset;null!==n&&T(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log("Setting startPosition to "+i+" for start time offset "+n+" found in "+(s?"multivariant":"media")+" playlist"),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge "+i),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r},i.getLoadPosition=function(){var e,t=this.media,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i},i.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&ee(e)&&e.stats.aborted&&(this.log("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},i.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===lr.FRAG_LOADING_WAITING_RETRY)||(this.state=lr.IDLE)},i.onFragmentOrKeyLoadError=function(e,t){var i;if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var s=t.frag;if(s&&s.type===e&&this.levels)if(this.fragContextChanged(s)){var n;this.warn("Frag load error must match current frag to retry "+s.url+" > "+(null==(n=this.fragCurrent)?void 0:n.url))}else{var a=t.details===A.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);var o=t.errorAction;if(o){var l=o.action,h=o.flags,u=o.retryCount,d=void 0===u?0:u,c=o.retryConfig,f=!!c,g=f&&5===l,p=f&&!o.resolved&&1===h,v=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!g&&p&&ee(s)&&!s.endList&&v&&!Et(t))this.resetFragmentErrors(e),this.treatAsGap(s),o.resolved=!0;else if((g||p)&&d<c.maxNumRetry){var m,y=bt(null==(m=t.response)?void 0:m.code),E=Tt(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=lr.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,y)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment "+s.sn+" of "+e+" "+s.level+" errored with "+t.details+", retrying loading "+(d+1)+"/"+c.maxNumRetry+" in "+E+"ms")}else if(c){if(this.resetFragmentErrors(e),!(d<c.maxNumRetry))return void this.warn(t.details+" reached or exceeded max retry ("+d+")");a||3===l||(o.resolved=!0)}else this.state=2===l?lr.WAITING_LEVEL:lr.ERROR;this.tickImmediate()}else this.state=lr.ERROR}},i.checkRetryDate=function(){var e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!bt(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=lr.IDLE)},i.reduceLengthAndFlushBuffer=function(e){if(this.state===lr.PARSING||this.state===lr.PARSED){var t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);var n=!s;return n&&this.warn("Buffer full error while media.currentTime ("+this.getLoadPosition()+") is not buffered, flush "+i+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1},i.resetFragmentErrors=function(e){e===C&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==lr.STOPPED&&(this.state=lr.IDLE)},i.afterBufferFlushed=function(e,t,i){if(e){var r=jt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===lr.ENDED&&this.resetLoadingState()}},i.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==lr.STOPPED&&(this.state=lr.IDLE)},i.resetStartWhenNotLoaded=function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},i.resetWhenMissingContext=function(e){this.log("Loading context changed while buffering sn "+e.sn+" of "+this.playlistLabel()+" "+(-1===e.level?"<removed>":e.level)+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()},i.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},i.updateLevelTiming=function(e,t,i,r){var s=this,n=i.details;if(n){var a;if(!Object.keys(e.elementaryStreams).reduce((function(t,a){var o=e.elementaryStreams[a];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return s.warn("Could not parse fragment "+e.sn+" "+a+" duration reliably ("+l+")"),t||!1;var h=r?0:Vi(n,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,s);return s.hls.trigger(I.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(a=this.transmuxer)?void 0:a.error))){var o=new Error("Found no media in fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+" resetting transmuxer to fallback to playlist timing");if(this.warn(o.message),this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+i.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=lr.PARSED,this.log("Parsed "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+")"),this.hls.trigger(I.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")},i.playlistLabel=function(){return this.playlistType===w?"level":"track"},i.fragInfo=function(e,t,i){var r,s;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(i?"part":"frag")+":["+(null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN).toFixed(3)+"-"+(null!=(s=t&&!i?e.endPTS:(i||e).end)?s:NaN).toFixed(3)+"]"+(i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):"")},i.treatAsGap=function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)},i.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},i.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())},r(t,[{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"primaryPrefetch",get:function(){var e;return!(!ur(this.config)||!(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}($t);function ur(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var dr=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,i=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var i=new Uint8Array(t),r=0,s=0;s<e.length;s++){var n=e[s];i.set(n,r),r+=n.length}return i}(t,i),this.reset(),e):new Uint8Array(0)},t.reset=function(){this.chunks.length=0,this.dataLength=0},e}();function cr(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function fr(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function gr(e,t){var i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,(i|=(127&e[t+2])<<7)|127&e[t+3]}function pr(e,t){for(var i=t,r=0;fr(e,t);)r+=10,r+=gr(e,t+6),cr(e,t+10)&&(r+=10),t+=r;if(r>0)return e.subarray(i,i+r)}function vr(e,t){return 255===e[t]&&240==(246&e[t+1])}function mr(e,t){return 1&e[t+1]?7:9}function yr(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Er(e,t){return t+1<e.length&&vr(e,t)}function Sr(e,t){if(Er(e,t)){var i=mr(e,t);if(t+i>=e.length)return!1;var r=yr(e,t);if(r<=i)return!1;var s=t+r;return s===e.length||Er(e,s)}return!1}function Tr(e,t,i,r,s){if(!e.samplerate){var a=function(e,t,i,r){var s=t[i+2],n=s>>2&15;if(!(n>12)){var a=1+(s>>6&3),o=t[i+3]>>6&3|(1&s)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n],u=n;5!==a&&29!==a||(u-=3);var d=[a<<3|(14&u)>>1,(1&u)<<7|o<<3];return V.log("manifest codec:"+r+", parsed codec:"+l+", channels:"+o+", rate:"+h+" (ADTS object type:"+a+" sampling index:"+n+")"),{config:d,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:r}}var c=new Error("invalid ADTS sampling index:"+n);e.emit(I.ERROR,I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}(t,i,r,s);if(!a)return;n(e,a)}}function _r(e){return 9216e4/e}function Lr(e,t,i,r,s){var n,a=r+s*_r(e.samplerate),o=function(e,t){var i=mr(e,t);if(t+i<=e.length){var r=yr(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(o){var l=o.frameLength,h=o.headerLength,u=h+l,d=Math.max(0,i+u-t.length);d?(n=new Uint8Array(u-h)).set(t.subarray(i+h,t.length),0):n=t.subarray(i+h,i+u);var c={unit:n,pts:a};return d||e.samples.push(c),{sample:c,length:u,missing:d}}var f=t.length-i;return(n=new Uint8Array(f)).set(t.subarray(i,t.length),0),{sample:{unit:n,pts:a},length:f,missing:-1}}function br(e,t){return fr(e,t)&&gr(e,t+6)+10<=e.length-t}function Ar(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1/0),function(e,t,i,r){var s=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);var a,o=(a=e)&&a.buffer instanceof ArrayBuffer&&void 0!==a.byteLength&&void 0!==a.byteOffset?e.byteOffset:0,l=(o+e.byteLength)/n,h=(o+t)/n,u=Math.floor(Math.max(0,Math.min(h,l)));return new r(s,u,Math.floor(Math.min(u+Math.max(i,0),l))-u)}(e,t,i,Uint8Array)}function Ir(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=q(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,i=q(e.data.subarray(t),!0);t+=i.length+1;var r=q(e.data.subarray(t));return{key:e.type,info:i,data:r}}var s=q(e.data);return{key:e.type,info:"",data:s}}(e):"APIC"===e.type?function(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var i=e.data.subarray(1).indexOf(0);if(-1!==i){var r=q(Ar(e.data,1,i)),s=e.data[2+i],n=e.data.subarray(3+i).indexOf(0);if(-1!==n){var a,o=q(Ar(e.data,3+i,n));return a="--\x3e"===r?q(Ar(e.data,4+i+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+n)),t.mimeType=r,t.pictureType=s,t.description=o,t.data=a,t}}}else console.log("Ignore frame with unrecognized character encoding")}(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,i=q(e.data.subarray(t),!0);t+=i.length+1;var r=q(e.data.subarray(t));return{key:e.type,info:i,data:r}}var s=q(e.data.subarray(1));return{key:e.type,info:"",data:s}}}(e)}function Rr(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=gr(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}var Pr=10,kr=10;function Dr(e){for(var t=0,i=[];fr(e,t);){var r=gr(e,t+6);e[t+5]>>6&1&&(t+=Pr);for(var s=(t+=Pr)+r;t+kr<s;){var n=Rr(e.subarray(t)),a=Ir(n);a&&i.push(a),t+=n.size+Pr}cr(e,t)&&(t+=Pr)}return i}function wr(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Cr(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Mr(e){for(var t=Dr(e),i=0;i<t.length;i++){var r=t[i];if(wr(r))return Cr(r)}}var Or=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function xr(e,t){return void 0===e&&(e=""),void 0===t&&(t=9e4),{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var Fr=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,i){},t.demux=function(e,t){this.cachedData&&(e=Te(this.cachedData,e),this.cachedData=null);var i,r=pr(e,0),s=r?r.length:0,n=this._audioTrack,a=this._id3Track,o=r?Mr(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&T(o))&&(this.basePTS=Nr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Or.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){var h=this.appendFrame(n,e,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i=s+=h.length):s=l}else br(e,s)?(r=pr(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Or.audioId3,duration:Number.POSITIVE_INFINITY}),i=s+=r.length):s++;if(s===l&&i!==l){var u=e.slice(i);this.cachedData?this.cachedData=Te(this.cachedData,u):this.cachedData=u}}return{audioTrack:n,videoTrack:xr(),id3Track:a,textTrack:xr()}},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},t.flush=function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:xr(),id3Track:this._id3Track,textTrack:xr()}},t.destroy=function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},e}(),Nr=function(e,t,i){return T(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0)},Br=null,Ur=[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],Gr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Hr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Kr=[0,1,1,4];function Vr(e,t,i,r,s){if(!(i+24>t.length)){var n=$r(t,i);if(n&&i+n.frameLength<=t.length){var a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function $r(e,t){var i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){var a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Ur[14*(3===i?3-r:3===r?3:4)+s-1],h=Gr[3*(3===i?0:2===i?1:2)+n],u=3===o?1:2,d=Hr[i][r],c=Kr[r],f=8*d*c,g=Math.floor(d*l/h+a)*c;if(null===Br){var p=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Br=p?parseInt(p[1]):0}return!!Br&&Br<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:u,frameLength:g,samplesPerFrame:f}}}function Wr(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function qr(e,t){return t+1<e.length&&Wr(e,t)}function jr(e,t){if(t+1<e.length&&Wr(e,t)){var i=$r(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);var s=t+r;return s===e.length||qr(e,s)}return!1}var Yr=function(e){function t(t,i){var r;return(r=e.call(this)||this).observer=void 0,r.config=void 0,r.observer=t,r.config=i,r}o(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e,t){if(!e)return!1;var i=pr(e,0),r=(null==i?void 0:i.length)||0;if(jr(e,r))return!1;for(var s=e.length;r<s;r++)if(Sr(e,r))return t.log("ADTS sync word found !"),!0;return!1},i.canParse=function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&vr(e,t)&&yr(e,t)<=e.length-t}(e,t)},i.appendFrame=function(e,t,i){Tr(e,this.observer,t,i,e.manifestCodec);var r=Lr(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r},t}(Fr),zr=function(e,t){var i=0,r=5;t+=r;for(var s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);r>0;){a[0]=e[t];var o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],t+=1,r-=o}return i},Xr=function(e){function t(t){var i;return(i=e.call(this)||this).observer=void 0,i.observer=t,i}o(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},i.canParse=function(e,t){return t+64<e.length},i.appendFrame=function(e,t,i){var r=Qr(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}},t.probe=function(e){if(!e)return!1;var t=pr(e,0);if(!t)return!1;var i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Mr(t)&&zr(e,i)<16},t}(Fr);function Qr(e,t,i,r,s){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;var n=t[i+4]>>6;if(n>=3)return-1;var a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[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][3*o+n];if(i+l>t.length)return-1;var h=t[i+6]>>5,u=0;2===h?u+=2:(1&h&&1!==h&&(u+=2),4&h&&(u+=2));var d=(t[i+6]<<8|t[i+7])>>12-u&1,c=[2,1,2,3,3,4,4,5][h]+d,f=t[i+5]>>3,g=7&t[i+5],p=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|d<<2|o>>4,o<<4&224]),v=r+s*(1536/a*9e4),m=t.subarray(i,i+l);return e.config=p,e.channelCount=c,e.samplerate=a,e.samples.push({unit:m,pts:v}),l}var Jr=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=pr(e,0),i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Mr(t)&&zr(e,i)<=16)return!1;for(var r=e.length;i<r;i++)if(jr(e,i))return V.log("MPEG Audio sync word found !"),!0;return!1},i.canParse=function(e,t){return function(e,t){return Wr(e,t)&&4<=e.length-t}(e,t)},i.appendFrame=function(e,t,i){if(null!==this.basePTS)return Vr(e,t,i,this.basePTS,this.frameIndex)},t}(Fr),Zr=/\/emsg[-/]ID3/i,es=function(){function e(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}var t=e.prototype;return t.resetTimeStamp=function(){},t.resetInitSegment=function(e,t,i,r){var s=this.videoTrack=xr("video",1),n=this.audioTrack=xr("audio",1),a=this.txtTrack=xr("text",1);if(this.id3Track=xr("id3",1),this.timeOffset=0,null!=e&&e.byteLength){var o=ge(e);if(o.video){var l=o.video,h=l.id,u=l.timescale,d=l.codec,c=l.supplemental;s.id=h,s.timescale=a.timescale=u,s.codec=d,s.supplemental=c}if(o.audio){var f=o.audio,g=f.id,p=f.timescale,v=f.codec;n.id=g,n.timescale=p,n.codec=v}a.id=ae.text,s.sampleDuration=0,s.duration=n.duration=r}},t.resetContiguity=function(){this.remainderData=null},e.probe=function(e){return function(e){for(var t=e.byteLength,i=0;i<t;){var r=he(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var i=e,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Te(this.remainderData,e));var n=function(e){var t={valid:null,remainder:null},i=ce(e,["moof"]);if(i.length<2)return t.remainder=e,t;var r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=n.remainder,r.samples=n.valid||new Uint8Array}else r.samples=i;var a=this.extractID3Track(r,t);return s.samples=_e(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(t,this.timeOffset);return i.samples=_e(e,t),{videoTrack:t,audioTrack:xr(),id3Track:r,textTrack:xr()}},t.extractID3Track=function(e,t){var i=this,r=this.id3Track;if(e.samples.length){var s=ce(e.samples,["emsg"]);s&&s.forEach((function(e){var s=function(e){var t=e[0],i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==oe(e.subarray(h,h+1));)i+=oe(e.subarray(h,h+1)),h+=1;for(i+=oe(e.subarray(h,h+1)),h+=1;"\0"!==oe(e.subarray(h,h+1));)r+=oe(e.subarray(h,h+1)),h+=1;r+=oe(e.subarray(h,h+1)),h+=1,s=he(e,12),n=he(e,16),o=he(e,20),l=he(e,24),h=28}else if(1===t){s=he(e,h+=4);var u=he(e,h+=4),d=he(e,h+=4);for(h+=4,a=Math.pow(2,32)*u+d,_(a)||(a=Number.MAX_SAFE_INTEGER,V.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=he(e,h),l=he(e,h+=4),h+=4;"\0"!==oe(e.subarray(h,h+1));)i+=oe(e.subarray(h,h+1)),h+=1;for(i+=oe(e.subarray(h,h+1)),h+=1;"\0"!==oe(e.subarray(h,h+1));)r+=oe(e.subarray(h,h+1)),h+=1;r+=oe(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Zr.test(s.schemeIdUri)){var n=ts(s,t),a=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=s.payload;r.samples.push({data:o,len:o.byteLength,dts:n,pts:n,type:Or.emsg,duration:a})}else if(i.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=ts(s,t);r.samples.push({data:s.payload,len:s.payload.byteLength,dts:l,pts:l,type:Or.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return r},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0},e}();function ts(e,t){return T(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var is=function(){function e(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Bt(t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,0)},t.decryptAacSample=function(e,t,i){var r=this,s=e[t].unit;if(!(s.length<=16)){var n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then((function(n){var a=new Uint8Array(n);s.set(a,16),r.decrypter.isSync()||r.decryptAacSamples(e,t+1,i)})).catch(i)}},t.decryptAacSamples=function(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,i),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0,s=32;s<e.length-16;s+=160,r+=16)i.set(e.subarray(s,s+16),r);return i},t.getAvcDecryptedUnit=function(e,t){for(var i=new Uint8Array(t),r=0,s=32;s<e.length-16;s+=160,r+=16)e.set(i.subarray(r,r+16),s);return e},t.decryptAvcSample=function(e,t,i,r,s){var n=this,a=Ie(s.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then((function(o){s.data=n.getAvcDecryptedUnit(a,o),n.decrypter.isSync()||n.decryptAvcSamples(e,t,i+1,r)})).catch(r)},t.decryptAvcSamples=function(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)return void r();for(var s=e[t].units;!(i>=s.length);i++){var n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,r,n),this.decrypter.isSync())))return}}},e}(),rs=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}},t.getLastNalUnit=function(e){var t,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){var s=r.units;i=s[s.length-1]}return i},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var i=t.samples,r=i.length;if(!r)return void t.dropped++;var s=i[r-1];e.pts=s.pts,e.dts=s.dts}t.samples.push(e)}},t.parseNALu=function(e,t,i){var r,s,n=t.byteLength,a=e.naluState||0,o=a,l=[],h=0,u=-1,d=0;for(-1===a&&(u=0,d=this.getNALuType(t,0),a=0,h=1);h<n;)if(r=t[h++],a)if(1!==a)if(r)if(1===r){if(s=h-a-1,u>=0){var c={data:t.subarray(u,s),type:d};l.push(c)}else{var f=this.getLastNalUnit(e.samples);f&&(o&&h<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),s>0&&(f.data=Te(f.data,t.subarray(0,s)),f.state=0))}h<n?(u=h,d=this.getNALuType(t,h),a=0):a=-1}else a=0;else a=3;else a=r?0:2;else a=r?0:1;if(u>=0&&a>=0){var g={data:t.subarray(u,n),type:d,state:a};l.push(g)}if(0===l.length){var p=this.getLastNalUnit(e.samples);p&&(p.data=Te(p.data,t))}return e.naluState=a,l},e}(),ss=function(){function e(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}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&V.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i},t.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},e}(),ns=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var s,n=this,a=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,h;switch(r.type){case 1:var u=!1;s=!0;var d,c=r.data;if(l&&c.length>4){var f=n.readSliceType(c);2!==f&&4!==f&&7!==f&&9!==f||(u=!0)}u&&null!=(d=o)&&d.frame&&!o.key&&(n.pushAccessUnit(o,e),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=u;break;case 5:s=!0,null!=(a=o)&&a.frame&&!o.key&&(n.pushAccessUnit(o,e),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:s=!0,Ae(r.data,1,i.pts,t.samples);break;case 7:var g,p;s=!0,l=!0;var v=r.data,m=n.readSPS(v);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(g=e.pixelRatio)?void 0:g[0])!==m.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[v];for(var y=v.subarray(1,4),E="avc1.",S=0;S<3;S++){var T=y[S].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:s=!0,e.pps=[r.data];break;case 9:s=!0,e.audFound=!0,null!=(h=o)&&h.frame&&(n.pushAccessUnit(o,e),o=null),o||(o=n.VideoSample=n.createVideoSample(!1,i.pts,i.dts));break;case 12:s=!0;break;default:s=!1}o&&s&&o.units.push(r)})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},i.getNALuType=function(e,t){return 31&e[t]},i.readSliceType=function(e){var t=new ss(e);return t.readUByte(),t.readUEG(),t.readUEG()},i.skipScalingList=function(e,t){for(var i=8,r=8,s=0;s<e;s++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r},i.readSPS=function(e){var t,i,r,s=new ss(e),n=0,a=0,o=0,l=0,h=s.readUByte.bind(s),u=s.readBits.bind(s),d=s.readUEG.bind(s),c=s.readBoolean.bind(s),f=s.skipBits.bind(s),g=s.skipEG.bind(s),p=s.skipUEG.bind(s),v=this.skipScalingList.bind(this);h();var m=h();if(u(5),f(3),h(),p(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),p(),p(),f(1),c())for(i=3!==y?8:12,r=0;r<i;r++)c()&&v(r<6?16:64,s)}p();var E=d();if(0===E)d();else if(1===E)for(f(1),g(),g(),t=d(),r=0;r<t;r++)g();p(),f(1);var S=d(),T=d(),_=u(1);0===_&&f(1),f(1),c()&&(n=d(),a=d(),o=d(),l=d());var L=[1,1];if(c()&&c())switch(h()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil(16*(S+1)-2*n-2*a),height:(2-_)*(T+1)*16-(_?2:4)*(o+l),pixelRatio:L}},t}(rs),as=function(e){function t(){for(var t,i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return(t=e.call.apply(e,[this].concat(r))||this).initVPS=null,t}o(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var s,a=this,o=this.parseNALu(e,i.data,r),l=this.VideoSample,h=!1;i.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.forEach((function(r){var o,u;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=a.VideoSample=a.createVideoSample(!1,i.pts,i.dts)),l.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:var d;s=!0,h&&null!=(d=l)&&d.frame&&!l.key&&(a.pushAccessUnit(l,e),l=a.VideoSample=null),l||(l=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:s=!0,null!=(o=l)&&o.frame&&!l.key&&(a.pushAccessUnit(l,e),l=a.VideoSample=null),l||(l=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 39:s=!0,Ae(r.data,2,i.pts,t.samples);break;case 32:s=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=n(e.params,a.readVPS(r.data)),a.initVPS=r.data),e.vps=[r.data];break;case 33:if(s=!0,h=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],r.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var c=a.readSPS(r.data);for(var f in e.width=c.width,e.height=c.height,e.pixelRatio=c.pixelRatio,e.codec=c.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),c.params)e.params[f]=c.params[f]}a.pushParameterSet(e.sps,r.data,e.vps),l||(l=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts)),l.key=!0;break;case 34:if(s=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];var g=a.readPPS(r.data);for(var p in g)e.params[p]=g[p]}a.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:s=!0,e.audFound=!0,null!=(u=l)&&u.frame&&(a.pushAccessUnit(l,e),l=null),l||(l=a.VideoSample=a.createVideoSample(!1,i.pts,i.dts));break;default:s=!1}l&&s&&l.units.push(r)})),r&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)},i.pushParameterSet=function(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)},i.getNALuType=function(e,t){return(126&e[t])>>>1},i.ebsp2rbsp=function(e){for(var t=new Uint8Array(e.byteLength),i=0,r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)},i.pushAccessUnit=function(t,i){e.prototype.pushAccessUnit.call(this,t,i),this.initVPS&&(this.initVPS=null)},i.readVPS=function(e){var t=new ss(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}},i.readSPS=function(e){var t=new ss(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var i=t.readBits(3);t.readBoolean();for(var r=t.readBits(2),s=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),m=[],y=[],E=0;E<i;E++)m.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(var S=i;S<8;S++)t.readBits(2);for(var T=0;T<i;T++)m[T]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[T]&&t.readUByte();t.readUEG();var _=t.readUEG();3==_&&t.skipBits(1);var L=t.readUEG(),b=t.readUEG(),A=t.readBoolean(),I=0,R=0,P=0,k=0;A&&(I+=t.readUEG(),R+=t.readUEG(),P+=t.readUEG(),k+=t.readUEG());for(var D=t.readUEG(),w=t.readUEG(),C=t.readUEG(),M=t.readBoolean()?0:i;M<=i;M++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(var O=0;O<4;O++)for(var x=0;x<(3===O?2:6);x++)if(t.readBoolean()){var F=Math.min(64,1<<4+(O<<1));O>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var B=t.readUEG(),U=0,G=0;G<B;G++){var H=!1;if(0!==G&&(H=t.readBoolean()),H){G===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var K=0,V=0;V<=U;V++){var $=t.readBoolean(),W=!1;$||(W=t.readBoolean()),($||W)&&K++}U=K}else{var q=t.readUEG(),j=t.readUEG();U=q+j;for(var Y=0;Y<q;Y++)t.readUEG(),t.readBoolean();for(var z=0;z<j;z++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var X=t.readUEG(),Q=0;Q<X;Q++){for(var J=0;J<C+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,ie=!0,re=1,se=0;if(t.readBoolean(),t.readBoolean(),t.readBoolean()){if(t.readBoolean()){var ne=t.readUByte();ne>0&&ne<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ne-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ne-1]):255===ne&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(re=t.readBits(32),se=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){var ae=t.readBoolean(),oe=t.readBoolean(),le=!1;(ae||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var he=0;he<=i;he++){var ue=!1;(ie=t.readBoolean())||t.readBoolean()?t.readEG():ue=t.readBoolean();var de=ue?1:t.readUEG()+1;if(ae)for(var ce=0;ce<de;ce++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var fe=0;fe<de;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var ge=L,pe=b;if(A){var ve=1,me=1;1===_?ve=me=2:2==_&&(ve=2),ge=L-ve*R-ve*I,pe=b-me*k-me*P}for(var ye=r?["A","B","C"][r]:"",Ee=a<<24|o<<16|l<<8|h,Se=0,Te=0;Te<32;Te++)Se=(Se|(Ee>>Te&1)<<31-Te)>>>0;var _e=Se.toString(16);return 1===n&&"2"===_e&&(_e="6"),{codecString:"hvc1."+ye+n+"."+_e+"."+(s?"H":"L")+v+".B0",params:{general_tier_flag:s,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[u,d,c,f,g,p],general_level_idc:v,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:w,min_spatial_segmentation_idc:Z,chroma_format_idc:_,frame_rate:{fixed:ie,fps:se/re}},width:ge,height:pe,pixelRatio:[ee,te]}},i.readPPS=function(e){var t=new ss(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var i=t.readBoolean(),r=t.readBoolean(),s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}},i.matchSPS=function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)},t}(rs),os=188,ls=function(){function e(e,t,i,r){this.logger=void 0,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._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.logger=r,this.videoParser=null}e.probe=function(t,i){var r=e.syncOffset(t);return r>0&&i.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},e.syncOffset=function(e){for(var t=e.length,i=Math.min(940,t-os)+1,r=0;r<i;){for(var s=!1,n=-1,a=0,o=r;o<t;o+=os){if(71!==e[o]||t-o!==os&&71!==e[o+os]){if(a)return-1;break}if(a++,-1===n&&0!==(n=o)&&(i=Math.min(n+18612,e.length-os)+1),s||(s=0===hs(e,o)),s&&a>1&&(0===n&&a>2||o+os>i))return n}r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:ae[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,i,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=e.createTrack("audio",s),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=r},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,i=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,i,r,s){var n;void 0===r&&(r=!1),void 0===s&&(s=!1),r||(this.sampleAes=null);var a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,u=a.pid,d=a.pesData,c=o.pid,f=l.pid,g=o.pesData,p=l.pesData,v=null,m=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=Te(this.remainderData,t)).length,this.remainderData=null),E<os&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var S=Math.max(0,e.syncOffset(t));(E-=(E-S)%os)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var T=0,_=S;_<E;_+=os)if(71===t[_]){var L=!!(64&t[_+1]),b=hs(t,_),A=void 0;if((48&t[_+3])>>4>1){if((A=_+5+t[_+4])===_+os)continue}else A=_+4;switch(b){case u:L&&(d&&(n=gs(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,h,n,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(A,_+os)),d.size+=_+os-A);break;case c:if(L){if(g&&(n=gs(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}g={data:[],size:0}}g&&(g.data.push(t.subarray(A,_+os)),g.size+=_+os-A);break;case f:L&&(p&&(n=gs(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(t.subarray(A,_+os)),p.size+=_+os-A);break;case 0:L&&(A+=t[A]+1),y=this._pmtId=us(t,A);break;case y:L&&(A+=t[A]+1);var I=ds(t,A,this.typeSupported,r,this.observer,this.logger);(u=I.videoPid)>0&&(a.pid=u,a.segmentCodec=I.segmentVideoCodec),(c=I.audioPid)>0&&(o.pid=c,o.segmentCodec=I.segmentAudioCodec),(f=I.id3Pid)>0&&(l.pid=f),null===v||m||(this.logger.warn("MPEG-TS PMT found at "+_+" after unknown PID '"+v+"'. Backtracking to sync byte @"+S+" to parse all TS packets."),v=null,_=S-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:v=b}}else T++;T>0&&cs(this.observer,new Error("Found "+T+" TS packet/s that do not start with 0x47"),void 0,this.logger),a.pesData=d,o.pesData=g,l.pesData=p;var R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(R),R},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,i=e.audioTrack,r=e.videoTrack,s=e.id3Track,n=e.textTrack,a=r.pesData,o=i.pesData,l=s.pesData;if(a&&(t=gs(a,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,n,t,!0),r.pesData=null)):r.pesData=a,o&&(t=gs(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(t=gs(l,this.logger))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=l},t.demuxSampleAes=function(e,t,i){var r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new is(this.observer,this.config,t);return this.decrypt(r,s)},t.readyVideoParser=function(e){null===this.videoParser&&("avc"===e?this.videoParser=new ns:"hevc"===e&&(this.videoParser=new as))},t.decrypt=function(e,t){return new Promise((function(i){var r=e.audioTrack,s=e.videoTrack;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(function(){s.samples?t.decryptAvcSamples(s.samples,0,0,(function(){i(e)})):i(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(function(){i(e)}))}))},t.destroy=function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0},t.parseAACPES=function(e,t){var i,r,s,n=0,a=this.aacOverFlow,o=t.data;if(a){this.aacOverFlow=null;var l=a.missing,h=a.sample.unit.byteLength;if(-1===l)o=Te(a.sample.unit,o);else{var u=h-l;a.sample.unit.set(o.subarray(0,l),u),e.samples.push(a.sample),n=a.missing}}for(i=n,r=o.length;i<r-1&&!Er(o,i);i++);if(i!==n){var d,c=i<r-1;if(d=c?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES",cs(this.observer,new Error(d),c,this.logger),!c)return}if(Tr(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)s=t.pts;else{if(!a)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=_r(e.samplerate);s=a.sample.pts+f}for(var g,p=0;i<r;){if(i+=(g=Lr(e,o,i,s,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;i<r-1&&!Er(o,i);i++);}},t.parseMPEGPES=function(e,t){var i=t.data,r=i.length,s=0,n=0,a=t.pts;if(void 0!==a)for(;n<r;)if(qr(i,n)){var o=Vr(e,i,n,a,s);if(!o)break;n+=o.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},t.parseAC3PES=function(e,t){var i=t.data,r=t.pts;if(void 0!==r)for(var s,n=i.length,a=0,o=0;o<n&&(s=Qr(e,i,o,r,a++))>0;)o+=s;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var i=n({},t,{type:this._videoTrack?Or.emsg:Or.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function hs(e,t){return((31&e[t+1])<<8)+e[t+2]}function us(e,t){return(31&e[t+10])<<8|e[t+11]}function ds(e,t,i,r,s,n){var a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){var l=hs(e,t),h=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){fs("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=l);break;case 21:-1===a.id3Pid&&(a.id3Pid=l);break;case 219:if(!r){fs("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){fs("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&h>0)for(var u=t+5,d=h;d>2;){106===e[u]&&(!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=l,a.segmentAudioCodec="ac3"));var c=e[u+1]+2;u+=c,d-=c}break;case 194:case 135:return cs(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=l,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=h+5}return a}function cs(e,t,i,r){r.warn("parsing error: "+t.message),e.emit(I.ERROR,I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function fs(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function gs(e,t){var i,r,s,n,a,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Te(l[0],l[1]),l.splice(1,1);if(1===((i=l[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>e.size-6)return null;var h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?n-(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2)>54e5&&(t.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var u=(s=i[8])+9;if(e.size<=u)return null;e.size-=u;for(var d=new Uint8Array(e.size),c=0,f=l.length;c<f;c++){var g=(i=l[c]).byteLength;if(u){if(u>g){u-=g;continue}i=i.subarray(u),g-=u,u=0}d.set(i,o),o+=g}return r&&(r-=s+3),{data:d,pts:n,dts:a,len:r}}return null}var ps=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}},e}(),vs=Math.pow(2,32)-1,ms=function(){function e(){}return e.init=function(){var t;for(t in e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var i=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:i,audio:r};var s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=n,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,a,l,a,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,s))},e.box=function(e){for(var t=8,i=arguments.length,r=new Array(i>1?i-1:0),s=1;s<i;s++)r[s-1]=arguments[s];for(var n=r.length,a=n;n--;)t+=r[n].byteLength;var o=new Uint8Array(t);for(o[0]=t>>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),n=0,t=8;n<a;n++)o.set(r[n],t),t+=r[n].byteLength;return o},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,i){i*=t;var r=Math.floor(i/(vs+1)),s=Math.floor(i%(vs+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,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,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,i,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,i))},e.moov=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(e.mvex(t)))},e.mvex=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trex(t[i]);return e.box.apply(null,[e.types.mvex].concat(r))},e.mvhd=function(t,i){i*=t;var r=Math.floor(i/(vs+1)),s=Math.floor(i%(vs+1)),n=new Uint8Array([1,0,0,0,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,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,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 e.box(e.types.mvhd,n)},e.sdtp=function(t){var i,r,s=t.samples||[],n=new Uint8Array(4+s.length);for(i=0;i<s.length;i++)r=s[i].flags,n[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,n)},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))},e.avc1=function(t){var i,r,s,n=[],a=[];for(i=0;i<t.sps.length;i++)s=(r=t.sps[i]).byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)s=(r=t.pps[i]).byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(r));var o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.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,255&l,h>>8&255,255&h,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,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,d>>24,d>>16&255,d>>8&255,255&d])))},e.esds=function(e){var t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2].concat(t,[6,1,2]))},e.audioStsd=function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){return e.box(e.types[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))},e.stsd=function(t){var i=t.segmentCodec;if("audio"===t.type){if("aac"===i)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===i&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===i&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===i)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===i&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+i+"/"+t.codec+")")},e.tkhd=function(t){var i=t.id,r=(t.duration||0)*(t.timescale||0),s=t.width||0,n=t.height||0,a=Math.floor(r/(vs+1)),o=Math.floor(r%(vs+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,s>>8&255,255&s,0,0,n>>8&255,255&n,0,0]))},e.traf=function(t,i){var r=e.sdtp(t),s=t.id,n=Math.floor(i/(vs+1)),a=Math.floor(i%(vs+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,r.length+16+20+8+16+8+8),r)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var i=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,i){var r,s,n,a,o,l,h=t.samples||[],u=h.length,d=12+16*u,c=new Uint8Array(d);for(i+=8+d,c.set(["video"===t.type?1:0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<u;r++)n=(s=h[r]).duration,a=s.size,o=s.flags,l=s.cts,c.set([n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*r);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var i=e.moov(t);return Te(e.FTYP,i)},e.hvc1=function(t){for(var i=t.params,r=[t.vps,t.sps,t.pps],s=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),r.length]),n=s.length,a=0;a<r.length;a+=1){n+=3;for(var o=0;o<r[a].length;o+=1)n+=2+r[a][o].length}var l=new Uint8Array(n);l.set(s,0),n=s.length;for(var h=r.length-1,u=0;u<r.length;u+=1){l.set(new Uint8Array([32+u|(u===h?128:0),0,r[u].length]),n),n+=3;for(var d=0;d<r[u].length;d+=1)l.set(new Uint8Array([r[u][d].length>>8,255&r[u][d].length]),n),n+=2,l.set(r[u][d],n),n+=r[u][d].length}var c=e.box(e.types.hvcC,l),f=t.width,g=t.height,p=t.pixelRatio[0],v=t.pixelRatio[1];return e.box(e.types.hvc1,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,f>>8&255,255&f,g>>8&255,255&g,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]),c,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,255&p,v>>24,v>>16&255,v>>8&255,255&v])))},e}();ms.types=void 0,ms.HDLR_TYPES=void 0,ms.STTS=void 0,ms.STSC=void 0,ms.STCO=void 0,ms.STSZ=void 0,ms.VMHD=void 0,ms.SMHD=void 0,ms.STSD=void 0,ms.FTYP=void 0,ms.DINF=void 0;function ys(e,t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);var s=e*t*i;return r?Math.round(s):s}function Es(e,t){return ys(e,1e3,1/9e4,t)}var Ss=null,Ts=null;function _s(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Ls=function(e){function t(t,i,r,s){var n;if((n=e.call(this,"mp4-remuxer",s)||this).observer=void 0,n.config=void 0,n.typeSupported=void 0,n.ISGenerated=!1,n._initPTS=null,n._initDTS=null,n.nextVideoTs=null,n.nextAudioTs=null,n.videoSampleDuration=null,n.isAudioContiguous=!1,n.isVideoContiguous=!1,n.videoTrackConfig=void 0,n.observer=t,n.config=i,n.typeSupported=r,n.ISGenerated=!1,null===Ss){var a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ss=a?parseInt(a[1]):0}if(null===Ts){var o=navigator.userAgent.match(/Safari\/(\d+)/i);Ts=o?parseInt(o[1]):0}return n}o(t,e);var i=t.prototype;return i.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},i.resetTimeStamp=function(e){this.log("initPTS & initDTS reset"),this._initPTS=this._initDTS=e},i.resetNextTimestamp=function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},i.resetInitSegment=function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},i.getVideoStartPts=function(e){var t=!1,i=e[0].pts,r=e.reduce((function(e,r){var s=r.pts,n=s-e;return n<-4294967296&&(t=!0,n=(s=bs(s,i))-e),n>0?e:s}),i);return t&&this.debug("PTS rollover detected"),r},i.remux=function(e,t,i,r,s,n,a,o){var l,h,u,d,c,f,g=s,p=s,v=e.pid>-1,m=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!v||E)&&(!m||S)||this.ISGenerated||a){if(this.ISGenerated){var T,_,L,b,A=this.videoTrackConfig;(A&&(t.width!==A.width||t.height!==A.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(_=A.pixelRatio)?void 0:_[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(b=A.pixelRatio)?void 0:b[1]))||!A&&S||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,s,n));var I,R=this.isVideoContiguous,P=-1;if(S&&(P=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!R&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,P>0){this.warn("Dropped "+P+" out of "+y+" video samples due to a missing keyframe");var k=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,I=p+=(t.samples[0].pts-k)/t.inputTimeScale}else-1===P&&(this.warn("No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&S){var D=this.getVideoStartPts(t.samples),w=(bs(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,w),p+=Math.max(0,-w)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,m||S||o===C?p:void 0),S){var M=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,p,R,M)}}else S&&(l=this.remuxVideo(t,p,R,0));l&&(l.firstKeyFrame=P,l.independent=-1!==P,l.firstKeyFramePTS=I)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=As(i,s,this._initPTS,this._initDTS)),r.samples.length&&(d=Is(r,s,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:c}},i.generateIS=function(e,t,i,r){var s,n,a,o=e.samples,l=t.samples,h=this.typeSupported,u={},d=this._initPTS,c=!d||r,f="audio/mp4",g=-1;if(c&&(s=n=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",e.codec=""):h.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}u.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&h.mpeg?new Uint8Array(0):ms.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(g=e.id,a=e.inputTimeScale,d&&a===d.timescale?c=!1:s=n=o[0].pts-Math.round(a*i))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:ms.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(g=t.id,a=t.inputTimeScale,d&&a===d.timescale)c=!1;else{var p=this.getVideoStartPts(l),v=Math.round(a*i);n=Math.min(n,bs(l[0].dts,p)-v),s=Math.min(s,p-v)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,c?(d&&this.warn("Timestamps at playlist time: "+(r?"":"~")+i+" "+s/a+" != initPTS: "+d.baseTime/d.timescale+" ("+d.baseTime+"/"+d.timescale+") trackId: "+d.trackId),this.log("Found initPTS at playlist time: "+i+" offset: "+s/a+" ("+s+"/"+a+") trackId: "+g),this._initPTS={baseTime:s,timescale:a,trackId:g},this._initDTS={baseTime:n,timescale:a,trackId:g}):s=a=void 0,{tracks:u,initPTS:s,timescale:a,trackId:g}},i.remuxVideo=function(e,t,i,r){var s,a,o=e.inputTimeScale,l=e.samples,h=[],u=l.length,d=this._initPTS,c=d.baseTime*o/d.timescale,f=this.nextVideoTs,g=8,p=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,y=!1;if(!i||null===f){var E=c+t*o,S=l[0].pts-bs(l[0].dts,l[0].pts);Ss&&null!==f&&Math.abs(E-S-(f+c))<15e3?i=!0:f=E-S-c}for(var T=f+c,_=0;_<u;_++){var L=l[_];L.pts=bs(L.pts,T),L.dts=bs(L.dts,T),L.dts<l[_>0?_-1:_].dts&&(y=!0)}y&&l.sort((function(e,t){var i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),s=l[0].dts;var R=l[l.length-1].dts-s,P=R?Math.round(R/(u-1)):p||e.inputTimeScale/30;if(i){var k=s-T,D=k>P,w=k<-1;if((D||w)&&(D?this.warn((e.segmentCodec||"").toUpperCase()+": "+Es(k,!0)+" ms ("+k+"dts) hole between fragments detected at "+t.toFixed(3)):this.warn((e.segmentCodec||"").toUpperCase()+": "+Es(-k,!0)+" ms ("+k+"dts) overlapping between fragments detected at "+t.toFixed(3)),!w||T>=l[0].pts||Ss)){s=T;var C=l[0].pts-k;if(D)l[0].dts=s,l[0].pts=C;else for(var M=!0,O=0;O<l.length&&!(l[O].dts>C&&M);O++){var x=l[O].pts;if(l[O].dts-=k,l[O].pts-=k,O<l.length-1){var F=l[O+1].pts;M=F<=l[O].pts==F<=x}}this.log("Video: Initial PTS/DTS adjusted: "+Es(C,!0)+"/"+Es(s,!0)+", delta: "+Es(k,!0)+" ms")}}for(var N=0,B=0,U=s=Math.max(0,s),G=0;G<u;G++){for(var H=l[G],K=H.units,V=K.length,$=0,W=0;W<V;W++)$+=K[W].data.length;B+=$,N+=V,H.length=$,H.dts<U?(H.dts=U,U+=P/4|0||1):U=H.dts,v=Math.min(H.pts,v),m=Math.max(H.pts,m)}a=l[u-1].dts;var q,j=B+4*N+8;try{q=new Uint8Array(j)}catch(e){return void this.observer.emit(I.ERROR,I.ERROR,{type:b.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:j,reason:"fail allocating video mdat "+j})}var Y=new DataView(q.buffer);Y.setUint32(0,j),q.set(ms.types.mdat,4);for(var z=!1,X=Number.POSITIVE_INFINITY,Q=Number.POSITIVE_INFINITY,J=Number.NEGATIVE_INFINITY,Z=Number.NEGATIVE_INFINITY,ee=0;ee<u;ee++){for(var te=l[ee],ie=te.units,re=0,se=0,ne=ie.length;se<ne;se++){var ae=ie[se],oe=ae.data,le=ae.data.byteLength;Y.setUint32(g,le),g+=4,q.set(oe,g),g+=le,re+=4+le}var he=void 0;if(ee<u-1)p=l[ee+1].dts-te.dts,he=l[ee+1].pts-te.pts;else{var ue=this.config,de=ee>0?te.dts-l[ee-1].dts:P;if(he=ee>0?te.pts-l[ee-1].pts:P,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var ce=Math.floor(ue.maxBufferHole*o),fe=(r?v+r*o:this.nextAudioTs+c)-te.pts;fe>ce?((p=fe-de)<0?p=de:z=!0,this.log("It is approximately "+fe/90+" ms to the next segment; using duration "+p/90+" ms for the last video frame.")):p=de}else p=de}var ge=Math.round(te.pts-te.dts);X=Math.min(X,p),J=Math.max(J,p),Q=Math.min(Q,he),Z=Math.max(Z,he),h.push(_s(te.key,p,re,ge))}if(h.length)if(Ss){if(Ss<70){var pe=h[0].flags;pe.dependsOn=2,pe.isNonSync=0}}else if(Ts&&Z-Q<J-X&&P/J<.025&&0===h[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var ve=s,me=0,ye=h.length;me<ye;me++){var Ee=ve+h[me].duration,Se=ve+h[me].cts;if(me<ye-1){var Te=Ee+h[me+1].cts;h[me].duration=Te-Se}else h[me].duration=me?h[me-1].duration:P;h[me].cts=0,ve=Ee}}var _e=a+(p=z||!p?P:p);this.nextVideoTs=f=_e-c,this.videoSampleDuration=p,this.isVideoContiguous=!0;var Le={data1:ms.moof(e.sequenceNumber++,s,n(e,{samples:h})),data2:q,startPTS:(v-c)/o,endPTS:(m+p-c)/o,startDTS:(s-c)/o,endDTS:f/o,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Le},i.getSamplesPerFrame=function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}},i.remuxAudio=function(e,t,i,r,s){var a=e.inputTimeScale,o=a/(e.samplerate?e.samplerate:a),l=this.getSamplesPerFrame(e),h=l*o,u=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],f=void 0!==s,g=e.samples,p=d?0:8,v=this.nextAudioTs||-1,m=u.baseTime*a/u.timescale,y=m+t*a;if(this.isAudioContiguous=i=i||g.length&&v>0&&(r&&Math.abs(y-(v+m))<9e3||Math.abs(bs(g[0].pts,y)-(v+m))<20*h),g.forEach((function(e){e.pts=bs(e.pts,y)})),!i||v<0){if(g=g.filter((function(e){return e.pts>=0})),!g.length)return;v=0===s?0:r&&!f?Math.max(0,y-m):g[0].pts-m}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,S=0,T=v+m;S<g.length;S++){var _=g[S],L=_.pts,R=L-T,P=Math.abs(1e3*R/a);if(R<=-E*h&&f)0===S&&(this.warn("Audio frame @ "+(L/a).toFixed(3)+"s overlaps marker by "+Math.round(1e3*R/a)+" ms."),this.nextAudioTs=v=L-m,T=L);else if(R>=E*h&&P<1e4&&f){var k=Math.round(R/h);for(T=L-k*h;T<0&&k&&h;)k--,T+=h;0===S&&(this.nextAudioTs=v=T-m),this.warn("Injecting "+k+" audio frames @ "+((T-m)/a).toFixed(3)+"s due to "+Math.round(1e3*R/a)+" ms gap.");for(var D=0;D<k;D++){var w=ps.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);w||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),w=_.unit.subarray()),g.splice(S,0,{unit:w,pts:T}),T+=h,S++}}_.pts=T,T+=h}for(var C,M=null,O=null,x=0,F=g.length;F--;)x+=g[F].unit.byteLength;for(var N=0,B=g.length;N<B;N++){var U=g[N],G=U.unit,H=U.pts;if(null!==O)c[N-1].duration=Math.round((H-O)/o);else{if(i&&"aac"===e.segmentCodec&&(H=v+m),M=H,!(x>0))return;x+=p;try{C=new Uint8Array(x)}catch(e){return void this.observer.emit(I.ERROR,I.ERROR,{type:b.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:x,reason:"fail allocating audio mdat "+x})}d||(new DataView(C.buffer).setUint32(0,x),C.set(ms.types.mdat,4))}C.set(G,p);var K=G.byteLength;p+=K,c.push(_s(!0,l,K,0)),O=H}var V=c.length;if(V){var $=c[c.length-1];v=O-m,this.nextAudioTs=v+o*$.duration;var W=d?new Uint8Array(0):ms.moof(e.sequenceNumber++,M/o,n({},e,{samples:c}));e.samples=[];var q=(M-m)/a,j=v/a,Y={data1:W,data2:C,startPTS:q,endPTS:j,startDTS:q,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,Y}},t}(F);function bs(e,t){var i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function As(e,t,i,r){var s=e.samples.length;if(s){for(var n=e.inputTimeScale,a=0;a<s;a++){var o=e.samples[a];o.pts=bs(o.pts-i.baseTime*n/i.timescale,t*n)/n,o.dts=bs(o.dts-r.baseTime*n/r.timescale,t*n)/n}var l=e.samples;return e.samples=[],{samples:l}}}function Is(e,t,i){var r=e.samples.length;if(r){for(var s=e.inputTimeScale,n=0;n<r;n++){var a=e.samples[n];a.pts=bs(a.pts-i.baseTime*s/i.timescale,t*s)/s}e.samples.sort((function(e,t){return e.pts-t.pts}));var o=e.samples;return e.samples=[],{samples:o}}}var Rs,Ps=function(e){function t(t,i,r,s){var n;return(n=e.call(this,"passthrough-remuxer",s)||this).emitInitSegment=!1,n.audioCodec=void 0,n.videoCodec=void 0,n.initData=void 0,n.initPTS=null,n.initTracks=void 0,n.lastEndTime=null,n.isVideoContiguous=!1,n}o(t,e);var i=t.prototype;return i.destroy=function(){},i.resetTimeStamp=function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)},i.resetNextTimestamp=function(){this.isVideoContiguous=!1,this.lastEndTime=null},i.resetInitSegment=function(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=!0},i.generateInitSegment=function(e,t){var i=this.audioCodec,r=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var s=this.initData=ge(e),n=s.audio,a=s.video;if(t)!function(e,t){if(e&&t){var i=t.keyId;i&&t.isCommonEncryption&&ce(e,["moov","trak"]).forEach((function(e){var t=ce(e,["mdia","minf","stbl","stsd"])[0].subarray(8),r=ce(t,["enca"]),s=r.length>0;s||(r=ce(t,["encv"])),r.forEach((function(e){ce(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=Se(e);if(t){var r=t.subarray(8,24);r.some((function(e){return 0!==e}))||(V.log("[eme] Patching keyId in 'enc"+(s?"a":"v")+">sinf>>tenc' box: "+j(r)+" -> "+j(i)),t.set(i,8))}}))}))}))}}(e,t);else{var o=n||a;null!=o&&o.encrypted&&this.warn('Init segment with encrypted track with has no key ("'+o.codec+'")!')}n&&(i=Ds(n,X,this)),a&&(r=Ds(a,Q,this));var l={};n&&a?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?l.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?l.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l},i.remux=function(e,t,i,r,s,n){var a,o,l=this.initPTS,h=this.lastEndTime,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};T(h)||(h=this.lastEndTime=s||0);var d=t.samples;if(!d.length)return u;var c={initPTS:void 0,timescale:void 0,trackId:void 0},f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=function(e,t,i){for(var r={},s=ce(e,["moof","traf"]),n=0;n<s.length;n++){var a=s[n],o=ce(a,["tfhd"])[0],l=he(o,4),h=t[l];if(h){r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:h.timescale,type:h.type});var u=r[l],d=ce(a,["tfdt"])[0];if(d){var c=d[0],f=he(d,4);1===c&&(f===se?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=se+1,f+=he(d,8))),T(f)&&(!T(u.start)||f<u.start)&&(u.start=f)}var g=h.default,p=he(o,0)|(null==g?void 0:g.flags),v=(null==g?void 0:g.duration)||0;8&p&&(v=he(o,2&p?12:8));for(var m=ce(a,["trun"]),y=u.start||0,E=0,S=v,_=0;_<m.length;_++){var L=m[_],b=he(L,4),A=u.sampleCount;u.sampleCount+=b;var I=1&L[3],R=4&L[3],P=1&L[2],k=2&L[2],D=4&L[2],w=8&L[2],C=8,M=b;for(I&&(C+=4),R&&b&&(1&L[C+1]||void 0!==u.keyFrameIndex||(u.keyFrameIndex=A),C+=4,P?(S=he(L,C),C+=4):S=v,k&&(C+=4),w&&(C+=4),y+=S,E+=S,M--);M--;)P?(S=he(L,C),C+=4):S=v,k&&(C+=4),D&&(1&L[C+1]||void 0===u.keyFrameIndex&&(u.keyFrameIndex=u.sampleCount-(M+1),u.keyFrameStart=y),C+=4),w&&(C+=4),y+=S,E+=S;!E&&v&&(E+=v*b)}u.duration+=E}}if(!Object.keys(r).some((function(e){return r[e].duration}))){for(var O=1/0,x=0,F=ce(e,["sidx"]),N=0;N<F.length;N++){var B=fe(F[N]);if(null!=B&&B.references){O=Math.min(O,B.earliestPresentationTime/B.timescale);var U=B.references.reduce((function(e,t){return e+t.info.duration||0}),0);x=Math.max(x,U+B.earliestPresentationTime/B.timescale)}}x&&T(x)&&Object.keys(r).forEach((function(e){r[e].duration||(r[e].duration=x*r[e].timescale-r[e].start)}))}return r}(d,f,this),p=f.audio?g[f.audio.id]:null,v=f.video?g[f.video.id]:null,m=ks(v,1/0),y=ks(p,1/0),E=ks(v,0,!0),S=ks(p,0,!0),_=s,L=0,b=p&&(!v||!l&&y<m||l&&l.trackId===f.audio.id),A=b?p:v;if(A){var I=A.timescale,R=A.start-s*I,P=b?f.audio.id:f.video.id;_=A.start/I,L=b?S-y:E-m,!n&&l||!function(e,t,i,r){if(null===e)return!0;var s=Math.max(r,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>s}(l,_,s,L)&&I===l.timescale||(l&&this.warn("Timestamps at playlist time: "+(n?"":"~")+s+" "+R/I+" != initPTS: "+l.baseTime/l.timescale+" ("+l.baseTime+"/"+l.timescale+") trackId: "+l.trackId),this.log("Found initPTS at playlist time: "+s+" offset: "+(_-s)+" ("+R+"/"+I+") trackId: "+P),l=null,c.initPTS=R,c.timescale=I,c.trackId=P)}else this.warn("No audio or video samples found for initPTS at playlist time: "+s);l?(c.initPTS=l.baseTime,c.timescale=l.timescale,c.trackId=l.trackId):(c.timescale&&void 0!==c.trackId&&void 0!==c.initPTS||(this.warn("Could not set initPTS"),c.initPTS=_,c.timescale=1,c.trackId=-1),this.initPTS=l={baseTime:c.initPTS,timescale:c.timescale,trackId:c.trackId});var k=_-l.baseTime/l.timescale,D=k+L;L>0?this.lastEndTime=D:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var w=!!f.audio,C=!!f.video,M="";w&&(M+="audio"),C&&(M+="video");var O={data1:d,startPTS:k,startDTS:k,endPTS:D,endDTS:D,type:M,hasAudio:w,hasVideo:C,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};u.audio=w&&!C?O:void 0,u.video=C?O:void 0;var x=null==v?void 0:v.sampleCount;if(x){var F=v.keyFrameIndex,N=-1!==F;O.nb=x,O.dropped=0===F||this.isVideoContiguous?0:N?F:x,O.independent=N,O.firstKeyFrame=F,N&&v.keyFrameStart&&(O.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=N),this.isVideoContiguous||(this.isVideoContiguous=N),O.dropped&&this.warn("fmp4 does not start with IDR: firstIDR "+F+"/"+x+" dropped: "+O.dropped+" start: "+(O.firstKeyFramePTS||"NA"))}return u.initSegment=c,u.id3=As(i,s,l,l),r.samples.length&&(u.text=Is(r,s,l)),u},t}(F);function ks(e,t,i){return void 0===i&&(i=!1),void 0!==(null==e?void 0:e.start)?(e.start+(i?e.duration:0))/e.timescale:t}function Ds(e,t,i){var r=e.codec;return r&&r.length>4?r:t===X?"ec-3"===r||"ac-3"===r||"alac"===r?r:"fLaC"===r||"Opus"===r?Be(r,!1):(i.warn('Unhandled audio codec "'+r+'" in mp4 MAP'),r||"mp4a"):(i.warn('Unhandled video codec "'+r+'" in mp4 MAP'),r||"avc1")}try{Rs=self.performance.now.bind(self.performance)}catch(e){Rs=Date.now}var ws=[{demux:es,remux:Ps},{demux:ls,remux:Ls},{demux:Yr,remux:Ls},{demux:Jr,remux:Ls}];ws.splice(2,0,{demux:Xr,remux:Ls});var Cs=function(){function e(e,t,i,r,s,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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.id=s,this.logger=n}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,i,r){var s=this,n=i.transmuxing;n.executeStart=Rs();var a=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var h=r||o,u=h.contiguous,d=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,p=h.initSegmentChange,v=l.audioCodec,m=l.videoCodec,y=l.defaultInitPts,E=l.duration,S=l.initSegmentData,T=function(e,t){var i=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t),i}(a,t);if(T&&oi(T.method)){var _=this.getDecrypter(),L=li(T.method);if(!_.isSync())return this.asyncResult=!0,this.decryptionPromise=_.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,L).then((function(e){var t=s.push(e,null,i);return s.decryptionPromise=null,t})),this.decryptionPromise;var R=_.softwareDecrypt(a,T.key.buffer,T.iv.buffer,L);if(i.part>-1){var P=_.flush();R=P?P.buffer:P}if(!R)return n.executeEnd=Rs(),Ms(i);a=new Uint8Array(R)}var k=this.needsProbing(d,c);if(k){var D=this.configureTransmuxer(a);if(D)return this.logger.warn("[transmuxer] "+D.message),this.observer.emit(I.ERROR,I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),n.executeEnd=Rs(),Ms(i)}(d||c||p||k)&&this.resetInitSegment(S,v,m,E,t),(d||p||k)&&this.resetInitialTimestamp(y),u||this.resetContiguity();var w=this.transmux(a,T,g,f,i);this.asyncResult=Os(w);var C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,n.executeEnd=Rs(),w},t.flush=function(e){var t=this,i=e.transmuxing;i.executeStart=Rs();var r=this.decrypter,s=this.currentTransmuxState,n=this.decryptionPromise;if(n)return this.asyncResult=!0,n.then((function(){return t.flush(e)}));var a=[],o=s.timeOffset;if(r){var l=r.flush();l&&a.push(this.push(l.buffer,null,e))}var h=this.demuxer,u=this.remuxer;if(!h||!u){i.executeEnd=Rs();var d=[Ms(e)];return this.asyncResult?Promise.resolve(d):d}var c=h.flush(o);return Os(c)?(this.asyncResult=!0,c.then((function(i){return t.flushRemux(a,i,e),a}))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)},t.flushRemux=function(e,t,i){var r=t.audioTrack,s=t.videoTrack,n=t.id3Track,a=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,h=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+i.sn+(i.part>-1?" part: "+i.part:"")+" of "+(this.id===w?"level":"track")+" "+i.level);var u=this.remuxer.remux(r,s,n,a,h,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Rs()},t.resetInitialTimestamp=function(e){var t=this.demuxer,i=this.remuxer;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,i,r,s){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,s))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,i,r,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s)},t.transmuxUnencrypted=function(e,t,i,r){var s=this.demuxer.demux(e,t,!1,!this.config.progressive),n=s.audioTrack,a=s.videoTrack,o=s.id3Track,l=s.textTrack;return{remuxResult:this.remuxer.remux(n,a,o,l,t,i,!1,this.id),chunkMeta:r}},t.transmuxSampleAes=function(e,t,i,r,s){var n=this;return this.demuxer.demuxSampleAes(e,t,i).then((function(e){return{remuxResult:n.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,n.id),chunkMeta:s}}))},t.configureTransmuxer=function(e){for(var t,i=this.config,r=this.observer,s=this.typeSupported,n=0,a=ws.length;n<a;n++){var o;if(null!=(o=ws[n].demux)&&o.probe(e,this.logger)){t=ws[n];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,h=this.remuxer,u=t.remux,d=t.demux;h&&h instanceof u||(this.remuxer=new u(r,i,s,this.logger)),l&&l instanceof d||(this.demuxer=new d(r,i,s,this.logger),this.probe=d.probe)},t.needsProbing=function(e,t){return!this.demuxer||!this.remuxer||e||t},t.getDecrypter=function(){var e=this.decrypter;return e||(e=this.decrypter=new Bt(this.config)),e},e}(),Ms=function(e){return{remuxResult:{},chunkMeta:e}};function Os(e){return"then"in e&&e.then instanceof Function}var xs=function(e,t,i,r,s){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=s||null},Fs=function(e,t,i,r,s,n){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=s,this.initSegmentChange=n},Ns=[];function Bs(e,t,i){if(!((r=t.remuxResult).audio||r.video||r.text||r.id3||r.initSegment))return!1;var r,s=[],n=t.remuxResult,a=n.audio,o=n.video;return a&&Us(s,a),o&&Us(s,o),e.postMessage({event:"transmuxComplete",data:t,instanceNo:i},s),!0}function Us(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function Gs(e,t,i,r){t.reduce((function(t,i){return Bs(e,i,r)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0],instanceNo:r}),e.postMessage({event:"flush",data:i,instanceNo:r})}function Hs(e,t,i){self.postMessage({event:e,data:t,instanceNo:i})}void 0!==i&&i&&self.addEventListener("message",(function(e){var t=e.data,i=t.instanceNo;if(void 0!==i){var r=Ns[i];if("reset"===t.cmd&&(delete Ns[t.resetNo],r&&r.destroy(),t.cmd="init"),"init"===t.cmd){var s=JSON.parse(t.config),n=new y;n.on(I.FRAG_DECRYPTED,Hs),n.on(I.ERROR,Hs);var a=K(s.debug,t.id);return function(e,t){var i=function(i){e[i]=function(){var e=Array.prototype.join.call(arguments," ");Hs("workerLog",{logType:i,message:e},t)}};for(var r in e)i(r)}(a,i),Ns[i]=new Cs(n,t.typeSupported,s,"",t.id,a),void Hs("init",null,i)}if(r)switch(t.cmd){case"configure":r.configure(t.config);break;case"demux":var o=r.push(t.data,t.decryptdata,t.chunkMeta,t.state);Os(o)?o.then((function(e){Bs(self,e,i)})).catch((function(e){Hs(I.ERROR,{instanceNo:i,type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker push error"},i)})):Bs(self,o,i);break;case"flush":var l=t.chunkMeta,h=r.flush(l);Os(h)?h.then((function(e){Gs(self,e,l,i)})).catch((function(e){Hs(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker flush error"},i)})):Gs(self,h,l,i)}}}));var Ks="1.6.12",Vs={},$s=0,Ws=function(){function e(e,i,r,s){var n=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=$s++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,i=n.hls;if(i&&null!=t&&t.event&&t.instanceNo===n.instanceNo)switch(t.event){case"init":var r,s=null==(r=n.workerContext)?void 0:r.objectURL;s&&self.URL.revokeObjectURL(s);break;case"transmuxComplete":n.handleTransmuxComplete(t.data);break;case"flush":n.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=n.frag,t.data.part=n.part,t.data.id=n.id,i.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(n.hls){var t=new Error(e.message+" ("+e.filename+":"+e.lineno+")");n.hls.config.enableWorker=!1,n.hls.logger.warn('Error in "'+n.id+'" Web Worker, fallback to inline'),n.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var a=e.config;this.hls=e,this.id=i,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=r,this.onFlush=s;var o=function(e,t){(t=t||{}).frag=n.frag||void 0,e===I.ERROR&&(t.parent=n.id,t.part=n.part,n.error=t.error),n.hls.trigger(e,t)};this.observer=new y,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);var l=Ke(a.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var h=this.hls.logger;a.workerPath;try{a.workerPath?(h.log("loading Web Worker "+a.workerPath+' for "'+i+'"'),this.workerContext=function(e){var t=Vs[e];if(t)return t.clientCount++,t;var i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Vs[e]=r,r}(a.workerPath)):(h.log('injecting Web Worker for "'+i+'"'),this.workerContext=function(){var e=Vs[Ks];if(e)return e.clientCount++,e;var i=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+t.toString()+")(true);"],{type:"text/javascript"}),r=self.URL.createObjectURL(i),s={worker:new self.Worker(r),objectURL:r,clientCount:1};return Vs[Ks]=s,s}());var u=this.workerContext.worker;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:i,config:it(a)})}catch(t){h.warn('Error setting up "'+i+'" Web Worker, fallback to inline',t),this.terminateWorker(),this.error=null,this.transmuxer=new Cs(this.observer,l,a,"",i,e.logger)}}else this.transmuxer=new Cs(this.observer,l,a,"",i,e.logger)}var i=e.prototype;return i.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=$s++;var t=this.hls.config,i=Ke(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:it(t)})}},i.terminateWorker=function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=Vs[e||Ks];if(t&&1==t.clientCount--){var i=t.worker,r=t.objectURL;delete Vs[e||Ks],r&&self.URL.revokeObjectURL(r),i.terminate()}}(this.hls.config.workerPath)}},i.destroy=function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null},i.push=function(e,t,i,r,s,n,a,o,l,h){var u,d,c=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,g=this.transmuxer,p=n?n.start:s.start,v=s.decryptdata,m=this.frag,y=!(m&&s.cc===m.cc),E=!(m&&l.level===m.level),S=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,_=0===S&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),L=!E&&(1===S||0===S&&(1===T||_&&T<=0)),b=self.performance.now();(E||S||0===s.stats.parsing.start)&&(s.stats.parsing.start=b),!n||!T&&L||(n.stats.parsing.start=b);var A=!(m&&(null==(u=s.initSegment)?void 0:u.url)===(null==(d=m.initSegment)?void 0:d.url)),I=new Fs(y,L,o,E,p,A);if(!L||y||A){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+s.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===w?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+p+"\n initSegmentChange: "+A);var R=new xs(i,r,t,a,h);this.configureTransmuxer(R)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:v,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(g){var P=g.push(e,v,l,I);Os(P)?P.then((function(e){c.handleTransmuxComplete(e)})).catch((function(e){c.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(P)}},i.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var i=this.instanceNo,r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:e});else if(r){var s=r.flush(e);Os(s)?s.then((function(i){t.handleFlushResult(i,e)})).catch((function(i){t.transmuxerError(i,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}},i.transmuxerError=function(e,t,i){this.hls&&(this.error=e,this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))},i.handleFlushResult=function(e,t){var i=this;e.forEach((function(e){i.handleTransmuxComplete(e)})),this.onFlush(t)},i.configureTransmuxer=function(e){var t=this.instanceNo,i=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)},i.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}(),qs=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"audio-stream-controller",C)||this).mainAnchor=null,s.mainFragLoading=null,s.audioOnly=!1,s.bufferedTrack=null,s.switchingTrack=null,s.trackId=-1,s.waitingData=null,s.mainDetails=null,s.flushing=!1,s.bufferFlushed=!1,s.cachedTrackLoadedData=null,s.registerListeners(),s}o(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.resetItem()},i.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(I.BUFFER_RESET,this.onBufferReset,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(I.FRAG_LOADING,this.onFragLoading,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){var t=this.hls;t&&(e.prototype.unregisterListeners.call(this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(I.BUFFER_RESET,this.onBufferReset,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(I.FRAG_LOADING,this.onFragLoading,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this))},i.onInitPtsFound=function(e,t){var i=t.frag,r=t.id,s=t.initPTS,n=t.timescale,a=t.trackId;if(r===w){var o=i.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:s,timescale:n,trackId:a},this.log("InitPTS for cc: "+o+" found from main: "+s/n+" ("+s+"/"+n+") trackId: "+a),this.mainAnchor=i,this.state===lr.WAITING_INIT_PTS){var h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==o)&&this.syncWithAnchor(i,null==h?void 0:h.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(i,l)):this.state===lr.IDLE&&this.tick()}},i.getLoadPosition=function(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:e.prototype.getLoadPosition.call(this)},i.syncWithAnchor=function(e,t){var i,r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(!t||(null==r?void 0:r.cc)!==t.cc){var s=(r||e).cc,n=vt(this.getLevelDetails(),s,this.getLoadPosition());n&&(this.log("Syncing with main frag at "+n.start+" cc "+n.cc),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===lr.IDLE&&this.doTickIdle())}},i.startLoad=function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=lr.STOPPED);var i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i,this.state=lr.IDLE):this.state=lr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.doTick=function(){switch(this.state){case lr.IDLE:this.doTickIdle();break;case lr.WAITING_TRACK:var t=this.levels,i=this.trackId,r=null==t?void 0:t[i],s=null==r?void 0:r.details;if(s&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(s))break;this.state=lr.WAITING_INIT_PTS}break;case lr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case lr.WAITING_INIT_PTS:var n=this.waitingData;if(n){var a=n.frag,o=n.part,l=n.cache,h=n.complete,u=this.mainAnchor;if(void 0!==this.initPTS[a.cc]){this.waitingData=null,this.state=lr.FRAG_LOADING;var d={frag:a,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),h&&e.prototype._handleFragmentLoadComplete.call(this,d)}else u&&u.cc!==n.frag.cc&&this.syncWithAnchor(u,n.frag)}else this.state=lr.IDLE}this.onTickEnd()},i.resetLoadingState=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),e.prototype.resetLoadingState.call(this)},i.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)},i.doTickIdle=function(){var e,t=this.hls,i=this.levels,r=this.media,s=this.trackId,n=t.config;if(this.buffering&&(r||this.primaryPrefetch||!this.startFragRequested&&n.startFragPrefetch)&&null!=i&&i[s]){var a=i[s],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=lr.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,X,C));var h=this.getFwdBufferInfo(l,C);if(null!==h){if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(I.BUFFER_EOS,{type:"audio"}),void(this.state=lr.ENDED);var u=h.len,d=t.maxBufferLength,c=o.fragments,f=c[0].start,g=this.getLoadPosition(),p=this.flushing?g:h.end;if(this.switchingTrack&&r){var v=g;o.PTSKnown&&v<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(!(u>=d&&!this.switchingTrack&&p<c[c.length-1].start)){var m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,h,w,d)),m){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&ee(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Dt&&(this.mainFragLoading=y=null),y&&ee(y))){if(m.start>y.end){var E=this.fragmentTracker.getFragAtPos(p,w);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(m.start>y.end)return}this.loadFragment(m,a,p)}else this.bufferFlushed=!0}}}},i.onMediaDetaching=function(t,i){this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this,t,i)},i.onAudioTracksUpdated=function(e,t){var i=t.audioTracks;this.resetTransmuxer(),this.levels=i.map((function(e){return new et(e)}))},i.onAudioTrackSwitching=function(e,t){var i=!!t.url;this.trackId=t.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==lr.STOPPED&&(this.setInterval(100),this.state=lr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},i.onLevelLoaded=function(e,t){this.mainDetails=t.details;var i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(I.AUDIO_TRACK_LOADED,i))},i.onAudioTrackLoaded=function(e,t){var i,r=this.levels,s=t.details,n=t.id,a=t.groupId,o=t.track;if(r){var l=this.mainDetails;if(!l||s.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==lr.STOPPED&&(this.state=lr.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+n+' "'+o.name+'" of "'+a+'" loaded ['+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+",duration:"+s.totalduration);var h=r[n],u=0;if(s.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;var d;h.details&&(u=this.alignPlaylists(s,h.details,null==(d=this.levelLastLoaded)?void 0:d.details)),s.alignedSliding||(sr(s,l),s.alignedSliding||nr(s,l),u=s.fragmentStart)}h.details=s,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(I.AUDIO_TRACK_UPDATED,{details:s,id:n,groupId:t.groupId}),this.state!==lr.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=lr.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+n+' "'+o.name+'" of "'+a+'"')},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,s=e.payload,n=this.config,a=this.trackId,o=this.levels;if(o){var l=o[a];if(l){var h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);var u=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new Ws(this.hls,C,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){var g=r?r.index:-1,p=-1!==g,v=new Wt(i.level,i.sn,i.stats.chunkCount,s.byteLength,g,p);d.push(s,f,u,"",i,r,h.totalduration,!1,v,c)}else this.log("Unknown video PTS for cc "+i.cc+", waiting for video PTS before demuxing audio frag "+i.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+a),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new dr,complete:!1}).cache.push(new Uint8Array(s)),this.state!==lr.STOPPED&&(this.state=lr.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},i.onBufferReset=function(){this.mediaBuffer=null},i.onBufferCreated=function(e,t){this.bufferFlushed=this.flushing=!1;var i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)},i.onFragLoading=function(e,t){!this.audioOnly&&t.frag.type===w&&ee(t.frag)&&(this.mainFragLoading=t,this.state===lr.IDLE&&this.tick())},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part;if(i.type===C)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"));else{if(ee(i)){this.fragPrevious=i;var s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,u({},s)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==w||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},i.onError=function(t,i){var r;if(i.fatal)this.state=lr.ERROR;else switch(i.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(C,i);break;case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==lr.WAITING_TRACK||(null==(r=i.context)?void 0:r.type)!==k||(this.state=lr.IDLE);break;case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)||this.resetLoadingState();break;case A.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}},i.onBufferFlushing=function(e,t){t.type!==Q&&(this.flushing=!0)},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==Q){this.flushing=!1,this.bufferFlushed=!0,this.state===lr.ENDED&&(this.state=lr.IDLE);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,C),this.tick())}},i._handleTransmuxComplete=function(e){var t,i="audio",r=this.hls,s=e.remuxResult,a=e.chunkMeta,o=this.getCurrentContext(a);if(o){var l=o.frag,h=o.part,u=o.level,d=u.details,c=s.audio,f=s.text,g=s.id3,p=s.initSegment;if(!this.fragContextChanged(l)&&d){if(this.state=lr.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){var v=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,v,a),r.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:p.tracks})}if(c){var m=c.startPTS,y=c.endPTS,E=c.startDTS,S=c.endDTS;h&&(h.elementaryStreams[X]={startPTS:m,endPTS:y,startDTS:E,endDTS:S}),l.setElementaryStreamInfo(X,m,y,E,S),this.bufferFragmentData(c,l,h,a)}if(null!=g&&null!=(t=g.samples)&&t.length){var T=n({id:i,frag:l,details:d},g);r.trigger(I.FRAG_PARSING_METADATA,T)}if(f){var _=n({id:i,frag:l,details:d},f);r.trigger(I.FRAG_PARSING_USERDATA,_)}}else this.fragmentTracker.removeFragment(l)}else this.resetWhenMissingContext(a)},i._bufferInitSegment=function(e,t,i,r){if(this.state===lr.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var s=t.audio;s.id=C;var n=e.audioCodec;this.log("Init audio buffer, container:"+s.container+", codecs[level/parsed]=["+n+"/"+s.codec+"]"),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(I.BUFFER_CODECS,t);var a=s.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(I.BUFFER_APPENDING,o)}this.tickImmediate()}},i.loadFragment=function(t,i,r){var s,n=this.fragmentTracker.getState(t);if(this.switchingTrack||n===Rt||n===kt)if(ee(t))if(null!=(s=i.details)&&s.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=lr.WAITING_INIT_PTS;var a=this.mainDetails;a&&a.fragmentStart!==i.details.fragmentStart&&nr(i.details,a)}else e.prototype.loadFragment.call(this,t,i,r);else this._loadInitSegment(t,i);else this.clearTrackerIfNeeded(t)},i.flushAudioIfNeeded=function(t){if(this.media&&this.bufferedTrack){var i=this.bufferedTrack;ot({name:i.name,lang:i.lang,assocLang:i.assocLang,characteristics:i.characteristics,audioCodec:i.audioCodec,channels:i.channels},t,lt)||(ut(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}},i.completeAudioSwitch=function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(I.AUDIO_TRACK_SWITCHED,u({},e))},t}(hr),js=function(e){function t(t,i){var r;return(r=e.call(this,i,t.logger)||this).hls=void 0,r.canLoad=!1,r.timer=-1,r.hls=t,r}o(t,e);var i=t.prototype;return i.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},i.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},i.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},i.stopLoad=function(){this.canLoad=!1,this.clearTimer()},i.switchParams=function(e,t,i){var r=null==t?void 0:t.renditionReports;if(r){for(var s=-1,n=0;n<r.length;n++){var a=r[n],o=void 0;try{o=new self.URL(a.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: "+e),o=a.URI||""}if(o===e){s=n;break}o===e.substring(0,o.length)&&(s=n)}if(-1!==s){var l=r[s],h=parseInt(l["LAST-MSN"])||t.lastPartSn,u=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);u>=0&&d>t.partTarget&&(u+=1)}var c=i&&Je(i);return new Ze(h,u>=0?u:void 0,c)}}},i.loadPlaylist=function(e){this.clearTimer()},i.loadingPlaylist=function(e,t){this.clearTimer()},i.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},i.getUrlWithDirectives=function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}return e},i.playlistLoaded=function(e,t,i){var r=t.details,s=t.stats,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;r.advancedDateTime=Date.now()-a;var o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){var l=Math.max(o||0,0);r.appliedTimelineOffset=l,r.fragments.forEach((function(e){e.setStart(e.playlistOffset+l)}))}if(r.live||null!=i&&i.live){var h="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){$i(i,r,this);var u=r.playlistParsingError;if(u){this.warn(u);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var c,f=t.networkDetails;return void d.trigger(I.ERROR,{type:b.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:u,reason:u.message,level:t.level||void 0,parent:null==(c=r.fragments[0])?void 0:c.type,networkDetails:f,stats:s})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);var g,p=this.hls.mainForwardBufferInfo,v=p?p.end-p.len:0,m=Yi(r,1e3*(r.edge-v));if(r.requestScheduled+m<n?r.requestScheduled=n:r.requestScheduled+=m,this.log("live playlist "+e+" "+(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;var y=void 0,E=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){var S=this.hls.config.lowLatencyMode,T=r.lastPartSn,_=r.endSN,L=r.lastPartIndex,R=T===_;-1!==L?R?(y=_+1,E=S?0:L):(y=T,E=S?L+1:r.maxPartIndex):y=_+1;var P=r.age,k=P+r.ageHeader,D=Math.min(k-r.partTarget,1.5*r.targetduration);if(D>0){if(k>3*r.targetduration)this.log("Playlist last advanced "+P.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=i&&i.tuneInGoal&&k-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+i.tuneInGoal+" to: "+D+" with playlist age: "+r.age),D=0;else{var w=Math.floor(D/r.targetduration);y+=w,void 0!==E&&(E+=Math.round(D%r.targetduration/r.partTarget)),this.log("CDN Tune-in age: "+r.ageHeader+"s last advanced "+P.toFixed(2)+"s goal: "+D+" skip sn "+w+" to part "+E)}r.tuneInGoal=D}if(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E),S||!R)return r.requestScheduled=n,void this.loadingPlaylist(h,g)}else(r.canBlockReload||r.canSkipUntil)&&(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E));g&&void 0!==y&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(m-2*a,m/2)),this.scheduleLoading(h,g,r)}else this.clearTimer()},i.scheduleLoading=function(e,t,i){var r=this,s=i||e.details;if(s){var n=self.performance.now(),a=s.requestScheduled;if(n>=a)this.loadingPlaylist(e,t);else{var o=a-n;this.log("reload live playlist "+(e.name||e.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return r.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},i.getDeliveryDirectives=function(e,t,i,r){var s=Je(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=""),new Ze(i,r,s)},i.checkRetry=function(e){var t=this,i=e.details,r=mt(e),s=e.errorAction,n=s||{},a=n.action,o=n.retryCount,l=void 0===o?0:o,h=n.retryConfig,u=!!s&&!!h&&(5===a||!s.resolved&&2===a);if(u){var d;if(l>=h.maxNumRetry)return!1;if(r&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" without delivery-directives'),this.loadPlaylist();else{var c=Tt(h,l);this.clearTimer(),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" in '+c+"ms")}e.levelRetry=!0,s.resolved=!0}return u},t}(F);function Ys(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(!zs(e[i].attrs,t[i].attrs))return!1;return!0}function zs(e,t,i){var r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((function(i){return e[i]!==t[i]}))}function Xs(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var Qs=function(e){function t(t){var i;return(i=e.call(this,t,"audio-track-controller")||this).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.registerListeners(),i}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.ERROR,this.onError,this)},i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,e.prototype.destroy.call(this)},i.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.audioTracks||[]},i.onAudioTrackLoaded=function(e,t){var i=t.id,r=t.groupId,s=t.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=t.details,this.log("Audio track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Audio track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(e,t){e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.audioPreference;if(!s&&a){var o=at(a,n,lt);if(o>-1)s=n[o];else{var l=at(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var u={audioTracks:n};this.log("Updating audio tracks, "+n.length+" track(s) found in group(s): "+(null==i?void 0:i.join(","))),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,u);var d=this.trackId;if(-1!==h&&-1===d)this.setAudioTrack(h);else if(n.length&&-1===d){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+n.length);this.warn(f.message),this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==k||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&ot(e,r,lt))return r;var s=at(e,this.tracksInGroup,lt);if(s>-1){var n=this.tracksInGroup[s];return this.setAudioTrack(s),n}if(r){var a=t.loadLevel;-1===a&&(a=t.firstAutoLevel);var o=function(e,t,i,r,s){var n=t[r],a=t.reduce((function(e,t,i){var r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));var o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),u=ht(t,r,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;var r=t.audioGroups,n=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return at(e,n,s)>-1}));return u>-1?u:ht(t,r,(function(t){var r=t.audioGroups,n=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return at(e,n,s)>-1}))}(e,t.levels,i,a,lt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=at(e,i);if(l>-1)return i[l]}}}return null},i.setAudioTrack=function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(!(e===this.trackId&&r===i&&s||(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(I.AUDIO_TRACK_SWITCHING,u({},r)),s))){var n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=0;i<t.length;i++){var r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||ot(e,r,lt)))return i}if(e){for(var s=e.name,n=e.lang,a=e.assocLang,o=e.characteristics,l=e.audioCodec,h=e.channels,u=0;u<t.length;u++)if(ot({name:s,lang:n,assocLang:a,characteristics:o,audioCodec:l,channels:h},t[u],lt))return u;for(var d=0;d<t.length;d++){var c=t[d];if(zs(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var g=t[f];if(zs(e.attrs,g.attrs,["LANGUAGE"]))return f}}return-1},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var i=this.currentTrack;this.shouldLoadPlaylist(i)&&ut(i.url,this.hls)&&this.scheduleLoading(i,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,s=t.groupId,n=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading audio-track "+r+' "'+t.name+'" lang:'+t.lang+" group:"+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+n),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:i||null,track:t})},r(t,[{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}}])}(js),Js=function(){function e(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}var t=e.prototype;return t.destroy=function(){this.tracks=this.queues=null},t.append=function(e,t,i){if(null!==this.queues&&null!==this.tracks){var r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}},t.appendBlocker=function(e){var t=this;return new Promise((function(i){var r={label:"async-blocker",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(r,e)}))},t.prependBlocker=function(e){var t=this;return new Promise((function(i){if(t.queues){var r={label:"async-blocker-prepend",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(r)}}))},t.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(e){var t,i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))}))},t.unblockAudio=function(e){null!==this.queues&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")},t.executeNext=function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var i=t[0];try{i.execute()}catch(t){var r;if(i.onError(t),null===this.queues||null===this.tracks)return;var s=null==(r=this.tracks[e])?void 0:r.buffer;null!=s&&s.updating||this.shiftAndExecuteNext(e)}}}},t.shiftAndExecuteNext=function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))},t.current=function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null},t.toString=function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},t.list=function(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?"SourceBuffer"+(r.updating?" updating":"")+(i.ended?" ended":"")+(i.ending?" ending":""):"none"},t.listOps=function(e){var t;return(null==(t=this.queues)?void 0:t[e].map((function(e){return e.label})).join(", "))||""},e}(),Zs=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,en="HlsJsTrackRemovedError",tn=function(e){function t(t){var i;return(i=e.call(this,t)||this).name=en,i}return o(t,e),t}(f(Error)),rn=function(e){function t(t,i){var r,s;return(r=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.details=null,r._objectUrl=null,r.operationQueue=null,r.bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.lastMpegAudioChunk=null,r.blockedAudioAppend=null,r.lastVideoAppendEnd=0,r.appendSource=void 0,r.transferData=void 0,r.overrides=void 0,r.appendErrors={audio:0,video:0,audiovideo:0},r.tracks={},r.sourceBuffers=[[null,null],[null,null]],r._onEndStreaming=function(e){var t;r.hls&&"open"===(null==(t=r.mediaSource)?void 0:t.readyState)&&r.hls.pauseBuffering()},r._onStartStreaming=function(e){r.hls&&r.hls.resumeBuffering()},r._onMediaSourceOpen=function(e){var t=r,i=t.media,s=t.mediaSource;e&&r.log("Media source opened"),i&&s&&(s.removeEventListener("sourceopen",r._onMediaSourceOpen),i.removeEventListener("emptied",r._onMediaEmptied),r.updateDuration(),r.hls.trigger(I.MEDIA_ATTACHED,{media:i,mediaSource:s}),null!==r.mediaSource&&r.checkPendingTracks())},r._onMediaSourceClose=function(){r.log("Media source closed")},r._onMediaSourceEnded=function(){r.log("Media source ended")},r._onMediaEmptied=function(){var e=r,t=e.mediaSrc,i=e._objectUrl;t!==i&&r.error("Media element src was set while attaching MediaSource ("+i+" > "+t+")")},r.hls=t,r.fragmentTracker=i,r.appendSource=(s=$(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),r.initTracks(),r.registerListeners(),r}o(t,e);var i=t.prototype;return i.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},i.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null},i.registerListeners=function(){var e=this.hls;e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_APPENDING,this.onBufferAppending,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.BUFFER_EOS,this.onBufferEos,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.FRAG_PARSED,this.onFragParsed,this),e.on(I.FRAG_CHANGED,this.onFragChanged,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_APPENDING,this.onBufferAppending,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_EOS,this.onBufferEos,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.FRAG_PARSED,this.onFragParsed,this),e.off(I.FRAG_CHANGED,this.onFragChanged,this),e.off(I.ERROR,this.onError,this)},i.transferMedia=function(){var e=this,t=this.media,i=this.mediaSource;if(!t)return null;var r={};if(this.operationQueue){var s=this.isUpdating();s||this.operationQueue.removeBlockers();var a=this.isQueued();(s||a)&&this.warn("Transfering MediaSource with"+(a?" operations in queue":"")+(s?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var o=this.transferData;return!this.sourceBufferCount&&o&&o.mediaSource===i?n(r,o.tracks):this.sourceBuffers.forEach((function(t){var i=t[0];i&&(r[i]=n({},e.tracks[i]),e.removeBuffer(i)),t[0]=t[1]=null})),{media:t,mediaSource:i,tracks:r}},i.initTracks=function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},i.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},i.onManifestParsed=function(e,t){var i,r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(r+" bufferCodec event(s) expected."),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()},i.onMediaAttaching=function(e,t){var i=this.media=t.media;this.transferData=this.overrides=void 0;var r=$(this.appendSource);if(r){var s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var n=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(n),s)this._objectUrl=i.src,this.attachTransferred();else{var a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&n instanceof o,sn(i),function(e,t){var i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,a),i.load()}catch(e){i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}},i.assignMediaSource=function(e){var t,i;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(i=e.constructor)?void 0:i.name)),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))},i.attachTransferred=function(){var e=this,t=this.media,i=this.transferData;if(i&&t){var r=this.tracks,s=i.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=function(){Promise.resolve().then((function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()}))};if(s&&n&&a){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+it(r,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+it(s,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!W(s,r)){i.mediaSource=null,i.tracks=void 0;var l=t.currentTime,h=this.details,u=Math.max(l,(null==h?void 0:h.fragments[0].start)||0);return u-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+u):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(s)+'"->"'+Object.keys(r)+'") start time: '+u+" currentTime: "+l),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,i),void(t.currentTime=u))}this.transferData=void 0,n.forEach((function(t){var i=t,r=s[i];if(r){var n=r.buffer;if(n){var a=e.fragmentTracker,o=r.id;if(a.hasFragments(o)||a.hasParts(o)){var l=jt.getBuffered(n);a.detectEvictedFragments(i,l,o,null,!0)}var h=nn(i),u=[i,n];e.sourceBuffers[h]=u,n.updating&&e.operationQueue&&e.operationQueue.prependBlocker(i),e.trackSourceBuffer(i,r)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},i.onMediaDetaching=function(e,t){var i=this,r=!!t.transferMedia;this.transferData=this.overrides=void 0;var s=this.media,n=this.mediaSource,a=this._objectUrl;if(n){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===n.readyState;try{for(var l=n.sourceBuffers,h=l.length;h--;)o&&l[h].abort(),n.removeSourceBuffer(l[h]);o&&n.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&sn(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(I.MEDIA_DETACHED,t)},i.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];i&&e.resetBuffer(i)})),this.initTracks()},i.resetBuffer=function(e){var t,i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},i.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[nn(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)},i.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Js(this.tracks)},i.onBufferCodecs=function(e,t){var i,r=this,s=this.tracks,n=Object.keys(t);this.log('BUFFER_CODECS: "'+n+'" (current SB count '+this.sourceBufferCount+")");var a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some((function(e){return!s[e]}));a||o?this.warn('Unsupported transition between "'+Object.keys(s)+'" and "'+n+'" SourceBuffers'):(n.forEach((function(e){var i,n,a=t[e],o=a.id,l=a.codec,h=a.levelCodec,u=a.container,d=a.metadata,c=a.supplemental,f=s[e],g=null==(i=r.transferData)||null==(i=i.tracks)?void 0:i[e],p=null!=g&&g.buffer?g:f,v=(null==p?void 0:p.pendingCodec)||(null==p?void 0:p.codec),m=null==p?void 0:p.levelCodec;f||(f=s[e]={buffer:void 0,listeners:[],codec:l,supplemental:c,container:u,levelCodec:h,metadata:d,id:o});var y=Ue(v,m),E=null==y?void 0:y.replace(Zs,"$1"),S=Ue(l,h),T=null==(n=S)?void 0:n.replace(Zs,"$1");S&&y&&E!==T&&("audio"===e.slice(0,5)&&(S=Be(S,r.appendSource)),r.log("switching codec "+v+" to "+S),S!==(f.pendingCodec||f.codec)&&(f.pendingCodec=S),f.container=u,r.appendChangeType(e,u,S))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(i=t.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))},i.appendChangeType=function(e,t,i){var r=this,s=t+";codecs="+i,n={label:"change-type="+s,execute:function(){var n=r.tracks[e];if(n){var a=n.buffer;null!=a&&a.changeType&&(r.log("changing "+e+" sourceBuffer type to "+s),a.changeType(s),n.codec=i,n.container=t)}r.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(n,e,this.isPending(this.tracks[e]))},i.blockAudio=function(e){var t,i=this,r=e.start,s=r+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(r,w))?void 0:t.gap)){var n={label:"block-audio",execute:function(){var e,t=i.tracks.video;(i.lastVideoAppendEnd>s||null!=t&&t.buffer&&jt.isBuffered(t.buffer,s)||!0===(null==(e=i.fragmentTracker.getAppendedFrag(s,w))?void 0:e.gap))&&(i.blockedAudioAppend=null,i.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){i.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}},i.unblockAudio=function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))},i.onBufferAppending=function(e,t){var i=this,r=this.tracks,s=t.data,n=t.type,a=t.parent,o=t.frag,l=t.part,h=t.chunkMeta,u=t.offset,d=h.buffering[n],c=o.sn,f=o.cc,g=self.performance.now();d.start=g;var p=o.stats.buffering,v=l?l.stats.buffering:null;0===p.start&&(p.start=g),v&&0===v.start&&(v.start=g);var m=r.audio,y=!1;"audio"===n&&"audio/mpeg"===(null==m?void 0:m.container)&&(y=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var E=r.video,S=null==E?void 0:E.buffer;if(S&&"initSegment"!==c){var _=l||o,L=this.blockedAudioAppend;if("audio"!==n||"main"===a||this.blockedAudioAppend||E.ending||E.ended){if("video"===n){var R=_.end;if(L){var P=L.frag.start;(R>P||R<this.lastVideoAppendEnd||jt.isBuffered(S,P))&&this.unblockAudio()}this.lastVideoAppendEnd=R}}else{var k=_.start+.05*_.duration,D=S.buffered,C=this.currentOp("video");D.length||C?!C&&!jt.isBuffered(S,k)&&this.lastVideoAppendEnd<k&&this.blockAudio(_):this.blockAudio(_)}}var M=(l||o).start,O={label:"append-"+n,execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=i.tracks[n])?void 0:e.buffer;t&&(y?i.updateTimestampOffset(t,M,.1,n,c,f):void 0!==u&&T(u)&&i.updateTimestampOffset(t,u,1e-6,n,c,f)),i.appendExecutor(s,n)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===p.first&&(p.first=e),v&&0===v.first&&(v.first=e);var t={};i.sourceBuffers.forEach((function(e){var i=e[0],r=e[1];i&&(t[i]=jt.getBuffered(r))})),i.appendErrors[n]=0,"audio"===n||"video"===n?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(I.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:t})},onError:function(e){var t,r={type:b.MEDIA_ERROR,parent:o.type,details:A.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1},s=null==(t=i.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)r.details=A.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&i.mediaSourceOpenOrEnded&&!s)r.errorAction=It(!0);else if(e.name===en&&0===i.sourceBufferCount)r.errorAction=It(!0);else{var a=++i.appendErrors[n];i.warn("Failed "+a+"/"+i.hls.config.appendErrorMaxRetry+' times to append segment in "'+n+'" sourceBuffer ('+(s||"no media error")+")"),(a>=i.hls.config.appendErrorMaxRetry||s)&&(r.fatal=!0)}i.hls.trigger(I.ERROR,r)}};this.log('queuing "'+n+'" append sn: '+c+(l?" p: "+l.index:"")+" of "+(o.type===w?"level":"track")+" "+o.level+" cc: "+f),this.append(O,n,this.isPending(this.tracks[n]))},i.getFlushOp=function(e,t,i){var r=this;return this.log('queuing "'+e+'" remove '+t+"-"+i),{label:"remove",execute:function(){r.removeExecutor(e,t,i)},onStart:function(){},onComplete:function(){r.hls.trigger(I.BUFFER_FLUSHED,{type:e})},onError:function(s){r.warn("Failed to remove "+t+"-"+i+' from "'+e+'" SourceBuffer',s)}}},i.onBufferFlushing=function(e,t){var i=this,r=t.type,s=t.startOffset,n=t.endOffset;r?this.append(this.getFlushOp(r,s,n),r):this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.append(i.getFlushOp(t,s,n),t)}))},i.onFragParsed=function(e,t){var i=this,r=t.frag,s=t.part,n=[],a=s?s.elementaryStreams:r.elementaryStreams;a[J]?n.push("audiovideo"):(a[X]&&n.push("audio"),a[Q]&&n.push("video")),0===n.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+r.type+" level: "+r.level+" sn: "+r.sn),this.blockBuffers((function(){var e=self.performance.now();r.stats.buffering.end=e,s&&(s.stats.buffering.end=e);var t=s?s.stats:r.stats;i.hls.trigger(I.FRAG_BUFFERED,{frag:r,part:s,stats:t,id:r.type})}),n).catch((function(e){i.warn("Fragment buffered callback "+e),i.stepOperationQueue(i.sourceBufferTypes)}))},i.onFragChanged=function(e,t){this.trimBuffers()},i.onBufferEos=function(e,t){var i,r=this;this.sourceBuffers.forEach((function(e){var i=e[0];if(i){var s=r.tracks[i];t.type&&t.type!==i||(s.ending=!0,s.ended||(s.ended=!0,r.log(i+" buffer reached EOS")))}}));var s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,i=e[0];return i&&!(null!=(t=r.tracks[i])&&t.ended)}))?s?(this.log("Queueing EOS"),this.blockUntilOpen((function(){r.tracksEnded();var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream(),r.hls.trigger(I.BUFFERED_TO_END,void 0)):e&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(I.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()},i.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];if(null!==i){var r=e.tracks[i];r&&(r.ending=!1)}}))},i.onLevelUpdated=function(e,t){var i=t.details;i.fragments.length&&(this.details=i,this.updateDuration())},i.updateDuration=function(){var e=this;this.blockUntilOpen((function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)}))},i.onError=function(e,t){if(t.details===A.BUFFER_APPEND_ERROR&&t.frag){var i,r=null==(i=t.errorAction)?void 0:i.nextAutoLevel;T(r)&&r!==t.frag.level&&this.resetAppendErrors()}},i.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},i.trimBuffers=function(){var e=this.hls,t=this.details,i=this.media;if(i&&null!==t&&this.sourceBufferCount){var r=e.config,s=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(T(a)&&a>=0){var o=Math.max(a,n),l=Math.floor(s/n)*n-o;this.flushBackBuffer(s,n,l)}var h=r.frontBufferFlushThreshold;if(T(h)&&h>0){var u=Math.max(r.maxBufferLength,h),d=Math.max(u,n),c=Math.floor(s/n)*n+d;this.flushFrontBuffer(s,n,c)}}},i.flushBackBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(e){var t=e[0],s=e[1];if(s){var n=jt.getBuffered(s);if(n.length>0&&i>n.start(0)){var a;r.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i});var o=r.tracks[t];if(null!=(a=r.details)&&a.live)r.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=o&&o.ended)return void r.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");r.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}}))},i.flushFrontBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(t){var s=t[0],n=t[1];if(n){var a=jt.getBuffered(n),o=a.length;if(o<2)return;var l=a.start(o-1),h=a.end(o-1);if(i>l||e>=l&&e<=h)return;r.hls.trigger(I.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}}))},i.getDurationAndRange=function(){var e,t=this.details,i=this.mediaSource;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;var r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){var s=Math.max(0,t.fragmentStart);return{duration:1/0,start:s,end:Math.max(s,r)}}return{duration:1/0}}var n=null==(e=this.overrides)?void 0:e.duration;if(n)return T(n)?{duration:n}:null;var a=this.media.duration;return r>(T(i.duration)?i.duration:0)&&r>a||!T(a)?{duration:r}:null},i.updateMediaSource=function(e){var t=e.duration,i=e.start,r=e.end,s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==t&&(T(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),s.duration=t),void 0!==i&&void 0!==r&&(this.log("MediaSource duration is set to "+s.duration+". Setting seekable range to "+i+"-"+r+"."),s.setLiveSeekableRange(i,r)))},i.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,i=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+it(i)),this.tracksReady){var r,s=null==(r=this.transferData)?void 0:r.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}},i.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(i){var r=i[0],s=i[1];if(r){var n=e.tracks[r];t[r]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}})),this.hls.trigger(I.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var i=t[0];e.executeNext(i)}))}else{var i=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:i,reason:i.message})}},i.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,i=this.mediaSource;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(var r in e){var s=r,n=e[s];if(this.isPending(n)){var a=this.getTrackCodec(n,s),o=n.container+";codecs="+a;n.codec=a,this.log("creating sourceBuffer("+o+")"+(this.currentOp(s)?" Queued":"")+" "+it(n));try{var l=i.addSourceBuffer(o),h=nn(s),u=[s,l];t[h]=u,n.buffer=l}catch(e){var d;return this.error("error while trying to add sourceBuffer: "+e.message),this.shiftAndExecuteNext(s),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[s],void this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:o,parent:n.id})}this.trackSourceBuffer(s,n)}}this.bufferCreated()},i.getTrackCodec=function(e,t){var i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&we(i,"video")&&(r=function(e,t){var i=[];if(e)for(var r=e.split(","),s=0;s<r.length;s++)De(r[s],"video")||i.push(r[s]);return t&&i.push(t),i.join(",")}(r,i));var s=Ue(r,e.levelCodec);return s?"audio"===t.slice(0,5)?Be(s,this.appendSource):s:""},i.trackSourceBuffer=function(e,t){var i=this,r=t.buffer;if(r){var s=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(function(e,t){var r=t.removedRanges;null!=r&&r.length&&i.hls.trigger(I.BUFFER_FLUSHED,{type:e})}))}},i.onSBUpdateStart=function(e){var t=this.currentOp(e);t&&t.onStart()},i.onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)},i.onSBUpdateError=function(e,t){var i,r=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(i=this.mediaSource)?void 0:i.readyState));this.error(""+r,t),this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});var s=this.currentOp(e);s&&s.onError(r)},i.updateTimestampOffset=function(e,t,i,r,s,n){var a=t-e.timestampOffset;Math.abs(a)>=i&&(this.log("Updating "+r+" SourceBuffer timestampOffset to "+t+" (sn: "+s+" cc: "+n+")"),e.timestampOffset=t)},i.removeExecutor=function(e,t,i){var r=this.media,s=this.mediaSource,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!r||!s||!a)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(e);var o=T(r.duration)?r.duration:1/0,l=T(s.duration)?s.duration:1/0,h=Math.max(0,t),u=Math.min(i,o,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log("Removing ["+h+","+u+"] from the "+e+" SourceBuffer"),a.remove(h,u)):this.shiftAndExecuteNext(e)},i.appendExecutor=function(e,t){var i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new tn("Attempting to append to the "+t+" SourceBuffer, but it does not exist");i.ending=!1,i.ended=!1,r.appendBuffer(e)},i.blockUntilOpen=function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((function(e){t.warn("SourceBuffer blocked callback "+e),t.stepOperationQueue(t.sourceBufferTypes)}));else try{e()}catch(e){this.warn("Callback run without blocking "+this.operationQueue+" "+e)}},i.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],i=e[1];return t&&i.updating}))},i.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var i=t[0];return i&&!!e.currentOp(i)}))},i.isPending=function(e){return!!e&&!e.buffer},i.blockBuffers=function(e,t){var i=this;if(void 0===t&&(t=this.sourceBufferTypes),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var r=this.operationQueue,s=t.map((function(e){return i.appendBlocker(e)}));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then((function(t){r===i.operationQueue&&(e(),i.stepOperationQueue(i.sourceBufferTypes))}))},i.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var i,r=null==(i=t.tracks[e])?void 0:i.buffer;r&&!r.updating&&t.shiftAndExecuteNext(e)}))},i.append=function(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)},i.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},i.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},i.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},i.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},i.addBufferListener=function(e,t,i){var r=this.tracks[e];if(r){var s=r.buffer;if(s){var n=i.bind(this,e);r.listeners.push({event:t,listener:n}),s.addEventListener(t,n)}}},i.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var i=t.buffer;i&&(t.listeners.forEach((function(e){i.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},r(t,[{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){var r=e.tracks[i];return t[i]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var i=t[0];if(i){var r=e.tracks[i];if(r)return!r.ended||r.ending}return!1}))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"mediaSrc",get:function(){var e,t,i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){return t+(e.isPending(e.tracks[i])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(e,t){return e+(t[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(e){return e[0]})).filter((function(e){return!!e}))}}])}(F);function sn(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function nn(e){return"audio"===e?1:0}var an=function(){function e(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},t.registerListeners=function(){var e=this.hls;e.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListener=function(){var e=this.hls;e.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)},t.onFpsDropLevelCapping=function(e,t){var i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})},t.onMediaAttaching=function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},t.onManifestParsed=function(e,t){var i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&T(this.autoLevelCapping)&&this.detectPlayerSize()},t.onBufferCodecs=function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping(),this.media=null},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+i+": "+e[i].height+"p@"+e[i].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var i=this,r=this.hls.levels;if(!r.length)return-1;var s=r.filter((function(e,r){return i.isLevelAllowed(e)&&r<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)},t.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var 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},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,i){if(null==e||!e.length)return-1;for(var r,s,n=e.length-1,a=Math.max(t,i),o=0;o<e.length;o+=1){var l=e[o];if((l.width>=a||l.height>=a)&&(r=l,!(s=e[o+1])||r.width!==s.width||r.height!==s.height)){n=o;break}}return n},r(e,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}}])}(),on="m",ln="a",hn="v",un="av",dn="i",cn="tt",fn="h",gn=function e(t,i){Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=i},pn="Dict";function vn(e,t,i){return function(e,t,i,r){return new Error("failed to "+e+' "'+(s=t,(Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s))+'" as ')+i,{cause:r});var s}("serialize",e,t,i)}var mn=function(e){this.description=e},yn="Bare Item",En="Boolean",Sn="Byte Sequence";var Tn="Integer";function _n(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw vn(e,Tn);return e.toString()}function Ln(e,t){if(e<0)return-Ln(-e,t);var i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){var r=Math.floor(e*i);return(r%2==0?r:r+1)/i}return Math.round(e*i)/i}var bn="Decimal";function An(e){var t=Ln(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw vn(e,bn);var i=t.toString();return i.includes(".")?i:i+".0"}var In="String",Rn=/[\x00-\x1f\x7f]+/,Pn="Token";function kn(e){var t,i=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw vn(i,Pn);return i}function Dn(e){switch(typeof e){case"number":if(!T(e))throw vn(e,yn);return Number.isInteger(e)?_n(e):An(e);case"string":return function(e){if(Rn.test(e))throw vn(e,In);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(e);case"symbol":return kn(e);case"boolean":return function(e){if("boolean"!=typeof e)throw vn(e,En);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@"+_n(e.getTime()/1e3)}(e);if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw vn(e,Sn);return":"+(t=e,btoa(String.fromCharCode.apply(String,t))+":");var t}(e);if(e instanceof mn)return kn(e);default:throw vn(e,yn)}}var wn="Key";function Cn(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw vn(e,wn);return e}function Mn(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],i=e[1];return!0===i?";"+Cn(t):";"+Cn(t)+"="+Dn(i)})).join("")}function On(e){return e instanceof gn?""+Dn(e.value)+Mn(e.params):Dn(e)}function xn(e,t){return function(e,t){if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e||null==e)throw vn(e,pn);var i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map((function(e){var t=e[0],i=e[1];i instanceof gn==0&&(i=new gn(i));var r,s=Cn(t);return!0===i.value?s+=Mn(i.params):(s+="=",Array.isArray(i.value)?s+="("+(r=i).value.map(On).join(" ")+")"+Mn(r.params):s+=On(i)),s})).join(","+r)}(e,t)}var Fn="CMCD-Object",Nn="CMCD-Request",Bn="CMCD-Session",Un="CMCD-Status",Gn={br:Fn,ab:Fn,d:Fn,ot:Fn,tb:Fn,tpb:Fn,lb:Fn,tab:Fn,lab:Fn,url:Fn,pb:Nn,bl:Nn,tbl:Nn,dl:Nn,ltc:Nn,mtp:Nn,nor:Nn,nrr:Nn,rc:Nn,sn:Nn,sta:Nn,su:Nn,ttfb:Nn,ttfbb:Nn,ttlb:Nn,cmsdd:Nn,cmsds:Nn,smrt:Nn,df:Nn,cs:Nn,ts:Nn,cid:Bn,pr:Bn,sf:Bn,sid:Bn,st:Bn,v:Bn,msd:Bn,bs:Un,bsd:Un,cdn:Un,rtp:Un,bg:Un,pt:Un,ec:Un,e:Un},Hn={REQUEST:Nn};var Kn="event",Vn=function(e){return Math.round(e)},$n=function(e,t){return Array.isArray(e)?e.map((function(e){return $n(e,t)})):e instanceof gn&&"string"==typeof e.value?new gn($n(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;for(var s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e)},Wn=function(e){return 100*Vn(e/100)},qn={br:Vn,d:Vn,bl:Wn,dl:Wn,mtp:Wn,nor:function(e,t){var i=e;return t.version>=2&&(e instanceof gn&&"string"==typeof e.value?i=new gn([e]):"string"==typeof e&&(i=[e])),$n(i,t)},rtp:Wn,tb:Vn},jn="request",Yn="response",zn=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Xn=["e"],Qn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Jn(e){return Qn.test(e)}var Zn,ea=["d","dl","nor","ot","rtp","su"],ta=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],ia=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ra(e){return ia.includes(e)||Jn(e)}var sa=((Zn={})[Yn]=function(e){return zn.includes(e)||ea.includes(e)||ta.includes(e)||Jn(e)},Zn[Kn]=function(e){return zn.includes(e)||Xn.includes(e)||Jn(e)},Zn[jn]=function(e){return zn.includes(e)||ea.includes(e)||Jn(e)},Zn);function na(e,t){void 0===t&&(t={});var i={};if(null==e||"object"!=typeof e)return i;var r=t.version||e.v||1,s=t.reportingMode||jn,a=1===r?ra:sa[s],o=Object.keys(e).filter(a),l=t.filter;"function"==typeof l&&(o=o.filter(l));var h=s===Yn||s===Kn;h&&!o.includes("ts")&&o.push("ts"),r>1&&!o.includes("v")&&o.push("v");var u=n({},qn,t.formatters),d={version:r,reportingMode:s,baseUrl:t.baseUrl};return o.sort().forEach((function(t){var s=e[t],n=u[t];if("function"==typeof n&&(s=n(s,d)),"v"===t){if(1===r)return;s=r}"pr"==t&&1===s||(h&&"ts"===t&&!T(s)&&(s=Date.now()),function(e){return"number"==typeof e?T(e):null!=e&&""!==e&&!1!==e}(s)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof s&&(s=new mn(s)),i[t]=s))})),i}function aa(e,t,i){return n(e,function(e,t){void 0===t&&(t={});var i={};if(!e)return i;var r=function(e,t){var i={};if(!e)return i;var r,s=Object.keys(e),n=t?(r=t,Object.keys(r).reduce((function(e,t){var i;return null===(i=r[t])||void 0===i||i.forEach((function(i){return e[i]=t})),e}),{})):{};return s.reduce((function(t,i){var r,s=Gn[i]||n[i]||Hn.REQUEST;return(null!==(r=t[s])&&void 0!==r?r:t[s]={})[i]=e[i],t}),i)}(na(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(r).reduce((function(e,t){var i=t[0],r=xn(t[1],{whitespace:!1});return r&&(e[i]=r),e}),i)}(t,i))}var oa=/CMCD=[^&#]+/;function la(e,t,i){var r=function(e,t){if(void 0===t&&(t={}),!e)return"";var i=function(e,t){if(void 0===t&&(t={}),!e)return"";var i=function(e,t){return void 0===t&&(t={}),e?xn(na(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(i)}(e,t);return"CMCD="+i}(t,i);if(!r)return e;if(oa.test(e))return e.replace(oa,r);var s=e.includes("?")?"&":"?";return""+e+s+r}var ha=function(){function e(e){var t=this;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=function(){t.initialized&&(t.starved=!0),t.buffering=!0},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1},this.applyPlaylistData=function(e){try{t.apply(e,{ot:on,su:!t.initialized})}catch(e){t.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var i=e.frag,r=e.part,s=t.hls.levels[i.level],n=t.getObjectType(i),a={d:1e3*(r||i).duration,ot:n};n!==hn&&n!==ln&&n!=un||(a.br=s.bitrate/1e3,a.tb=t.getTopBandwidth(n)/1e3,a.bl=t.getBufferLength(n));var o=r?t.getNextPart(r):t.getNextFrag(i);null!=o&&o.url&&o.url!==i.url&&(a.nor=o.url),t.apply(e,a)}catch(e){t.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;var i=this.config=e.config,r=i.cmcd;null!=r&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHED,this.onMediaDetached,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHED,this.onMediaDetached,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},t.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},t.onBufferCreated=function(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer},t.createData=function(){var e;return{v:1,sf:fn,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},t.apply=function(e,t){void 0===t&&(t={}),n(t,this.createData());var i=t.ot===dn||t.ot===hn||t.ot===un;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var r=this.includeKeys;r&&(t=Object.keys(t).reduce((function(e,i){return r.includes(i)&&(e[i]=t[i]),e}),{}));var s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),aa(e.headers,t,s)):e.url=la(e.url,t,s)},t.getNextFrag=function(e){var t,i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){var r=e.sn-i.startSN;return i.fragments[r+1]}},t.getNextPart=function(e){var t,i=e.index,r=e.fragment,s=null==(t=this.hls.levels[r.level])||null==(t=t.details)?void 0:t.partList;if(s)for(var n=r.sn,a=s.length-1;a>=0;a--){var o=s[a];if(o.index===i&&o.fragment.sn===n)return s[a+1]}},t.getObjectType=function(e){var t=e.type;return"subtitle"===t?cn:"initSegment"===e.sn?dn:"audio"===t?ln:"main"===t?this.hls.audioTracks.length?hn:un:void 0},t.getTopBandwidth=function(e){var t,i=0,r=this.hls;if(e===ln)t=r.audioTracks;else{var s=r.maxAutoLevel,n=s>-1?s+1:r.levels.length;t=r.levels.slice(0,n)}return t.forEach((function(e){e.bitrate>i&&(i=e.bitrate)})),i>0?i:NaN},t.getBufferLength=function(e){var t=this.media,i=e===ln?this.audioBuffer:this.videoBuffer;return i&&t?1e3*jt.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var s=e.prototype;return s.destroy=function(){this.loader.destroy()},s.abort=function(){this.loader.abort()},s.load=function(e,i,r){t(e),this.loader.load(e,i,r)},r(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var s=e.prototype;return s.destroy=function(){this.loader.destroy()},s.abort=function(){this.loader.abort()},s.load=function(e,i,r){t(e),this.loader.load(e,i,r)},r(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},e}(),ua=function(e){function t(t){var i;return(i=e.call(this,"content-steering",t.logger)||this).hls=void 0,i.loader=null,i.uri=null,i.pathwayId=".",i._pathwayPriority=null,i.timeToLoad=300,i.reloadTimer=-1,i.updated=0,i.started=!1,i.enabled=!0,i.levels=null,i.audioTracks=null,i.subtitleTracks=null,i.penalizedPathways={},i.hls=t,i.registerListeners(),i}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.ERROR,this.onError,this))},i.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},i.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},i.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},i.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},i.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},i.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},i.onManifestLoaded=function(e,t){var i=t.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())},i.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},i.onError=function(e,t){var i=t.errorAction;if(2===(null==i?void 0:i.action)&&1===i.flags){var r=this.levels,s=this._pathwayPriority,n=this.pathwayId;if(t.context){var a=t.context,o=a.groupId,l=a.pathwayId,h=a.type;o&&r?n=this.getPathwayForGroupId(o,h,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&r&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n),t.details!==A.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+n+" levels: "+(r?r.length:r)+" priorities: "+it(s)+" penalized: "+it(this.penalizedPathways)):i.resolved=!0}},i.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var 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},i.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},i.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((function(e){r-i[e]>3e5&&delete i[e]}));for(var s=0;s<e.length;s++){var n=e[s];if(!(n in i)){if(n===this.pathwayId)return;var a=this.hls.nextLoadLevel,o=this.hls.levels[a];if((t=this.getLevelsForPathway(n)).length>0){this.log('Setting Pathway to "'+n+'"'),this.pathwayId=n,Ji(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[a];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=a);break}}}},i.getPathwayForGroupId=function(e,t,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),s=0;s<r.length;s++)if(t===k&&r[s].hasAudioGroup(e)||t===D&&r[s].hasSubtitleGroup(e))return r[s].pathwayId;return i},i.clonePathways=function(e){var t=this,i=this.levels;if(i){var r={},s={};e.forEach((function(e){var n=e.ID,a=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!i.some((function(e){return e.pathwayId===n}))){var l=t.getLevelsForPathway(a).map((function(e){var t=new ti(e.attrs);t["PATHWAY-ID"]=n;var i=t.AUDIO&&t.AUDIO+"_clone_"+n,a=t.SUBTITLES&&t.SUBTITLES+"_clone_"+n;i&&(r[t.AUDIO]=i,t.AUDIO=i),a&&(s[t.SUBTITLES]=a,t.SUBTITLES=a);var l=ca(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new et({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var u=1;u<e.audioGroups.length;u++)h.addGroupId("audio",e.audioGroups[u]+"_clone_"+n);if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)h.addGroupId("text",e.subtitleGroups[d]+"_clone_"+n);return h}));i.push.apply(i,l),da(t.audioTracks,r,o,n),da(t.subtitleTracks,s,o,n)}}))}},i.loadSteeringManifest=function(e){var t,i=this,r=this.hls.config,s=r.loader;this.loader&&this.loader.destroy(),this.loader=new s(r);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+e)}if("data:"!==t.protocol){var n=0|(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+n)}var a={responseType:"json",url:t.href},o=r.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},u={onSuccess:function(e,r,s,n){i.log('Loaded steering manifest: "'+t+'"');var a=e.data;if(1===(null==a?void 0:a.VERSION)){i.updated=performance.now(),i.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,t).href}catch(e){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}i.scheduleRefresh(i.uri||s.url),l&&i.clonePathways(l);var u={steeringManifest:a,url:t.toString()};i.hls.trigger(I.STEERING_MANIFEST_LOADED,u),h&&i.updatePathwayPriority(h)}else i.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(e,t,r,s){if(i.log("Error loading steering manifest: "+e.code+" "+e.text+" ("+t.url+")"),i.stopLoad(),410===e.code)return i.enabled=!1,void i.log("Steering manifest "+t.url+" no longer available");var n=1e3*i.timeToLoad;if(429!==e.code)i.scheduleRefresh(i.uri||t.url,n);else{var a=i.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(n=1e3*parseFloat(o))}i.log("Steering manifest "+t.url+" rate limited")}},onTimeout:function(e,t,r){i.log("Timeout loading steering manifest ("+t.url+")"),i.scheduleRefresh(i.uri||t.url)}};this.log("Requesting steering manifest: "+t),this.loader.load(a,h,u)},i.scheduleRefresh=function(e,t){var i=this;void 0===t&&(t=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var t,r=null==(t=i.hls)?void 0:t.media;!r||r.ended?i.scheduleRefresh(e,1e3*i.timeToLoad):i.loadSteeringManifest(e)}),t)},r(t,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}}])}(F);function da(e,t,i,r){e&&Object.keys(t).forEach((function(s){var a=e.filter((function(e){return e.groupId===s})).map((function(e){var a=n({},e);return a.details=void 0,a.attrs=new ti(a.attrs),a.url=a.attrs.URI=ca(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=r,a}));e.push.apply(e,a)}))}function ca(e,t,i,r){var s,n=r.HOST,a=r.PARAMS,o=r[i];t&&(s=null==o?void 0:o[t])&&(e=s);var l=new self.URL(e);return n&&!s&&(l.host=n),a&&Object.keys(a).sort().forEach((function(e){e&&l.searchParams.set(e,a[e])})),l.href}var fa=function(e){function t(i){var r;return(r=e.call(this,"eme",i.logger)||this).hls=void 0,r.config=void 0,r.media=null,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.mediaKeys=null,r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.bannedKeyIds={},r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,s='"'+e.type+'" event: init data type: "'+t+'"';if(r.debug(s),null!==i){if(!r.keyFormatPromise){var n=Object.keys(r.keySystemAccessPromises);n.length||(n=Si(r.config));var a=n.map(Ei).filter((function(e){return!!e}));r.keyFormatPromise=r.getKeyFormatPromise(a)}r.keyFormatPromise.then((function(n){var a=yi(n);if("sinf"===t&&a===fi.FAIRPLAY){var o;try{var l=oe(new Uint8Array(i)),h=Se(hi(JSON.parse(l).sinf));if(!h)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(h.subarray(8,24))}catch(e){return void r.warn(s+" Failed to parse sinf: "+e)}for(var u,d=j(o),c=r,f=c.keyIdToKeySessionPromise,g=c.mediaKeySessions,p=f[d],v=function(){var e=g[m],s=e.decryptdata;if(!s.keyId)return 0;var n=j(s.keyId);return ni(o,s.keyId)||-1!==s.uri.replace(/-/g,"").indexOf(d)?(p=f[n])?(s.pssh||(delete f[n],s.pssh=new Uint8Array(i),s.keyId=o,(p=f[d]=p.then((function(){return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-key-match")}))).catch((function(e){return r.handleError(e)}))),1):0:void 0},m=0;m<g.length&&(0===(u=v())||1!==u);m++);p||r.handleError(new Error("Key ID "+d+" not encountered in playlist. Key-system sessions "+g.length+"."))}else r.log('Ignoring "'+e.type+'" event with init data type: "'+t+'" for selected key-system '+a)})).catch((function(e){return r.handleError(e)}))}},r.onWaitingForKey=function(e){r.log('"'+e.type+'" event')},r.hls=i,r.config=i.config,r.registerListeners(),r}o(t,e);var i=t.prototype;return i.destroy=function(){this.onDestroying(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null},i.registerListeners=function(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(I.DESTROYING,this.onDestroying,this)},i.unregisterListeners=function(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(I.DESTROYING,this.onDestroying,this)},i.getLicenseServerUrl=function(e){var t=this.config,i=t.drmSystems,r=t.widevineLicenseUrl,s=null==i?void 0:i[e];return s?s.licenseUrl:e===fi.WIDEVINE&&r?r:void 0},i.getLicenseServerUrlOrThrow=function(e){var t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error('no license server URL configured for key-system "'+e+'"');return t},i.getServerCertificateUrl=function(e){var t=this.config.drmSystems,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+e+'"]')},i.attemptKeySystemAccess=function(e){var t=this,i=this.hls.levels,r=function(e,t,i){return!!e&&i.indexOf(e)===t},s=i.map((function(e){return e.audioCodec})).filter(r),n=i.map((function(e){return e.videoCodec})).filter(r);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((function(i,r){var a=function(e){var o=e.shift();t.getMediaKeysPromise(o,s,n).then((function(e){return i({keySystem:o,mediaKeys:e})})).catch((function(t){e.length?a(e):r(t instanceof va?t:new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};a(e)}))},i.requestMediaKeySystemAccess=function(e,t){var i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function "+i;return null===_i&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(r))}return i(e,t)},i.getMediaKeysPromise=function(e,t,i){var r,s=this,n=function(e,t,i,r){var s;switch(e){case fi.FAIRPLAY:s=["cenc","sinf"];break;case fi.WIDEVINE:case fi.PLAYREADY:s=["cenc"];break;case fi.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+e)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((function(e){return{contentType:"audio/mp4; codecs="+e,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}})),videoCapabilities:i.map((function(e){return{contentType:"video/mp4; codecs="+e,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}}))}]}(s,t,i,r)}(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=null==(r=a)?void 0:r.keySystemAccess;if(!o){this.log('Requesting encrypted media "'+e+'" key-system access with config: '+it(n)),o=this.requestMediaKeySystemAccess(e,n);var l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch((function(t){s.log('Failed to obtain access to key-system "'+e+'": '+t)})),o.then((function(t){s.log('Access for key-system "'+t.keySystem+'" obtained');var i=s.fetchServerCertificate(e);s.log('Create media-keys for "'+e+'"');var r=l.mediaKeys=t.createMediaKeys().then((function(t){return s.log('Media-keys created for "'+e+'"'),l.hasMediaKeys=!0,i.then((function(i){return i?s.setMediaKeysServerCertificate(t,e,i):t}))}));return r.catch((function(t){s.error('Failed to create media-keys for "'+e+'"}: '+t)})),r}))}return o.then((function(){return a.mediaKeys}))},i.createMediaKeySessionContext=function(e){var t=e.decryptdata,i=e.keySystem,r=e.mediaKeys;this.log('Creating key-system session "'+i+'" keyId: '+j(t.keyId||[])+" keyUri: "+t.uri);var s=r.createSession(),n={decryptdata:t,keySystem:i,mediaKeys:r,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n},i.renewKeySession=function(e){var t=e.decryptdata;if(t.pssh){var i=this.createMediaKeySessionContext(e),r=ga(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)},i.updateKeySession=function(e,t){var i=e.mediaKeysSession;return this.log('Updating key-session "'+i.sessionId+'" for keyId '+j(e.decryptdata.keyId||[])+"\n } (data length: "+t.byteLength+")"),i.update(t)},i.getSelectedKeySystemFormats=function(){var e=this;return Object.keys(this.keySystemAccessPromises).map((function(t){return{keySystem:t,hasMediaKeys:e.keySystemAccessPromises[t].hasMediaKeys}})).filter((function(e){return!!e.hasMediaKeys})).map((function(e){return Ei(e.keySystem)})).filter((function(e){return!!e}))},i.getKeySystemAccess=function(e){var t=this;return this.getKeySystemSelectionPromise(e).then((function(e){var i=e.keySystem,r=e.mediaKeys;return t.attemptSetMediaKeys(i,r)}))},i.selectKeySystem=function(e){var t=this;return new Promise((function(i,r){t.getKeySystemSelectionPromise(e).then((function(e){var t=e.keySystem,s=Ei(t);s?i(s):r(new Error('Unable to find format for key-system "'+t+'"'))})).catch(r)}))},i.selectKeySystemFormat=function(e){var 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},i.getKeyFormatPromise=function(e){var t=Si(this.config),i=e.map(yi).filter((function(e){return!!e&&-1!==t.indexOf(e)}));return this.selectKeySystem(i)},i.getKeyStatus=function(e){for(var t=this.mediaKeySessions,i=0;i<t.length;i++){var r=pa(e,t[i]);if(r)return r}},i.loadKey=function(e){var t=this,i=e.keyInfo.decryptdata,r=ga(i),s=this.bannedKeyIds[r];if(s||"internal-error"===this.getKeyStatus(i)){var n=ma(s||"internal-error",i);return this.handleError(n,e.frag),Promise.reject(n)}var a="(keyId: "+r+' format: "'+i.keyFormat+'" method: '+i.method+" uri: "+i.uri+")";this.log("Starting session for key "+a);var o=this.keyIdToKeySessionPromise[r];if(!o){var l=this.getKeySystemForKeyPromise(i).then((function(r){var s=r.keySystem,n=r.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: "+e.frag.sn+" "+e.frag.type+": "+e.frag.level+" using key "+a),t.attemptSetMediaKeys(s,n).then((function(){return t.throwIfDestroyed(),t.createMediaKeySessionContext({keySystem:s,mediaKeys:n,decryptdata:i})}))})).then((function(e){var r=i.pssh?i.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",r,"playlist-key")}));return l.catch((function(i){return t.handleError(i,e.frag)})),this.keyIdToKeySessionPromise[r]=l,l}return o.catch((function(r){if(r instanceof va){var s=u({},r.data);"internal-error"===t.getKeyStatus(i)&&(s.decryptdata=i);var n=new va(s,r.message);t.handleError(n,e.frag)}})),o},i.throwIfDestroyed=function(e){if(!this.hls)throw new Error("invalid state")},i.handleError=function(e,t){if(this.hls)if(e instanceof va){t&&(e.data.frag=t);var i=e.data.decryptdata;this.error(e.message+(i?" ("+j(i.keyId||[])+")":"")),this.hls.trigger(I.ERROR,e.data)}else this.error(e.message),this.hls.trigger(I.ERROR,{type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})},i.getKeySystemForKeyPromise=function(e){var t=ga(e),i=this.keyIdToKeySessionPromise[t];if(!i){var r=yi(e.keyFormat),s=r?[r]:Si(this.config);return this.attemptKeySystemAccess(s)}return i},i.getKeySystemSelectionPromise=function(e){if(e.length||(e=Si(this.config)),0===e.length)throw new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+it({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(e)},i.attemptSetMediaKeys=function(e,t){var i=this;if(this.mediaKeys===t)return Promise.resolve();var r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+e+'"');var s=Promise.all(r).then((function(){if(!i.media)throw i.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return i.media.setMediaKeys(t)}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then((function(){i.log('Media-keys set for "'+e+'"'),r.push(s),i.setMediaKeysQueue=i.setMediaKeysQueue.filter((function(e){return-1===r.indexOf(e)}))}))},i.generateRequestWithPreferredKeySession=function(e,t,i,r){var s,n=this,a=null==(s=this.config.drmSystems)||null==(s=s[e.keySystem])?void 0:s.generateRequest;if(a)try{var o=a.call(this.hls,t,i,e);if(!o)throw new Error("Invalid response from configured generateRequest filter");t=o.initDataType,i=o.initData?o.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log('Skipping key-session request for "'+r+'" (no initData)'),Promise.resolve(e);var l=ga(e.decryptdata),h=e.decryptdata.uri;this.log('Generating key-session request for "'+r+'" keyId: '+l+" URI: "+h+" (init data type: "+t+" length: "+i.byteLength+")");var u=new y,d=e._onmessage=function(t){var i=e.mediaKeysSession;if(i){var r=t.messageType,s=t.message;n.log('"'+r+'" message event for session "'+i.sessionId+'" message size: '+s.byteLength),"license-request"===r||"license-renewal"===r?n.renewLicense(e,s).catch((function(e){u.eventNames().length?u.emit("error",e):n.handleError(e)})):"license-release"===r?e.keySystem===fi.FAIRPLAY&&n.updateKeySession(e,ui("acknowledged")).then((function(){return n.removeSession(e)})).catch((function(e){return n.handleError(e)})):n.warn('unhandled media key message type "'+r+'"')}else u.emit("error",new Error("invalid state"))},c=function(e,t){var i;t.keyStatus=e,e.startsWith("usable")?u.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=ma(e,t.decryptdata):"expired"===e?i=new Error("key expired (keyId: "+l+")"):"released"===e?i=new Error("key released"):"status-pending"===e||n.warn('unhandled key status change "'+e+'" (keyId: '+l+")"),i&&(u.eventNames().length?u.emit("error",i):n.handleError(i))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){var i=n.getKeyStatuses(e);if(Object.keys(i).some((function(e){return"status-pending"!==i[e]}))){if("expired"===i[l])return n.log("Expired key "+it(i)+' in key-session "'+e.mediaKeysSession.sessionId+'"'),void n.renewKeySession(e);var r,s=i[l];s?c(s,e):(e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(r=e.keyStatusTimeouts)[l]||(r[l]=self.setTimeout((function(){if(e.mediaKeysSession&&n.mediaKeys){var t=n.getKeyStatus(e.decryptdata);if(t&&"status-pending"!==t)return n.log("No status for keyId "+l+' in key-session "'+e.mediaKeysSession.sessionId+'". Using session key-status '+t+" from other session."),c(t,e);n.log("key status for "+l+' in key-session "'+e.mediaKeysSession.sessionId+'" timed out after 0ms'),c(s="internal-error",e)}}),0)),n.log("No status for keyId "+l+" ("+it(i)+")."))}}else u.emit("error",new Error("invalid state"))};ar(e.mediaKeysSession,"message",d),ar(e.mediaKeysSession,"keystatuseschange",f);var g=new Promise((function(e,t){u.on("error",t),u.on("resolved",e)}));return e.mediaKeysSession.generateRequest(t,i).then((function(){n.log('Request generated for key-session "'+e.mediaKeysSession.sessionId+'" keyId: '+l+" URI: "+h)})).catch((function(t){throw new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},"Error generating key-session request: "+t)})).then((function(){return g})).catch((function(t){return u.removeAllListeners(),n.removeSession(e).then((function(){throw t}))})).then((function(){return u.removeAllListeners(),e}))},i.getKeyStatuses=function(e){var t=this,i={};return e.mediaKeysSession.keyStatuses.forEach((function(r,s){if("string"==typeof s&&"object"==typeof r){var n=s;s=r,r=n}var a="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);e.keySystem===fi.PLAYREADY&&16===a.length&&di(a);var o=j(a);"internal-error"===r&&(t.bannedKeyIds[o]=r),t.log('key status change "'+r+'" for keyStatuses keyId: '+o+' key-session "'+e.mediaKeysSession.sessionId+'"'),i[o]=r})),i},i.fetchServerCertificate=function(e){var t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log('Fetching server certificate for "'+e+'"'),new Promise((function(s,n){var a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(e,t,i,r){s(e.data)},onError:function(t,i,s,o){n(new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:u({url:a.url,data:void 0},t)},'"'+e+'" certificate request failed ('+r+"). Status: "+t.code+" ("+t.text+")"))},onTimeout:function(t,i,s){n(new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},'"'+e+'" certificate request timed out ('+r+")"))},onAbort:function(e,t,i){n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()},i.setMediaKeysServerCertificate=function(e,t,i){var r=this;return new Promise((function(s,n){e.setServerCertificate(i).then((function(n){r.log("setServerCertificate "+(n?"success":"not supported by CDM")+" ("+i.byteLength+') on "'+t+'"'),s(e)})).catch((function(e){n(new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))},i.renewLicense=function(e,t){var i=this;return this.requestLicense(e,new Uint8Array(t)).then((function(t){return i.updateKeySession(e,new Uint8Array(t)).catch((function(t){throw new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}))},i.unpackPlayReadyKeyMessage=function(e,t){var i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0)for(var n,a=0,o=s.length;a<o;a++){var l,h,u=null==(l=(n=s[a]).querySelector("name"))?void 0:l.textContent,d=null==(h=n.querySelector("value"))?void 0:h.textContent;u&&d&&e.setRequestHeader(u,d)}var c=r.querySelector("Challenge"),f=null==c?void 0:c.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return ui(atob(f))},i.setupLicenseXHR=function(e,t,i,r){var s=this,n=this.config.licenseXhrSetup;return n?Promise.resolve().then((function(){if(!i.decryptdata)throw new Error("Key removed");return n.call(s.hls,e,t,i,r)})).catch((function(a){if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(s.hls,e,t,i,r)})).then((function(i){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))},i.requestLicense=function(e,t){var i=this,r=this.config.keyLoadPolicy.default;return new Promise((function(s,n){var a=i.getLicenseServerUrlOrThrow(e.keySystem);i.log("Sending license request to URL: "+a);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var h=i.config.licenseResponseCallback;if(h)try{l=h.call(i.hls,o,a,e)}catch(e){i.error(e)}s(l)}else{var u=r.errorRetry,d=u?u.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,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{var c=d-i._requestLicenseFailureCount+1;i.warn("Retrying license request, "+c+" attempts left"),i.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,i.setupLicenseXHR(o,a,e,t).then((function(t){var r=t.xhr,s=t.licenseChallenge;e.keySystem==fi.PLAYREADY&&(s=i.unpackPlayReadyKeyMessage(r,s)),r.send(s)})).catch(n)}))},i.onDestroying=function(){this.unregisterListeners(),this._clear()},i.onMediaAttached=function(e,t){if(this.config.emeEnabled){var i=t.media;this.media=i,ar(i,"encrypted",this.onMediaEncrypted),ar(i,"waitingforkey",this.onWaitingForKey)}},i.onMediaDetached=function(){var e=this.media;e&&(or(e,"encrypted",this.onMediaEncrypted),or(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)},i._clear=function(){var e,i=this;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},this.mediaKeys||this.mediaKeySessions.length){var r=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,bi.clearKeyUriToKeyIdMap();var n=s.length;t.CDMCleanupPromise=Promise.all(s.map((function(e){return i.removeSession(e)})).concat((null==r||null==(e=r.setMediaKeys(null))?void 0:e.catch((function(e){i.log("Could not clear media keys: "+e),i.hls&&i.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+e)})})))||Promise.resolve())).catch((function(e){i.log("Could not close sessions and clear media keys: "+e),i.hls&&i.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+e)})})).then((function(){n&&i.log("finished closing key sessions and clearing media keys")}))}},i.onManifestLoading=function(){this.keyFormatPromise=null,this.bannedKeyIds={}},i.onManifestLoaded=function(e,t){var i=t.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+r.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(r)}},i.removeSession=function(e){var t=this,i=e.mediaKeysSession,r=e.licenseXhr,s=e.decryptdata;if(i){this.log('Remove licenses and keys and close session "'+i.sessionId+'" keyId: '+j((null==s?void 0:s.keyId)||[])),e._onmessage&&(i.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);var a=e.keyStatusTimeouts;a&&Object.keys(a).forEach((function(e){return self.clearTimeout(a[e])}));var o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some((function(e){return"persistent-license"===e}))))}(this.config.drmSystemOptions)?new Promise((function(e,t){self.setTimeout((function(){return t(new Error("MediaKeySession.remove() timeout"))}),8e3),i.remove().then(e).catch(t)})):Promise.resolve();return o.catch((function(e){t.log("Could not remove session: "+e),t.hls&&t.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+e)})})).then((function(){return i.close()})).catch((function(e){t.log("Could not close session: "+e),t.hls&&t.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+e)})}))}return Promise.resolve()},t}(F);function ga(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return j(e.keyId)}function pa(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}fa.CDMCleanupPromise=void 0;var va=function(e){function t(t,i){var r;return(r=e.call(this,i)||this).data=void 0,t.error||(t.error=new Error(i)),r.data=t,t.err=t.error,r}return o(t,e),t}(f(Error));function ma(e,t){var i="output-restricted"===e,r=i?A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:A.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new va({type:b.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},i?"HDCP level output restricted":'key status changed to "'+e+'"')}var ya=function(){function e(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()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListeners=function(){this.hls.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var i=this.hls.config;if(i.capLevelOnFPSDrop){var r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,i){var r=performance.now();if(t){if(this.lastTime){var s=r-this.lastTime,n=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*n/s,l=this.hls;if(l.trigger(I.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*a){var h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=h)&&(h-=1,l.trigger(I.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}();function Ea(e){for(var t=5381,i=e.length;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}var Sa=.025,Ta=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function _a(e,t,i){return e.identifier+"-"+(i+1)+"-"+Ea(t)}var La=function(){function e(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}var t=e.prototype;return t.setDateRange=function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)},t.reset=function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)},t.isAssetPastPlayoutLimit=function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var i=this.playoutLimit;return!(e<=0||isNaN(i))&&(0===i||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i)},t.findAssetIndex=function(e){return this.assetList.indexOf(e)},t.toString=function(){return'["'+(e=this).identifier+'" '+(e.cue.pre?"<pre>":e.cue.post?"<post>":"")+e.timelineStart.toFixed(2)+"-"+e.resumeTime.toFixed(2)+"]";var e},r(e,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return ba(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-ba(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=T(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return ba(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Sa))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Ta.Range:Ta.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}}])}();function ba(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Sa)?t.start:t.start+t.duration}function Aa(e,t,i){var r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function Ia(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function Ra(e){var t=e.timelineStart,i=e.duration||0;return'["'+e.identifier+'" '+t.toFixed(2)+"-"+(t+i).toFixed(2)+"]"}var Pa=function(){function e(e,t,i,r){var s=this;this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){s.reachedPlayout(s.currentTime)&&s.hls&&s.hls.trigger(I.PLAYOUT_LIMIT_REACHED,{})};var n=this.hls=new e(t);this.interstitial=i,this.assetItem=r;var a=function(){s.hasDetails=!0};n.once(I.LEVEL_LOADED,a),n.once(I.AUDIO_TRACK_LOADED,a),n.once(I.SUBTITLE_TRACK_LOADED,a),n.on(I.MEDIA_ATTACHING,(function(e,t){var i=t.media;s.removeMediaListeners(),s.mediaAttached=i,s.interstitial.playoutLimit&&(i.addEventListener("timeupdate",s.checkPlayout),s.appendInPlace&&n.on(I.BUFFER_APPENDED,(function(){var e=s.bufferedEnd;s.reachedPlayout(e)&&(s._bufferedEosTime=e,n.trigger(I.BUFFERED_TO_END,void 0))})))}))}var t=e.prototype;return t.loadSource=function(){var e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{var t=this.assetItem.uri;try{t=Aa(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}},t.bufferedInPlaceToEnd=function(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;var i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,s=jt.bufferInfo(e,r,0);return this.getAssetTime(s.end)>=i-.02},t.reachedPlayout=function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t},t.getAssetTime=function(e){var t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)},t.removeMediaListeners=function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))},t.bufferSnapShot=function(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},t.destroy=function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null},t.attachMedia=function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)},t.detachMedia=function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()},t.resumeBuffering=function(){var e;null==(e=this.hls)||e.resumeBuffering()},t.pauseBuffering=function(){var e;null==(e=this.hls)||e.pauseBuffering()},t.transferMedia=function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null},t.resetDetails=function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}},t.on=function(e,t,i){var r;null==(r=this.hls)||r.on(e,t)},t.once=function(e,t,i){var r;null==(r=this.hls)||r.once(e,t)},t.off=function(e,t,i){var r;null==(r=this.hls)||r.off(e,t)},t.toString=function(){var e;return"HlsAssetPlayer: "+Ra(this.assetItem)+" "+(null==(e=this.hls)?void 0:e.sessionId)+" "+(this.appendInPlace?"append-in-place":"")},r(e,[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=jt.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var i=t-this.startOffset;if(i>0&&i<e)return i}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}}])}(),ka=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials-sched",i)||this).onScheduleUpdate=void 0,r.eventMap={},r.events=null,r.items=null,r.durations={primary:0,playout:0,integrated:0},r.onScheduleUpdate=t,r}o(t,e);var i=t.prototype;return i.destroy=function(){this.reset(),this.onScheduleUpdate=null},i.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(e){return e.reset()})),this.events=this.items=null},i.resetErrorsInRange=function(e,t){return this.events?this.events.reduce((function(i,r){return e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i}),0):0},i.getEvent=function(e){return e&&this.eventMap[e]||null},i.hasEvent=function(e){return e in this.eventMap},i.findItemIndex=function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);var r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i},i.findItemIndexAtTime=function(e,t){var i=this.items;if(i)for(var r=0;r<i.length;r++){var s=i[r];if(t&&"primary"!==t&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return r}return-1},i.findJumpRestrictedIndex=function(e,t){var i=this.items;if(i)for(var r=e;r<=t&&i[r];r++){var s=i[r].event;if(null!=s&&s.restrictions.jump&&!s.appendInPlace)return r}return-1},i.findEventIndex=function(e){var t=this.items;if(t)for(var i=t.length;i--;){var r;if((null==(r=t[i].event)?void 0:r.identifier)===e)return i}return-1},i.findAssetIndex=function(e,t){var i=e.assetList,r=i.length;if(r>1)for(var s=0;s<r;s++){var n=i[s];if(!n.error){var a=n.timelineStart;if(t===a||t>a&&(t<a+(n.duration||0)||s===r-1))return s}}return 0},i.parseInterstitialDateRanges=function(e,t){var i=this,r=e.main.details,s=r.dateRanges,n=this.events,a=this.parseDateRanges(s,{url:r.url},t),o=Object.keys(s),l=n?n.filter((function(e){return!o.includes(e.identifier)})):[];a.length&&a.sort((function(e,t){var i=e.cue.pre,r=e.cue.post,s=t.cue.pre,n=t.cue.post;if(i&&!s)return-1;if(s&&!i)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(i||s||r||n)){var a=e.startTime,o=t.startTime;if(a!==o)return a-o}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=a,l.forEach((function(e){i.removeEvent(e)})),this.updateSchedule(e,l)},i.updateSchedule=function(e,t,i){void 0===t&&(t=[]),void 0===i&&(i=!1);var r=this.events||[];if(r.length||t.length||this.length<2){var s=this.items,n=this.parseSchedule(r,e);(i||t.length||(null==s?void 0:s.length)!==n.length||n.some((function(e,t){return Math.abs(e.playout.start-s[t].playout.start)>.005||Math.abs(e.playout.end-s[t].playout.end)>.005})))&&(this.items=n,this.onScheduleUpdate(t,s))}},i.parseDateRanges=function(e,t,i){for(var r=[],s=Object.keys(e),n=0;n<s.length;n++){var a=s[n],o=e[a];if(o.isInterstitial){var l=this.eventMap[a];l?l.setDateRange(o):(l=new La(o,t),this.eventMap[a]=l,!1===i&&(l.appendInPlace=i)),r.push(l)}}return r},i.parseSchedule=function(e,t){var i=[],r=t.main.details,s=r.live?1/0:r.edge,n=0;if((e=e.filter((function(e){return!(e.error||e.cue.once&&e.hasPlayed)}))).length){this.resolveOffsets(e,t);var a=0,o=0;if(e.forEach((function(t,r){var l=t.cue.pre,h=t.cue.post,u=e[r-1]||null,d=t.appendInPlace,c=h?s:t.startOffset,f=t.duration,g=t.timelineOccupancy===Ta.Range?f:0,p=t.resumptionOffset,v=(null==u?void 0:u.startTime)===c,m=c+t.cumulativeDuration,y=d?m+f:c+p;if(l||!h&&c<=0){var E=o;o+=g,t.timelineStart=m;var S=n;n+=f,i.push({event:t,start:m,end:y,playout:{start:S,end:n},integrated:{start:E,end:o}})}else{if(!(c<=s))return;if(!v){var T=c-a;if(T>.033){var _=a,L=o;o+=T;var b=n;n+=T;var A={previousEvent:e[r-1]||null,nextEvent:t,start:_,end:_+T,playout:{start:b,end:n},integrated:{start:L,end:o}};i.push(A)}else T>0&&u&&(u.cumulativeDuration+=T,i[i.length-1].end=c)}h&&(y=m),t.timelineStart=m;var I=o;o+=g;var R=n;n+=f,i.push({event:t,start:m,end:y,playout:{start:R,end:n},integrated:{start:I,end:o}})}var P=t.resumeTime;a=h||P>s?s:P})),a<s){var l,h=a,u=o,d=s-a;o+=d;var c=n;n+=d,i.push({previousEvent:(null==(l=i[i.length-1])?void 0:l.event)||null,nextEvent:null,start:a,end:h+d,playout:{start:c,end:n},integrated:{start:u,end:o}})}this.setDurations(s,n,o)}else i.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return i},i.setDurations=function(e,t,i){this.durations={primary:e,playout:t,integrated:i}},i.resolveOffsets=function(e,t){var i=this,r=t.main.details,s=r.live?1/0:r.edge,n=0,a=-1;e.forEach((function(o,l){var h=o.cue.pre,u=o.cue.post,d=h?0:u?s:o.startTime;i.updateAssetDurations(o),a===d?o.cumulativeDuration=n:(n=0,a=d),!u&&o.snapOptions.in&&(o.resumeAnchor=ft(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(i.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&i.warn("Could not change append strategy for abutting event "+o));var c=T(o.resumeOffset)?o.resumeOffset:o.duration;n+=c}))},i.primaryCanResumeInPlaceAt=function(e,t){var i=this,r=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(r-s)>Sa?(this.log('"'+e.identifier+'" resumption '+r+" not aligned with estimated timeline end "+s),!1):!Object.keys(t).some((function(s){var n=t[s].details,a=n.edge;if(r>=a)return i.log('"'+e.identifier+'" resumption '+r+" past "+s+" playlist end "+a),!1;var o=ft(null,n.fragments,r);if(!o)return i.log('"'+e.identifier+'" resumption '+r+" does not align with any fragments in "+s+" playlist ("+n.fragStart+"-"+n.fragmentEnd+")"),!0;var l="audio"===s?.175:0;return!(Math.abs(o.start-r)<Sa+l||Math.abs(o.end-r)<Sa+l||(i.log('"'+e.identifier+'" resumption '+r+" not aligned with "+s+" fragment bounds ("+o.start+"-"+o.end+" sn: "+o.sn+" cc: "+o.cc+")"),0))}))},i.updateAssetDurations=function(e){if(e.assetListLoaded){for(var t=e.timelineStart,i=0,r=!1,s=!1,n=0;n<e.assetList.length;n++){var a=e.assetList[n],o=t+i;a.startOffset=i,a.timelineStart=o,r||(r=null===a.duration),s||(s=!!a.error),i+=a.error?0:a.duration||0}e.duration=r&&!s?Math.max(i,e.duration):i}},i.removeEvent=function(e){e.reset(),delete this.eventMap[e.identifier]},r(t,[{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}}])}(F);function Da(e){return"["+(e.event?'"'+e.event.identifier+'"':"primary")+": "+e.start.toFixed(2)+"-"+e.end.toFixed(2)+"]"}var wa=function(){function e(e){this.hls=void 0,this.hls=e}var t=e.prototype;return t.destroy=function(){this.hls=null},t.loadAssetList=function(e,t){var i,r=this,s=e.assetListUrl;try{i=Aa(s,this.hls.sessionId,e.baseUrl)}catch(t){var n=this.assignAssetListError(e,A.ASSET_LIST_LOAD_ERROR,t,s);return void this.hls.trigger(I.ERROR,n)}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);var a=this.hls.config,o=new(0,a.loader)(a),l={responseType:"json",url:i.href},h=a.interstitialAssetListLoadPolicy.default,u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,i,s,n){var a=t.data,o=null==a?void 0:a.ASSETS;if(Array.isArray(o))e.assetListResponse=a,r.hls.trigger(I.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:n});else{var l=r.assignAssetListError(e,A.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,n);r.hls.trigger(I.ERROR,l)}},onError:function(t,i,s,n){var a=r.assignAssetListError(e,A.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status "+t.code+" "+t.text+" ("+i.url+")"),i.url,n,s);r.hls.trigger(I.ERROR,a)},onTimeout:function(t,i,s){var n=r.assignAssetListError(e,A.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST ("+i.url+")"),i.url,t,s);r.hls.trigger(I.ERROR,n)}};return o.load(l,u,d),this.hls.trigger(I.ASSET_LIST_LOADING,{event:e}),o},t.assignAssetListError=function(e,t,i,r,s,n){return e.error=i,{type:b.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:n,stats:s}},e}();function Ca(e){null==e||e.play().catch((function(){}))}function Ma(e,t){return"["+e+"] Advancing timeline position to "+t}var Oa=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials",t.logger)||this).HlsPlayerClass=void 0,r.hls=void 0,r.assetListLoader=void 0,r.mediaSelection=null,r.altSelection=null,r.media=null,r.detachedData=null,r.requiredTracks=null,r.manager=null,r.playerQueue=[],r.bufferedPos=-1,r.timelinePos=-1,r.schedule=void 0,r.playingItem=null,r.bufferingItem=null,r.waitingItem=null,r.endedItem=null,r.playingAsset=null,r.endedAsset=null,r.bufferingAsset=null,r.shouldPlay=!1,r.onPlay=function(){r.shouldPlay=!0},r.onPause=function(){r.shouldPlay=!1},r.onSeeking=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&r.schedule){var t=e-r.timelinePos;if(!(Math.abs(t)<1/7056e5)){var i=t<=-.01;r.timelinePos=e,r.bufferedPos=e;var s=r.playingItem;if(s)if(i&&r.schedule.resetErrorsInRange(e,e-t)&&r.updateSchedule(!0),r.checkBuffer(),i&&e<s.start||e>=s.end){var n,a=r.findItemIndex(s),o=r.schedule.findItemIndexAtTime(e);if(-1===o&&(o=a+(i?-1:1),r.log("seeked "+(i?"back ":"")+"to position not covered by schedule "+e+" (resolving from "+a+" to "+o+")")),!r.isInterstitial(s)&&null!=(n=r.media)&&n.paused&&(r.shouldPlay=!1),!i&&o>a){var l=r.schedule.findJumpRestrictedIndex(a+1,o);if(l>a)return void r.setSchedulePosition(l)}r.setSchedulePosition(o)}else{var h=r.playingAsset;if(h){var u,d=h.timelineStart,c=h.duration||0;(i&&e<d||e>=d+c)&&(null!=(u=s.event)&&u.appendInPlace&&(r.clearInterstitial(s.event,s),r.flushFrontBuffer(e)),r.setScheduleToAssetAtTime(e,h))}else if(r.playingLastItem&&r.isInterstitial(s)){var f=s.event.assetList[0];f&&(r.endedItem=r.playingItem,r.playingItem=null,r.setScheduleToAssetAtTime(e,f))}}else r.checkBuffer()}}},r.onTimeupdate=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&e>r.timelinePos){r.timelinePos=e,e>r.bufferedPos&&r.checkBuffer();var t=r.playingItem;if(t&&!r.playingLastItem){if(e>=t.end){r.timelinePos=t.end;var i=r.findItemIndex(t);r.setSchedulePosition(i+1)}var s=r.playingAsset;s&&e>=s.timelineStart+(s.duration||0)&&r.setScheduleToAssetAtTime(e,s)}}},r.onScheduleUpdate=function(e,t){var i=r.schedule;if(i){var s=r.playingItem,n=i.events||[],a=i.items||[],o=i.durations,l=e.map((function(e){return e.identifier})),h=!(!n.length&&!l.length);(h||t)&&r.log("INTERSTITIALS_UPDATED ("+n.length+"): "+n+"\nSchedule: "+a.map((function(e){return Da(e)}))+" pos: "+r.timelinePos),l.length&&r.log("Removed events "+l);var u=null,d=null;s&&(u=r.updateItem(s,r.timelinePos),r.itemsMatch(s,u)?r.playingItem=u:r.waitingItem=r.endedItem=null),r.waitingItem=r.updateItem(r.waitingItem),r.endedItem=r.updateItem(r.endedItem);var c=r.bufferingItem;if(c&&(d=r.updateItem(c,r.bufferedPos),r.itemsMatch(c,d)?r.bufferingItem=d:c.event&&(r.bufferingItem=r.playingItem,r.clearInterstitial(c.event,null))),e.forEach((function(e){e.assetList.forEach((function(e){r.clearAssetPlayer(e.identifier,null)}))})),r.playerQueue.forEach((function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>Sa&&r.warn(s+' ("'+e.assetId+'" '+e.timelineOffset+"->"+t+")")}}})),h||t){if(r.hls.trigger(I.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:a.slice(0),durations:o,removedIds:l}),r.isInterstitial(s)&&l.includes(s.event.identifier))return r.warn('Interstitial "'+s.event.identifier+'" removed while playing'),void r.primaryFallback(s.event);s&&r.trimInPlace(u,s),c&&d!==u&&r.trimInPlace(d,c),r.checkBuffer()}}},r.hls=t,r.HlsPlayerClass=i,r.assetListLoader=new wa(t),r.schedule=new ka(r.onScheduleUpdate,t.logger),r.registerListeners(),r}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e&&(e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(I.MEDIA_ENDED,this.onMediaEnded,this),e.on(I.ERROR,this.onError,this),e.on(I.DESTROYING,this.onDestroying,this))},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(I.MEDIA_ENDED,this.onMediaEnded,this),e.off(I.ERROR,this.onError,this),e.off(I.DESTROYING,this.onDestroying,this))},i.startLoad=function(){this.resumeBuffering()},i.stopLoad=function(){this.pauseBuffering()},i.resumeBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()},i.pauseBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},i.onDestroying=function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)},i.removeMediaListeners=function(e){or(e,"play",this.onPlay),or(e,"pause",this.onPause),or(e,"seeking",this.onSeeking),or(e,"timeupdate",this.onTimeupdate)},i.onMediaAttaching=function(e,t){var i=this.media=t.media;ar(i,"seeking",this.onSeeking),ar(i,"timeupdate",this.onTimeupdate),ar(i,"play",this.onPlay),ar(i,"pause",this.onPause)},i.onMediaAttached=function(e,t){var i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();var s=this.findItemIndex(i);this.setSchedulePosition(s)}},i.clearScheduleState=function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){var s=this.getBufferingPlayer();s&&(this.log("Removing schedule state for detachedData and "+s),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}},i.isInterstitial=function(e){return!(null==e||!e.event)},i.retreiveMediaSource=function(e,t){var i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)},i.transferMediaFromPlayer=function(e,t){var i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});var s=e.transferMedia();this.log("transfer MediaSource from "+e+" "+it(s)),this.detachedData=s}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))},i.transferMediaTo=function(e,t){var i,r,s=this;if(e.media!==t){var n,a=null,o=this.hls,l=e!==o,h=l&&e.interstitial.appendInPlace,u=null==(i=this.detachedData)?void 0:i.mediaSource;if(o.media)h&&(a=o.transferMedia(),this.detachedData=a),n="Primary";else if(u){var d=this.getBufferingPlayer();d?(a=d.transferMedia(),n=""+d):n="detached MediaSource"}else n="detached media";if(!a)if(u)a=this.detachedData,this.log("using detachedData: MediaSource "+it(a));else if(!this.detachedData||o.media===t){var c=this.playerQueue;c.length>1&&c.forEach((function(e){if(l&&e.interstitial.appendInPlace!==h){var t=e.interstitial;s.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&s.warn("Could not change append strategy for queued assets "+t)}})),this.hls.detachMedia(),this.detachedData={media:t}}var f=a&&"mediaSource"in a&&"closed"!==(null==(r=a.mediaSource)?void 0:r.readyState),g=f&&a?a:t;this.log((f?"transfering MediaSource":"attaching media")+" to "+(l?e:"Primary")+" from "+n+" (media.currentTime: "+t.currentTime+")");var p=this.schedule;if(g===a&&p){var v=l&&e.assetId===p.assetIdAtEnd;g.overrides={duration:p.duration,endOfStream:!l||v,cueRemoval:!l}}e.attachMedia(g)}},i.onInterstitialCueEnter=function(){this.onTimeupdate()},i.checkStart=function(){var e=this.schedule,t=null==e?void 0:e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){var s=this.hls.startPosition;if(this.log(Ma("checkStart",s)),this.timelinePos=s,t.length&&t[0].cue.pre){var n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(s>=0||!this.primaryLive){var a=this.timelinePos=s>0?s:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){var l=e.findItemIndex(r);this.setSchedulePosition(l)}}},i.advanceAssetBuffering=function(e,t){var i=e.event,r=i.findAssetIndex(t),s=Ia(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var n,a=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(e)+1];a&&this.bufferedToItem(a)}}else this.bufferedToEvent(e,s)},i.advanceAfterAssetEnded=function(e,t,i){var r=Ia(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){var s=this.schedule.items;if(s){var n=t+1;if(n>=s.length)return void this.setSchedulePosition(-1);var a=e.resumeTime;this.timelinePos<a&&(this.log(Ma("advanceAfterAssetEnded",a)),this.timelinePos=a,e.appendInPlace&&this.advanceInPlace(a),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){var o=e.assetList[r];o&&this.advanceInPlace(o.timelineStart)}this.setSchedulePosition(t,r)}},i.setScheduleToAssetAtTime=function(e,t){var i=this.schedule;if(i){var r=t.parentIdentifier,s=i.getEvent(r);if(s){var n=i.findEventIndex(r),a=i.findAssetIndex(s,e);this.advanceAfterAssetEnded(s,n,a-1)}}},i.setSchedulePosition=function(e,t){var i,r=null==(i=this.schedule)?void 0:i.items;if(r&&!this.playbackDisabled){var s=e>=0?r[e]:null;this.log("setSchedulePosition "+e+", "+t+" ("+(s?Da(s):s)+") pos: "+this.timelinePos);var n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){var o=n.event,l=this.playingAsset,h=null==l?void 0:l.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(n,s)||void 0!==t&&h!==o.assetList[t].identifier)){var d,c=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED "+(c+1)+"/"+o.assetList.length+" "+Ra(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(I.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:c,event:o,schedule:r.slice(0),scheduleIndex:e,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),c));this.retreiveMediaSource(h,s),!u.media||null!=(d=this.detachedData)&&d.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+Da(n)),o.hasPlayed=!0,this.hls.trigger(I.INTERSTITIAL_ENDED,{event:o,schedule:r.slice(0),scheduleIndex:e}),o.cue.once)){var f;this.updateSchedule();var g=null==(f=this.schedule)?void 0:f.items;if(s&&g){var p=this.findItemIndex(s);this.advanceSchedule(p,g,t,n,a)}return}}this.advanceSchedule(e,r,t,n,a)}},i.advanceSchedule=function(e,t,i,r,s){var n=this,a=this.schedule;if(a){var o=t[e]||null,l=this.primaryMedia,h=this.playerQueue;if(h.length&&h.forEach((function(t){var i=t.interstitial,r=a.findEventIndex(i.identifier);(r<e||r>e+1)&&n.clearInterstitial(i,o)})),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var u=o.event;if(void 0===i){var d=Ia(u,(i=a.findAssetIndex(u,this.timelinePos))-1);if(u.isAssetPastPlayoutLimit(d)||u.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(u,e,i);i=d}var c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(u,i);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED "+Da(o)+" "+(u.appendInPlace?"append in place":"")),this.hls.trigger(I.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+u);if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial "+u);this.waitingItem=this.endedItem=null,this.playingItem=o;var g=u.assetList[i];if(!g)return void this.advanceAfterAssetEnded(u,e,i||0);if(f||(f=this.getAssetPlayer(g.identifier)),null===f||f.destroyed){var p=u.assetList.length;this.warn("asset "+(i+1)+"/"+p+" player destroyed "+u),(f=this.createAssetPlayer(u,g,i)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(f,i,t,e,l),this.shouldPlay&&Ca(f.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&Ca(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}},i.resumePrimary=function(e,t,i){var r,s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming "+Da(e)),null==(r=this.detachedData)||!r.mediaSource){var n=this.timelinePos;(n<e.start||n>=e.end)&&(n=this.getPrimaryResumption(e,t),this.log(Ma("resumePrimary",n)),this.timelinePos=n),this.attachPrimary(n,e)}if(i){var a=null==(s=this.schedule)?void 0:s.items;a&&(this.log("INTERSTITIALS_PRIMARY_RESUMED "+Da(e)),this.hls.trigger(I.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}},i.getPrimaryResumption=function(e,t){var i=e.start;if(this.primaryLive){var r=this.primaryDetails;if(0===t)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i},i.isAssetBuffered=function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:jt.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)},i.attachPrimary=function(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var r=this.primaryMedia;if(r){var s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Ma("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}},i.startLoadingPrimaryAt=function(e,t){var i,r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()},i.onManifestLoading=function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(I.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(I.BUFFER_CODECS,this.onBufferCodecs,this)},i.onLevelUpdated=function(e,t){if(-1!==t.level&&this.schedule){var i=this.hls.levels[t.level];if(i.details){var r=u(u({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}}},i.onAudioTrackUpdated=function(e,t){var i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(r){var s=u(u({},r),{},{audio:i});this.mediaSelection=s}else this.altSelection=u(u({},this.altSelection),{},{audio:i})},i.onSubtitleTrackUpdated=function(e,t){var i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(r){var s=u(u({},r),{},{subtitles:i});this.mediaSelection=s}else this.altSelection=u(u({},this.altSelection),{},{subtitles:i})},i.onAudioTrackSwitching=function(e,t){var i=nt(t);this.playerQueue.forEach((function(e){var r=e.hls;return r&&(r.setAudioOption(t)||r.setAudioOption(i))}))},i.onSubtitleTrackSwitch=function(e,t){var i=nt(t);this.playerQueue.forEach((function(e){var r=e.hls;return r&&(r.setSubtitleOption(t)||-1!==t.id&&r.setSubtitleOption(i))}))},i.onBufferCodecs=function(e,t){var i=t.tracks;i&&(this.requiredTracks=i)},i.onBufferAppended=function(e,t){this.checkBuffer()},i.onBufferFlushed=function(e,t){var i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){var r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}},i.onBufferedToEnd=function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var i=0;i<t.length;i++){var r=t[i];if(r.cue.post){var s,n=this.schedule.findEventIndex(r.identifier),a=null==(s=this.schedule.items)?void 0:s[n];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}},i.onMediaEnded=function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1},i.updateItem=function(e,t){var i,r=null==(i=this.schedule)?void 0:i.items;return e&&r&&r[this.findItemIndex(e,t)]||null},i.trimInPlace=function(e,t){var i=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((function(t,r){e.event.isAssetPastPlayoutLimit(r)&&i.clearAssetPlayer(t.identifier,null)}));var r=e.end+.25,s=jt.bufferInfo(this.primaryMedia,r,0);(s.end>r||(s.nextStart||0)>r)&&(this.log("trim buffered interstitial "+Da(e)+" (was "+Da(t)+")"),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}},i.itemsMatch=function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))},i.eventItemsMatch=function(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))},i.findItemIndex=function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1},i.updateSchedule=function(e){var t;void 0===e&&(e=!1);var i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))},i.checkBuffer=function(e){var t,i=null==(t=this.schedule)?void 0:t.items;if(i){var r=jt.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}},i.updateBufferedPos=function(e,t,i){var r=this.schedule,s=this.bufferingItem;if(!(this.bufferedPos>e)&&r)if(1===t.length&&this.itemsMatch(t[0],s))this.bufferedPos=e;else{var n=this.playingItem,a=this.findItemIndex(n),o=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,h=this.findItemIndex(s),u=Math.min(h+1,t.length-1),d=t[u];if((-1===o&&s&&e>=s.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=u),this.isInterstitial(s)){var c=s.event;if(u-a>1&&!1===c.appendInPlace)return;if(0===c.assetList.length&&c.assetListLoader)return}if(this.bufferedPos=e,o>h&&o>a)this.bufferedToItem(d);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else i&&n&&!this.itemsMatch(n,s)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}},i.assetsBuffered=function(e,t){var i=this;return 0!==e.event.assetList.length&&!e.event.assetList.some((function(e){var r=i.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))}))},i.setBufferingItem=function(e){var t=this,i=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,i)&&r){var s=r.items,n=r.events;if(!s||!n)return i;var a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:i?i.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY "+Da(e)+(i?" ("+l.toFixed(2)+" remaining)":"")),!this.playbackDisabled)if(a){var h=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((function(e,i){var r=t.getAssetPlayer(e.identifier);r&&(i===h&&r.loadSource(),r.resumeBuffering())}))}else this.hls.resumeBuffering(),this.playerQueue.forEach((function(e){return e.pauseBuffering()}));this.hls.trigger(I.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return i},i.bufferedToItem=function(e,t){void 0===t&&(t=0);var i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;var r=this.detachedData;r&&r.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}},i.preloadPrimary=function(e){var t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)},i.bufferedToEvent=function(e,t){var i=e.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){var n=this.preloadAssets(i,t);if(null!=n&&n.interstitial.appendInPlace){var a=this.primaryMedia;a&&this.bufferAssetPlayer(n,a)}}},i.preloadAssets=function(e,t){var i=e.assetUrl,r=e.assetList.length,s=0===r&&!e.assetListLoader,n=e.cue.once;if(s){var a,o=e.timelineStart;if(e.appendInPlace){var l,h=this.playingItem;this.isInterstitial(h)||(null==h||null==(l=h.nextEvent)?void 0:l.identifier)!==e.identifier||this.flushFrontBuffer(o+.25)}var u=0;if(!this.playingItem&&this.primaryLive&&-1===(u=this.hls.startPosition)&&(u=this.hls.liveSyncPosition||0),u&&!e.cue.pre&&!e.cue.post){var d=u-o;d>0&&(a=Math.round(1e3*d)/1e3)}if(this.log("Load interstitial asset "+(t+1)+"/"+(i?1:r)+" "+e+(a?" live-start: "+u+" start-offset: "+a:"")),i)return this.createAsset(e,0,0,o,e.duration,i);var c=this.assetListLoader.loadAssetList(e,a);c&&(e.assetListLoader=c)}else if(!n&&r){for(var f=t;f<r;f++){var g=e.assetList[f],p=this.getAssetPlayerQueueIndex(g.identifier);-1!==p&&!this.playerQueue[p].destroyed||g.error||this.createAssetPlayer(e,g,f)}var v=e.assetList[t];if(v){var m=this.getAssetPlayer(v.identifier);return m&&m.loadSource(),m}}return null},i.flushFrontBuffer=function(e){var t=this,i=this.requiredTracks;i&&(this.log("Removing front buffer starting at "+e),Object.keys(i).forEach((function(i){t.hls.trigger(I.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})))},i.getAssetPlayerQueueIndex=function(e){for(var t=this.playerQueue,i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1},i.getAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null},i.getBufferingPlayer=function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null},i.createAsset=function(e,t,i,r,s,n){var a={parentIdentifier:e.identifier,identifier:_a(e,n,t),duration:s,startOffset:i,timelineStart:r,uri:n};return this.createAssetPlayer(e,a,t)},i.createAssetPlayer=function(e,t,i){var r=this,s=this.hls,a=s.userConfig,o=a.videoPreference,l=s.loadLevelObj||s.levels[s.currentLevel];(o||l)&&(o=n({},o),l.videoCodec&&(o.videoCodec=l.videoCodec),l.videoRange&&(o.allowedVideoRanges=[l.videoRange]));var h=s.audioTracks[s.audioTrack],d=s.subtitleTracks[s.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){var f=this.timelinePos-t.timelineStart;if(f>1){var g=t.duration;g&&f<g&&(c=f)}}var p=t.identifier,v=u(u({},a),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:p,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:h||a.audioPreference,subtitlePreference:d||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(v.timelineOffset=t.timelineStart));var m=v.cmcd;null!=m&&m.sessionId&&m.contentId&&(v.cmcd=n({},m,{contentId:Ea(t.uri)})),this.getAssetPlayer(p)&&this.warn("Duplicate date range identifier "+e+" and asset "+p);var y=new Pa(this.HlsPlayerClass,v,e,t);this.playerQueue.push(y),e.assetList[i]=t;var E=!0,S=function(s){if(s.live){var n,a=new Error("Interstitials MUST be VOD assets "+e),o={fatal:!0,type:b.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:a},l=(null==(n=r.schedule)?void 0:n.findEventIndex(e.identifier))||-1;r.handleAssetItemError(o,e,l,i,a.message)}else{var h=s.edge-s.fragmentStart,u=t.duration;(E||null===u||h>u)&&(E=!1,r.log('Interstitial asset "'+p+'" duration change '+u+" > "+h),t.duration=h,r.updateSchedule())}};y.on(I.LEVEL_UPDATED,(function(e,t){var i=t.details;return S(i)})),y.on(I.LEVEL_PTS_UPDATED,(function(e,t){var i=t.details;return S(i)})),y.on(I.EVENT_CUE_ENTER,(function(){return r.onInterstitialCueEnter()}));var T=function(e,t){var i=r.getAssetPlayer(p);if(i&&t.tracks){i.off(I.BUFFER_CODECS,T),i.tracks=t.tracks;var s=r.primaryMedia;r.bufferingAsset===i.assetItem&&s&&!i.media&&r.bufferAssetPlayer(i,s)}};y.on(I.BUFFER_CODECS,T),y.on(I.BUFFERED_TO_END,(function(){var i,s=r.getAssetPlayer(p);if(r.log("buffered to end of asset "+s),s&&r.schedule){var n=r.schedule.findEventIndex(e.identifier),a=null==(i=r.schedule.items)?void 0:i[n];r.isInterstitial(a)&&r.advanceAssetBuffering(a,t)}}));var _=function(t){return function(){if(r.getAssetPlayer(p)&&r.schedule){r.shouldPlay=!0;var i=r.schedule.findEventIndex(e.identifier);r.advanceAfterAssetEnded(e,i,t)}}};return y.once(I.MEDIA_ENDED,_(i)),y.once(I.PLAYOUT_LIMIT_REACHED,_(1/0)),y.on(I.ERROR,(function(t,s){if(r.schedule){var n=r.getAssetPlayer(p);if(s.details===A.BUFFER_STALLED_ERROR)return null!=n&&n.appendInPlace?void r.handleInPlaceStall(e):(r.onTimeupdate(),void r.checkBuffer(!0));r.handleAssetItemError(s,e,r.schedule.findEventIndex(e.identifier),i,"Asset player error "+s.error+" "+e)}})),y.on(I.DESTROYING,(function(){if(r.getAssetPlayer(p)&&r.schedule){var t=new Error("Asset player destroyed unexpectedly "+p),s={fatal:!0,type:b.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};r.handleAssetItemError(s,e,r.schedule.findEventIndex(e.identifier),i,t.message)}})),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED "+Ra(t)),this.hls.trigger(I.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:y}),y},i.clearInterstitial=function(e,t){var i=this;e.assetList.forEach((function(e){i.clearAssetPlayer(e.identifier,t)})),e.reset()},i.resetAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'+e+'" after error');var i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}},i.clearAssetPlayer=function(e,t){var i=this.getAssetPlayerQueueIndex(e);if(-1!==i){var r=this.playerQueue[i];this.log("clear "+r+" toSegment: "+(t?Da(t):t)),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}},i.emptyPlayerQueue=function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]},i.startAssetPlayer=function(e,t,i,r,s){var n=e.interstitial,a=e.assetItem,o=e.assetId,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log("INTERSTITIAL_ASSET_STARTED "+(t+1)+"/"+l+" "+Ra(a)),this.hls.trigger(I.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,s)},i.bufferAssetPlayer=function(e,t){var i,r;if(this.schedule){var s=e.interstitial,n=e.assetItem,a=this.schedule.findEventIndex(s.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(o){e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;var l=this.getBufferingPlayer();if(l!==e){var h=s.appendInPlace;if(!h||!1!==(null==l?void 0:l.interstitial.appendInPlace)){var u=(null==l?void 0:l.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering "+e);if(u&&!W(u,e.tracks)){var d=new Error("Asset "+Ra(n)+" SourceBuffer tracks ('"+Object.keys(e.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(u)+"')"),c={fatal:!0,type:b.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=s.findAssetIndex(n);return void this.handleAssetItemError(c,s,a,f,d.message)}}this.transferMediaTo(e,t)}}}}},i.handleInPlaceStall=function(e){var t=this.schedule,i=this.primaryMedia;if(t&&i){var r=i.currentTime,s=t.findAssetIndex(e,r),n=e.assetList[s];if(n){var a=this.getAssetPlayer(n.identifier);if(a){var o=a.currentTime||r-n.timelineStart,l=a.duration-o;if(this.warn("Stalled at "+o+" of "+(o+l)+" in "+a+" "+e+" (media.currentTime: "+r+")"),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){var h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,s)}}}}},i.advanceInPlace=function(e){var t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)},i.handleAssetItemError=function(e,t,i,r,s){if(e.details!==A.BUFFER_STALLED_ERROR){var a=t.assetList[r]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR "+(a?Ra(a):a)+" "+e.error),this.schedule){var o=(null==a?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),h=this.playerQueue[l]||null,u=this.schedule.items,d=n({},e,{fatal:!1,errorAction:It(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:i,player:h});if(this.hls.trigger(I.INTERSTITIAL_ASSET_ERROR,d),e.fatal){var c=this.playingAsset,f=this.bufferingAsset,g=new Error(s);if(a&&(this.clearAssetPlayer(o,null),a.error=g),t.assetList.some((function(e){return!e.error})))for(var p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);else t.error=g;this.updateSchedule(!0),t.error?this.primaryFallback(t):c&&c.identifier===o?this.advanceAfterAssetEnded(t,i,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}}}},i.primaryFallback=function(e){var t=e.timelineStart,i=this.effectivePlayingItem;if(i){this.log('Fallback to primary from event "'+e.identifier+'" start: '+t+" pos: "+this.timelinePos+" playing: "+Da(i)+" error: "+e.error);var r=this.timelinePos;-1===r&&(r=this.hls.startPosition);var s=this.updateItem(i,r);if(this.itemsMatch(i,s)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;var n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}else this.checkStart()},i.onAssetListLoaded=function(e,t){var i,r,s=this,n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(null!=(i=this.schedule)&&i.hasEvent(a)){var l=n.timelineStart,h=n.duration,u=0;o.forEach((function(e,t){var i=parseFloat(e.DURATION);s.createAsset(n,t,u,l+u,i,e.URI),u+=i})),n.duration=u,this.log("Loaded asset-list with duration: "+u+" (was: "+h+") "+n);var d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===a;this.updateSchedule();var f=null==(r=this.bufferingItem)?void 0:r.event;if(c){var g,p=this.schedule.findEventIndex(a),v=null==(g=this.schedule.items)?void 0:g[p];if(v){if(!this.playingItem&&this.timelinePos>v.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p)return n.error=new Error("Interstitial no longer within playback range "+this.timelinePos+" "+n),this.updateSchedule(!0),void this.primaryFallback(n);this.setBufferingItem(v)}this.setSchedulePosition(p)}else if((null==f?void 0:f.identifier)===a){var m=n.assetList[0];if(m){var y=this.getAssetPlayer(m.identifier);if(f.appendInPlace){var E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}},i.onError=function(e,t){if(this.schedule)switch(t.details){case A.ASSET_LIST_PARSING_ERROR:case A.ASSET_LIST_LOAD_ERROR:case A.ASSET_LIST_LOAD_TIMEOUT:var i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break;case A.BUFFER_STALLED_ERROR:var r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace)return void this.handleInPlaceStall(r.event);this.log("Primary player stall @"+this.timelinePos+" bufferedPos: "+this.bufferedPos),this.onTimeupdate(),this.checkBuffer(!0)}},r(t,[{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},i=function(t){return t?e.getAssetPlayer(t.identifier):t},r=function(t,r,n,a,o){if(t){var l=t[r].start,h=t.event;if(h){if("playout"===r||h.timelineOccupancy!==Ta.Point){var u=i(n);(null==u?void 0:u.interstitial)===h&&(l+=u.assetItem.startOffset+u[o])}}else l+=("bufferedPos"===a?s():e[a])-t.start;return l}return 0},s=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=function(t){var i,r;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(r=e.schedule)?void 0:r.durations[t])||0},a=function(t,s){var n,a,o=e.effectivePlayingItem;if((null==o||null==(n=o.event)||!n.restrictions.skip)&&e.schedule){e.log("seek to "+t+' "'+s+'"');var l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,s),u=null==(a=e.schedule.items)?void 0:a[h],d=e.getBufferingPlayer(),c=null==d?void 0:d.interstitial,f=null==c?void 0:c.appendInPlace,g=l&&e.itemsMatch(l,u);if(l&&(f||g)){var p=i(e.playingAsset),v=(null==p?void 0:p.media)||e.primaryMedia;if(v){var m="primary"===s?v.currentTime:r(l,s,e.playingAsset,"timelinePos","currentTime"),y=t-m,E=(f?m:v.currentTime)+y;if(E>=0&&(!p||f||E<=p.duration))return void(v.currentTime=E)}}if(u){var S=t;if("primary"!==s){var T=t-u[s].start;S=u.start+T}var _=!e.isInterstitial(u);if(e.isInterstitial(l)&&!l.event.appendInPlace||!_&&!u.event.appendInPlace){if(l){var L=e.findItemIndex(l);if(h>L){var b=e.schedule.findJumpRestrictedIndex(L+1,h);if(b>L)return void e.setSchedulePosition(b)}var A=0;if(_)e.timelinePos=S,e.checkBuffer();else for(var I=u.event.assetList,R=t-(u[s]||u).start,P=I.length;P--;){var k=I[P];if(k.duration&&R>=k.startOffset&&R<k.startOffset+k.duration){A=P;break}}e.setSchedulePosition(h,A)}}else{var D=e.media||(f?null==d?void 0:d.media:null);D&&(D.currentTime=S)}}}},o=function(){var i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;var r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){var i,s=t(),n=e.bufferingItem;return n&&n===s&&(r(n,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-n.playout.start||(null==(i=e.bufferingAsset)?void 0:i.startOffset))||0},get currentTime(){var t=o(),i=e.effectivePlayingItem;return i&&i===t?r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){var i=o(),r=e.effectivePlayingItem;r&&r===i&&a(t+r.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,i=null==(t=o())?void 0:t.event.assetList;return i?i.map((function(t){return e.getAssetPlayer(t.identifier)})):[]},get playingIndex(){var t,i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return s()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){var t;return function(t,i){var r;if(0!==t&&null!=(r=e.schedule)&&r.length){var s,n=e.schedule.findItemIndexAtTime(t),a=null==(s=e.schedule.items)?void 0:s[n];if(a)return t+(a[i].start-a.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){var r=e.findItemIndex(t);if(i.appendInPlace){var s=t.playout.start+t.event.duration;a(s+.001,"playout")}else e.advanceAfterAssetEnded(i,r,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var i=this.waitingItem||this.playingItem;if(!this.isInterstitial(i)||i.event.appendInPlace){var r=this.media;!r&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(r=this.primaryMedia);var s=null==(t=r)?void 0:t.currentTime;if(void 0!==s&&T(s))return s}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}}])}(F),xa=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"subtitle-stream-controller",M)||this).currentTrackId=-1,s.tracksBuffered=[],s.mainDetails=null,s.registerListeners(),s}o(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.mainDetails=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.startLoad=function(e,t){this.stopLoad(),this.state=lr.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.mainDetails=null},i.onMediaDetaching=function(t,i){this.tracksBuffered=[],e.prototype.onMediaDetaching.call(this,t,i)},i.onLevelLoaded=function(e,t){this.mainDetails=t.details},i.onSubtitleFragProcessed=function(e,t){var i=t.frag,r=t.success;if(this.fragContextChanged(i)||(ee(i)&&(this.fragPrevious=i),this.state=lr.IDLE),r){var s=this.tracksBuffered[this.currentTrackId];if(s){for(var n,a=i.start,o=0;o<s.length;o++)if(a>=s[o].start&&a<=s[o].end){n=s[o];break}var l=i.start+i.duration;n?n.end=l:(n={start:a,end:l},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}}},i.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var s=r-1;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach((function(e){for(var t=0;t<e.length;)if(e[t].end<=s)e.shift();else{if(!(e[t].start<s))break;e[t].start=s,t++}})),this.fragmentTracker.removeFragmentsInRange(i,s,M)}},i.onError=function(e,t){var i=t.frag;(null==i?void 0:i.type)===M&&(t.details===A.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==lr.STOPPED&&(this.state=lr.IDLE))},i.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks;this.levels&&Ys(this.levels,r)?this.levels=r.map((function(e){return new et(e)})):(this.tracksBuffered=[],this.levels=r.map((function(e){var t=new et(e);return i.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,M),this.fragPrevious=null,this.mediaBuffer=null)},i.onSubtitleTrackSwitch=function(e,t){var i;if(this.currentTrackId=t.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==lr.STOPPED&&this.setInterval(500)}else this.clearInterval()},i.onSubtitleTrackLoaded=function(e,t){var i,r=this.currentTrackId,s=this.levels,n=t.details,a=t.id;if(s){var o=s[a];if(!(a>=s.length)&&o){this.log("Subtitle track "+a+" loaded ["+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;var h=this.mainDetails;if(!h)return void(this.startFragRequested=!1);var u,d=h.fragments[0];o.details?0===(l=this.alignPlaylists(n,o.details,null==(u=this.levelLastLoaded)?void 0:u.details))&&d&&ji(n,l=d.start):n.hasProgramDateTime&&h.hasProgramDateTime?(nr(n,h),l=n.fragmentStart):d&&ji(n,l=d.start),h&&!this.startFragRequested&&this.setStartPosition(h,l)}o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(I.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===lr.IDLE&&(ft(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+a)},i._handleFragmentLoadComplete=function(e){var t=this,i=e.frag,r=e.payload,s=i.decryptdata,n=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&oi(s.method)){var a=performance.now();this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,li(s.method)).catch((function(e){throw n.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((function(e){var t=performance.now();n.trigger(I.FRAG_DECRYPTED,{frag:i,payload:e,stats:{tstart:a,tdecrypt:t}})})).catch((function(e){t.warn(e.name+": "+e.message),t.state=lr.IDLE}))}},i.doTick=function(){if(this.media){if(this.state===lr.IDLE){var e=this.currentTrackId,t=this.levels,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;var r=this.config,s=this.getLoadPosition(),n=jt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),a=n.end,o=n.len,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var h=l.fragments,u=h.length,d=l.edge,c=null,f=this.fragPrevious;if(a<d){var g=r.maxFragLookUpTolerance,p=a>d-g?0:g;!(c=ft(f,h,Math.max(h[0].start,a),p))&&f&&f.start<h[0].start&&(c=h[0])}else c=h[u-1];if(!(c=this.filterReplacedPrimary(c,i.details)))return;var v=h[c.sn-l.startSN-1];if(v&&v.cc===c.cc&&this.fragmentTracker.getState(v)===Rt&&(c=v),this.fragmentTracker.getState(c)===Rt){var m=this.mapToInitFragWhenRequired(c);m&&this.loadFragment(m,i,a)}}}else this.state=lr.IDLE},i.loadFragment=function(t,i,r){ee(t)?e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i)},r(t,[{key:"mediaBufferTimeRanges",get:function(){return new Fa(this.tracksBuffered[this.currentTrackId]||[])}}])}(hr),Fa=function(e){this.buffered=void 0;var t=function(t,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+i+") is greater than the maximum bound ("+r+")");return e[i][t]};this.buffered={get length(){return e.length},end:function(i){return t("end",i,e.length)},start:function(i){return t("start",i,e.length)}}};function Na(e,t){var i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function Ba(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(i){V.debug("[texttrack-utils]: "+i);try{var r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){V.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===i&&(e.mode=i)}function Ua(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===i&&(e.mode=i)}function Ga(e,t,i,r){var s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var n=function(e,t,i){var r=[],s=function(e,t){if(t<=e[0].startTime)return 0;var i=e.length-1;if(t>e[i].endTime)return-1;for(var r,s=0,n=i;s<=n;)if(t<e[r=Math.floor((n+s)/2)].startTime)n=r-1;else{if(!(t>e[r].startTime&&s<i))return r;s=r+1}return e[s].startTime-t<t-e[n].startTime?s:n}(e,t);if(s>-1)for(var n=s,a=e.length;n<a;n++){var o=e[n];if(o.startTime>=t&&o.endTime<=i)r.push(o);else if(o.startTime>i)return r}return r}(e.cues,t,i),a=0;a<n.length;a++)r&&!r(n[a])||e.removeCue(n[a]);"disabled"===s&&(e.mode=s)}function Ha(e){for(var t=[],i=0;i<e.length;i++){var r=e[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[i])}return t}var Ka=function(e){function t(t){var i;return(i=e.call(this,t,"subtitle-track-controller")||this).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var e=null,t=Ha(i.media.textTracks),r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}var s=i.findTrackForTextTrack(e);i.subtitleTrack!==s&&i.setSubtitleTrack(s)}},i.registerListeners(),i}o(t,e);var i=t.prototype;return i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,e.prototype.destroy.call(this)},i.registerListeners=function(){var e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(I.ERROR,this.onError,this)},i.onMediaAttached=function(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))},i.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},i.onMediaDetaching=function(e,t){var i=this.media;if(i){var r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r||Ha(i.textTracks).forEach((function(e){Ua(e)}))}},i.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},i.onSubtitleTrackLoaded=function(e,t){var i=t.id,r=t.groupId,s=t.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=t.details,this.log("Subtitle track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Subtitle track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(e,t){e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;var o=at(a,n);if(o>-1)s=n[o];else{var l=at(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var u={subtitleTracks:n};this.log("Updating subtitle tracks, "+n.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,u),-1!==h&&-1===this.trackId&&this.setSubtitleTrack(h)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=this.selectDefaultTrack,r=0;r<t.length;r++){var s=t[r];if((!i||s.default)&&(i||e)&&(!e||ot(s,e)))return r}if(e){for(var n=0;n<t.length;n++){var a=t[n];if(zs(e.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(var o=0;o<t.length;o++){var l=t[o];if(zs(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1},i.findTrackForTextTrack=function(e){if(e)for(var t=this.tracksInGroup,i=0;i<t.length;i++)if(Xs(t[i],e))return i;return-1},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==D||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setSubtitleOption=function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var i=this.currentTrack;if(i&&ot(e,i))return i;var r=at(e,this.tracksInGroup);if(r>-1){var s=this.tracksInGroup[r];return this.setSubtitleTrack(r),s}if(i)return null;var n=at(e,t);if(n>-1)return t[n]}}return null},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,s=t.groupId,n=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading subtitle "+r+' "'+t.name+'" lang:'+t.lang+" group:"+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+n),this.hls.trigger(I.SUBTITLE_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:i||null,track:t})},i.toggleTrackModes=function(){var e=this.media;if(e){var t,i=Ha(e.textTracks),r=this.currentTrack;if(r&&((t=i.filter((function(e){return Xs(r,e)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+r.name+'" and language "'+r.lang+'"')),[].slice.call(i).forEach((function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")})),t){var s=this.subtitleDisplay?"showing":"hidden";t.mode!==s&&(t.mode=s)}}},i.setSubtitleTrack=function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!T(e))this.warn("Invalid subtitle track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),r){var s=!!r.details&&!r.details.live;if(e!==this.trackId||r!==i||!s){this.log("Switching to subtitle-track "+e+(r?' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId:""));var n=r.id,a=r.groupId,o=void 0===a?"":a,l=r.name,h=r.type,u=r.url;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:l,type:h,url:u});var d=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(d)}}else this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e},r(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}}])}(js),Va={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},$a=function(e){return String.fromCharCode(Va[e]||e)},Wa=15,qa=100,ja={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ya={17:2,18:4,21:6,22:8,23:10,19:13,20:15},za={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Xa={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Qa=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Ja=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var i="function"==typeof t?t():t;V.log(this.time+" ["+e+"] "+i)}},e}(),Za=function(e){for(var t=[],i=0;i<e.length;i++)t.push(e[i].toString(16));return t},eo=function(){function e(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}var t=e.prototype;return t.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},t.setStyles=function(e){for(var t=["foreground","underline","italics","background","flash"],i=0;i<t.length;i++){var r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}},t.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},t.equals=function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash},t.copy=function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash},t.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},e}(),to=function(){function e(){this.uchar=" ",this.penState=new eo}var t=e.prototype;return t.reset=function(){this.uchar=" ",this.penState.reset()},t.setChar=function(e,t){this.uchar=e,this.penState.copy(t)},t.setPenState=function(e){this.penState.copy(e)},t.equals=function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)},t.copy=function(e){this.uchar=e.uchar,this.penState.copy(e.penState)},t.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},e}(),io=function(){function e(e){this.chars=[],this.pos=0,this.currPenState=new eo,this.cueStartTime=null,this.logger=void 0;for(var t=0;t<qa;t++)this.chars.push(new to);this.logger=e}var t=e.prototype;return t.equals=function(e){for(var t=0;t<qa;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0},t.copy=function(e){for(var t=0;t<qa;t++)this.chars[t].copy(e.chars[t])},t.isEmpty=function(){for(var e=!0,t=0;t<qa;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e},t.setCursor=function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>qa&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=qa)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)},t.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},t.insertChar=function(e){var t=this;e>=144&&this.backSpace();var i=$a(e);this.pos>=qa?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+i+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t<qa;t++)this.chars[t].reset()},t.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},t.clearToEndOfRow=function(){this.clearFromPos(this.pos)},t.getTextString=function(){for(var e=[],t=!0,i=0;i<qa;i++){var r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")},t.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),ro=function(){function e(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var t=0;t<Wa;t++)this.rows.push(new io(e));this.logger=e}var t=e.prototype;return t.reset=function(){for(var e=0;e<Wa;e++)this.rows[e].clear();this.currRow=14},t.equals=function(e){for(var t=!0,i=0;i<Wa;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t},t.copy=function(e){for(var t=0;t<Wa;t++)this.rows[t].copy(e.rows[t])},t.isEmpty=function(){for(var e=!0,t=0;t<Wa;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},t.backSpace=function(){this.rows[this.currRow].backSpace()},t.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},t.insertChar=function(e){this.rows[this.currRow].insertChar(e)},t.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},t.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},t.setCursor=function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)},t.setPAC=function(e){this.logger.log(2,(function(){return"pacData = "+it(e)}));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var i=0;i<Wa;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){var n=s.rows[r].cueStartTime,a=this.logger.time;if(null!==n&&null!==a&&n<a)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(s.rows[r+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var h=e.indent,u=Math.max(h-1,0);l.setCursor(e.indent),e.color=l.chars[u].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)},t.setBkgData=function(e){this.logger.log(2,(function(){return"bkgData = "+it(e)})),this.backSpace(),this.setPen(e),this.insertChar(32)},t.setRollUpRows=function(e){this.nrRollUpRows=e},t.rollUp=function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return e.getDisplayText()}));var t=this.currRow+1-this.nrRollUpRows,i=this.rows.splice(t,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")},t.getDisplayText=function(e){e=e||!1;for(var t=[],i="",r=-1,s=0;s<Wa;s++){var n=this.rows[s].getTextString();n&&(r=s+1,e?t.push("Row "+r+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i},t.getTextAndFormat=function(){return this.rows},e}(),so=function(){function e(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 ro(i),this.nonDisplayedMemory=new ro(i),this.lastOutputScreen=new ro(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(function(){return"MODE="+e})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},t.insertChars=function(e){for(var t=this,i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return r+": "+t.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())},t.ccRCL=function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},t.ccBS=function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},t.ccAOF=function(){},t.ccAON=function(){},t.ccDER=function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},t.ccRU=function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},t.ccFON=function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},t.ccRDC=function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},t.ccTR=function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")},t.ccRTD=function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")},t.ccEDM=function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},t.ccCR=function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},t.ccENM=function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},t.ccEOC=function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+e.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)},t.ccTO=function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},t.ccMIDROW=function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var i=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][i]}this.logger.log(2,"MIDROW: "+it(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?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.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),no=function(){function e(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var r=this.logger=new Ja;this.channels=[null,new so(e,t,r),new so(e+1,i,r)]}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var i=this;this.logger.time=e;for(var r=function(e){var r=127&t[e],s=127&t[e+1],n=!1,a=null;if(0===r&&0===s)return 0;i.logger.log(3,(function(){return"["+Za([t[e],t[e+1]])+"] -> ("+Za([r,s])+")"}));var o=i.cmdHistory;if(r>=16&&r<=31){if(function(e,t,i){return i.a===e&&i.b===t}(r,s,o))return ao(null,null,o),i.logger.log(3,(function(){return"Repeated command ("+Za([r,s])+") is dropped"})),0;ao(r,s,i.cmdHistory),(n=i.parseCmd(r,s))||(n=i.parseMidrow(r,s)),n||(n=i.parsePAC(r,s)),n||(n=i.parseBackgroundAttributes(r,s))}else ao(null,null,o);if(!n&&(a=i.parseChars(r,s))){var l=i.currentChannel;l&&l>0?i.channels[l].insertChars(a):i.logger.log(2,"No channel found yet. TEXT-MODE?")}n||a||i.logger.log(2,(function(){return"Couldn't parse cleaned data "+Za([r,s])+" orig: "+Za([t[e],t[e+1]])}))},s=0;s<t.length;s+=2)r(s)},t.parseCmd=function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0},t.parseMidrow=function(e,t){var i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+Za([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var r=e<=23?1:2;i=t>=64&&t<=95?1===r?ja[e]:za[e]:1===r?Ya[e]:Xa[e];var s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)},t.interpretPAC=function(e,t){var i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),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=4*Math.floor((i-16)/2),r},t.parseChars=function(e,t){var i,r,s=null,n=null;return e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19?(r=17===n?t+80:18===n?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+$a(r)+"' in channel "+i})),s=[r]):e>=32&&e<=127&&(s=0===t?[e]:[e,t]),s&&this.logger.log(3,(function(){return"Char codes = "+Za(s).join(",")})),s},t.parseBackgroundAttributes=function(e,t){var i;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;var r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=Qa[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));var s=e<=23?1:2;return this.channels[s].setBkgData(r),!0},t.reset=function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}ao(null,null,this.cmdHistory)},t.cueSplitAtTime=function(e){for(var t=0;t<this.channels.length;t++){var i=this.channels[t];i&&i.cueSplitAtTime(e)}},e}();function ao(e,t,i){i.a=e,i.b=t}var oo=function(){if(null!=ci&&ci.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function s(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)e[a]=n[a]}return e}function n(t,n,a){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var h="",u=!1,d=t,c=n,f=a,g=null,p="",v=!0,m="auto",y="start",E=50,S="middle",T=50,_="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return u},set:function(e){u=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return p},set:function(t){var r=function(t){return i(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");p=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return v},set:function(e){v=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return y},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return S},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return _},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");_=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),lo=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function ho(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}var i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}var uo=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,i){for(var r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}},t.integer=function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},t.percent=function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1},e}();function co(e,t,i,r){var s=r?e.split(r):[e];for(var n in s)if("string"==typeof s[n]){var a=s[n].split(i);2===a.length&&t(a[0],a[1])}}var fo=new oo(0,0,""),go="middle"===fo.align?"middle":"center";function po(e,t,i){var r=e;function s(){var t=ho(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=s(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=s(),n(),function(e,t){var r=new uo;co(e,(function(e,t){var s;switch(e){case"region":for(var n=i.length-1;n>=0;n--)if(i[n].id===t){r.set(e,i[n].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",go,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",go,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",go,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");var s=r.get("line","auto");"auto"===s&&-1===fo.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",go);var n=r.get("position","auto");"auto"===n&&50===fo.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function vo(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var mo=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new lo,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function i(){var e=t.buffer,i=0;for(e=vo(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;var r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var r="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var s=(r=i()).match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var n=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=i(),t.state){case"HEADER":/:/.test(r)?co(r,(function(e,t){}),/:/):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new oo(0,0,""),t.state="CUE",-1===r.indexOf("--\x3e")){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{po(r,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var a=-1!==r.indexOf("--\x3e");if(!r||a&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=r;continue;case"BADCUE":r||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},t.flush=function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this},e}(),yo=/\r\n|\n\r|\n|\r/g,Eo=function(e,t,i){return void 0===i&&(i=0),e.slice(i,i+t.length)===t};function So(e,t,i){return Ea(e.toString())+Ea(t.toString())+Ea(i)}var To="stpp.ttml.im1t",_o=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Lo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,bo={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ao(e,t,i,r){var s=ce(new Uint8Array(e),["mdat"]);if(0!==s.length){var a,o,l,h=s.map((function(e){return q(e)})),u=(a=t.baseTime,1,void 0===(o=t.timescale)&&(o=1),void 0===l&&(l=!1),ys(a,1,1/o,l));try{h.forEach((function(e){return i(function(e,t){var i=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((function(e,t){return e[t]=i.getAttribute("ttp:"+t)||r[t],e}),{}),a="preserve"!==i.getAttribute("xml:space"),o=Ro(Io(i,"styling","style")),l=Ro(Io(i,"layout","region")),h=Io(i,"body","[begin]");return[].map.call(h,(function(e){var i=Po(e,a);if(!i||!e.hasAttribute("begin"))return null;var r=wo(e.getAttribute("begin"),s),h=wo(e.getAttribute("dur"),s),u=wo(e.getAttribute("end"),s);if(null===r)throw Do(e);if(null===u){if(null===h)throw Do(e);u=r+h}var d=new oo(r-t,u-t,i);d.id=So(d.startTime,d.endTime,d.text);var c=function(e,t,i){var r="http://www.w3.org/ns/ttml#styling",s=null,n=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return n&&i.hasOwnProperty(n)&&(s=i[n]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((function(i,n){var a=ko(t,r,n)||ko(e,r,n)||ko(s,r,n);return a&&(i[n]=a),i}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),f=c.textAlign;if(f){var g=bo[f];g&&(d.lineAlign=g),d.align=f}return n(d,c),d})).filter((function(e){return null!==e}))}(e,u))}))}catch(e){r(e)}}else r(new Error("Could not parse IMSC1 mdat"))}function Io(e,t,i){var r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Ro(e){return e.reduce((function(e,t){var i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function Po(e,t){return[].slice.call(e.childNodes).reduce((function(e,i,r){var s;return"br"===i.nodeName&&r?e+"\n":null!=(s=i.childNodes)&&s.length?Po(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function ko(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Do(e){return new Error("Could not parse ttml timestamp "+e)}function wo(e,t){if(!e)return null;var i=ho(e);return null===i&&(_o.test(e)?i=function(e,t){var i=_o.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):Lo.test(e)&&(i=function(e,t){var i=Lo.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}var Co=function(){function e(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}var t=e.prototype;return t.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},t.newCue=function(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}(),Mo=function(){function e(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={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=function(){var e=this.hls;e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){var e=new Co(this,"textTrack1"),t=new Co(this,"textTrack2"),i=new Co(this,"textTrack3"),r=new Co(this,"textTrack4");this.cea608Parser1=new no(1,e,t),this.cea608Parser2=new no(3,i,r)},t.addCues=function(e,t,i,r,s){for(var n,a,o,l,h=!1,u=s.length;u--;){var d=s[u],c=(n=d[0],a=d[1],o=t,l=i,Math.min(a,l)-Math.max(n,o));if(c>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],i),h=!0,c/(i-t)>.5))return}if(h||s.push([t,i]),this.config.renderTextTracksNatively){var f=this.captionsTracks[e];this.Cues.newCue(f,t,i,r)}else{var g=this.Cues.newCue(null,t,i,r);this.hls.trigger(I.CUES_PARSED,{type:"captions",cues:g,track:e})}},t.onInitPtsFound=function(e,t){var i=this,r=t.frag,s=t.id,n=t.initPTS,a=t.timescale,o=t.trackId,l=this.unparsedVttFrags;s===w&&(this.initPTS[r.cc]={baseTime:n,timescale:a,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach((function(e){i.initPTS[e.frag.cc]?i.onFragLoaded(I.FRAG_LOADED,e):i.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))},t.getExistingTrack=function(e,t){var i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var s=i.textTracks[r];if(xo(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null},t.createCaptionsTrack=function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)},t.createNativeTrack=function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,i=this.captionsTracks,r=this.media,s=t[e],n=s.label,a=s.languageCode,o=this.getExistingTrack(n,a);if(o)i[e]=o,Ua(i[e]),Na(i[e],r);else{var l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}},t.createNonNativeTrack=function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}},t.createTextTrack=function(e,t,i){var r=this.media;if(r)return r.addTextTrack(e,t,i)},t.onMediaAttaching=function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()},t.onMediaDetaching=function(e,t){var i=!!t.transferMedia;if(this.media=null,!i){var r=this.captionsTracks;Object.keys(r).forEach((function(e){Ua(r[e]),delete r[e]})),this.nonNativeCaptionsTracks={}}},t.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},t._cleanTracks=function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var i=0;i<t.length;i++)Ua(t[i])}},t.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks||[],s=r.some((function(e){return e.textCodec===To}));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Ys(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var n=this.media,a=n?Ha(n.textTracks):null;if(this.tracks.forEach((function(e,t){var r;if(a){for(var s=null,n=0;n<a.length;n++)if(a[n]&&xo(a[n],e)){s=a[n],a[n]=null;break}s&&(r=s)}if(r)Ua(r);else{var o=Oo(e);(r=i.createTextTrack(o,e.name,e.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)})),null!=a&&a.length){var o=a.filter((function(e){return null!==e})).map((function(e){return e.label}));o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: "+o.join(", ")+". Replace media element for each source to clear TextTracks and captions menu.")}}else if(this.tracks.length){var l=this.tracks.map((function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}}));this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}},t.onManifestLoaded=function(e,t){var i=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var r="textTrack"+t[1],s=i.captionsProperties[r];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)}}))},t.closedCaptionsForLevel=function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]},t.onFragLoading=function(e,t){if(this.enabled&&t.frag.type===w){var i,r,s=this.cea608Parser1,n=this.cea608Parser2,a=this.lastSn,o=t.frag,l=o.cc,h=o.sn,u=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;s&&n&&(h!==a+1||h===a&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),n.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=u}},t.onFragLoaded=function(e,t){var i=t.frag,r=t.payload;if(i.type===M)if(r.byteLength){var s=i.decryptdata,n="stats"in t;if(null==s||!s.encrypted||n){var a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===To?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})},t._parseIMSC1=function(e,t){var i=this,r=this.hls;Ao(t,this.initPTS[e.cc],(function(t){i._appendCues(t,e.level),r.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(function(t){r.logger.log("Failed to parse IMSC1: "+t),r.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))},t._parseVTTs=function(e){var t,i=this,r=e.frag,s=e.payload,n=this.initPTS,a=this.unparsedVttFrags,o=n.length-1;if(n[r.cc]||-1!==o){var l=this.hls;!function(e,t,i,r,s,n,a){var o,l,h,u=new mo,d=q(new Uint8Array(e)).trim().replace(yo,"\n").split("\n"),c=[],f=t?(o=t.baseTime,void 0===(l=t.timescale)&&(l=1),ys(o,9e4,1/l)):0,g="00:00.000",p=0,v=0,m=!0;u.oncue=function(e){var n=i[r],a=i.ccOffset,o=(p-f)/9e4;if(null!=n&&n.new&&(void 0!==v?a=i.ccOffset=n.start:function(e,t,i){var r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=r.start-s.start,r.new=!1,s=e[(r=s).prevCC]}e.presentationOffset=i}(i,r,o)),o){if(!t)return void(h=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}var l=e.endTime-e.startTime,u=bs(9e4*(e.startTime+a-v),9e4*s)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);var d=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(d)),e.id||(e.id=So(e.startTime,e.endTime,d)),e.endTime>0&&c.push(e)},u.onparsingerror=function(e){h=e},u.onflush=function(){h?a(h):n(c)},d.forEach((function(e){if(m){if(Eo(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((function(e){Eo(e,"LOCAL:")?g=e.slice(6):Eo(e,"MPEGTS:")&&(p=parseInt(e.slice(7)))}));try{v=function(e){var t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(T(t)&&T(i)&&T(r)&&T(s)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*i,(t+=6e4*r)+36e5*s}(g)/1e3}catch(e){h=e}return}""===e&&(m=!1)}u.parse(e+"\n")})),u.flush()}(null!=(t=r.initSegment)&&t.data?Te(r.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(function(e){i._appendCues(e,r.level),l.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(function(t){var n="Missing initPTS for VTT MPEGTS"===t.message;n?a.push(e):i._fallbackToIMSC1(r,s),l.logger.log("Failed to parse VTT cue: "+t),n&&o>r.cc||l.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}else a.push(e)},t._fallbackToIMSC1=function(e,t){var i=this,r=this.tracks[e.level];r.textCodec||Ao(t,this.initPTS[e.cc],(function(){r.textCodec=To,i._parseIMSC1(e,t)}),(function(){r.textCodec="wvtt"}))},t._appendCues=function(e,t){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach((function(e){return Ba(r,e)}))}else{var s=this.tracks[t];if(!s)return;var n=s.default?"default":"subtitles"+t;i.trigger(I.CUES_PARSED,{type:"subtitles",cues:e,track:n})}},t.onFragDecrypted=function(e,t){t.frag.type===M&&this.onFragLoaded(I.FRAG_LOADED,t)},t.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},t.onFragParsingUserdata=function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var i=t.frag,r=t.samples;if(i.type!==w||"NONE"!==this.closedCaptionsForLevel(i))for(var s=0;s<r.length;s++){var n=r[s].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();var a=this.extractCea608Data(n);this.cea608Parser1.addData(r[s].pts,a[0]),this.cea608Parser2.addData(r[s].pts,a[1])}}}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,s=t.endOffsetSubtitles,n=t.type,a=this.media;if(a&&!(a.currentTime<r)){if(!n||"video"===n){var o=this.captionsTracks;Object.keys(o).forEach((function(e){return Ga(o[e],i,r)}))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==s){var l=this.textTracks;Object.keys(l).forEach((function(e){return Ga(l[e],i,s)}))}}},t.extractCea608Data=function(e){for(var t=[[],[]],i=31&e[0],r=2,s=0;s<i;s++){var n=e[r++],a=127&e[r++],o=127&e[r++];if((0!==a||0!==o)&&4&n){var l=3&n;0!==l&&1!==l||(t[l].push(a),t[l].push(o))}}return t},e}();function Oo(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function xo(e,t){return!!e&&e.kind===Oo(t)&&Xs(t,e)}var Fo=/\s/,No={newCue:function(e,t,i,r){for(var s,n,a,o,l,h=[],u=self.VTTCue||self.TextTrackCue,d=0;d<r.rows.length;d++)if(a=!0,o=0,l="",!(s=r.rows[d]).isEmpty()){for(var c,f=0;f<s.chars.length;f++)Fo.test(s.chars[f].uchar)&&a?o++:(l+=s.chars[f].uchar,a=!1);s.cueStartTime=t,t===i&&(i+=1e-4),o>=16?o--:o++;var g=vo(l.trim()),p=So(t,i,g);null!=e&&null!=(c=e.cues)&&c.getCueById(p)||((n=new u(t,i,g)).id=p,n.line=d+1,n.align="left",n.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(n))}return e&&h.length&&(h.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),h.forEach((function(t){return Ba(e,t)}))),h}},Bo=/(\d+)-(\d+)\/(\d+)/,Uo=function(){function e(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||Go,this.controller=new self.AbortController,this.stats=new z}var t=e.prototype;return t.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},t.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},t.load=function(e,t,i){var r=this,s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();var a=function(e,t){var i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(n({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(e,this.controller.signal),o="arraybuffer"===e.responseType,l=o?"byteLength":"length",h=t.loadPolicy,u=h.maxTimeToFirstByteMs,d=h.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&T(u)?u:d,this.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(s,e,r.response))}),t.timeout),(Os(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(i){var n;r.response=r.loader=i;var a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(r.requestTimeout),t.timeout=d,r.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(s,e,r.response))}),d-(a-s.loading.start)),!i.ok){var l=i.status,h=i.statusText;throw new Ho(h||"fetch, bad network response",l,i)}s.loading.first=a,s.total=function(e){var t=e.get("Content-Range");if(t){var i=function(e){var t=Bo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(T(i))return i}var r=e.get("Content-Length");if(r)return parseInt(r)}(i.headers)||s.total;var u=null==(n=r.callbacks)?void 0:n.onProgress;return u&&T(t.highWaterMark)?r.loadProgressively(i,s,e,t.highWaterMark,u):o?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((function(i){var n,a,o=r.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);var h=i[l];h&&(s.loaded=s.total=h);var u={url:o.url,data:i,code:o.status},d=null==(n=r.callbacks)?void 0:n.onProgress;d&&!T(t.highWaterMark)&&d(s,e,i,o),null==(a=r.callbacks)||a.onSuccess(u,s,e,o)})).catch((function(t){var i;if(self.clearTimeout(r.requestTimeout),!s.aborted){var n=t&&t.code||0,a=t?t.message:null;null==(i=r.callbacks)||i.onError({code:n,text:a},e,t?t.details:null,s)}}))},t.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},t.loadProgressively=function(e,t,i,r,s){void 0===r&&(r=0);var n=new dr,a=e.body.getReader(),o=function(){return a.read().then((function(a){if(a.done)return n.dataLength&&s(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return t.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(t,i,n.flush().buffer,e)):s(t,i,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},e}();function Go(e,t){return new self.Request(e.url,t)}var Ho=function(e){function t(t,i,r){var s;return(s=e.call(this,t)||this).code=void 0,s.details=void 0,s.code=i,s.details=r,s}return o(t,e),t}(f(Error)),Ko=/^age:\s*[\d.]+\s*$/im,Vo=function(){function e(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 z,this.retryDelay=0}var t=e.prototype;return t.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},t.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},t.load=function(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()},t.loadInternal=function(){var e=this,t=this.config,i=this.context;if(t&&i){var r=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;var n=this.xhrSetup;n?Promise.resolve().then((function(){if(e.loader===r&&!e.stats.aborted)return n(r,i.url)})).catch((function(t){if(e.loader===r&&!e.stats.aborted)return r.open("GET",i.url,!0),n(r,i.url)})).then((function(){e.loader!==r||e.stats.aborted||e.openAndSendXhr(r,i,t)})).catch((function(t){var n;null==(n=e.callbacks)||n.onError({code:r.status,text:t.message},i,r,s)})):this.openAndSendXhr(r,i,t)}},t.openAndSendXhr=function(e,t,i){e.readyState||e.open("GET",t.url,!0);var r=t.headers,s=i.loadPolicy,n=s.maxTimeToFirstByteMs,a=s.maxLoadTimeMs;if(r)for(var 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&&T(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()},t.readystatechange=function(){var e=this.context,t=this.loader,i=this.stats;if(e&&t){var r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var n=t.status,a="text"===t.responseType?t.responseText:null;if(n>=200&&n<300){var o=null!=a?a:t.response;if(null!=o){var l,h;i.loading.end=Math.max(self.performance.now(),i.loading.first);var u="arraybuffer"===t.responseType?o.byteLength:o.length;i.loaded=i.total=u,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(i,e,o,t);var c={url:t.responseURL,data:o,code:n};return void(null==(h=this.callbacks)||h.onSuccess(c,i,e,t))}}var f,g=s.loadPolicy.errorRetry;Lt(g,i.retry,!1,{url:e.url,data:void 0,code:n})?this.retry(g):(V.error(n+" while loading "+e.url),null==(f=this.callbacks)||f.onError({code:n,text:t.statusText},e,t,i))}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(Lt(e,this.stats.retry,!0))this.retry(e);else{var t;V.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,i=this.stats;this.retryDelay=Tt(e,i.retry),i.retry++,V.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?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)},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&Ko.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},e}(),$o=u(u({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:Vo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:dt,bufferController:rn,capLevelController:an,errorController:At,fpsController:ya,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:_i,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},{cueHandler:No,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:xa,subtitleTrackController:Ka,timelineController:Mo,audioStreamController:qs,audioTrackController:Qs,emeController:fa,cmcdController:ha,contentSteeringController:ua,interstitialsController:Oa});function Wo(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Wo):Object.keys(e).reduce((function(t,i){return t[i]=Wo(e[i]),t}),{}):e}var qo=function(e){function t(t,i){var r;return(r=e.call(this,"gap-controller",t.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.media=null,r.mediaSource=void 0,r.nudgeRetry=0,r.stallReported=!1,r.stalled=null,r.moved=!1,r.seeking=!1,r.buffered={},r.lastCurrentTime=0,r.ended=0,r.waiting=0,r.onMediaPlaying=function(){r.ended=0,r.waiting=0},r.onMediaWaiting=function(){var e;null!=(e=r.media)&&e.seeking||(r.waiting=self.performance.now(),r.tick())},r.onMediaEnded=function(){var e;r.hls&&(r.ended=(null==(e=r.media)?void 0:e.currentTime)||1,r.hls.trigger(I.MEDIA_ENDED,{stalled:!1}))},r.hls=t,r.fragmentTracker=i,r.registerListeners(),r}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e&&(e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this))},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this))},i.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},i.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var i=this.media=t.media;ar(i,"playing",this.onMediaPlaying),ar(i,"waiting",this.onMediaWaiting),ar(i,"ended",this.onMediaEnded)},i.onMediaDetaching=function(e,t){this.clearInterval();var i=this.media;i&&(or(i,"playing",this.onMediaPlaying),or(i,"waiting",this.onMediaWaiting),or(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},i.onBufferAppended=function(e,t){this.buffered=t.timeRanges},i.tick=function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}},i.poll=function(e,t){var i,r,s=null==(i=this.hls)?void 0:i.config;if(s){var n=this.media;if(n){var a=n.seeking,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(h)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!1})));if(jt.getBuffered(n).length){var u=jt.bufferInfo(n,e,0),d=u.nextStart||0,c=this.fragmentTracker;if(a&&c&&this.hls){var f=jo(this.hls.inFlightFragments,e),g=u.len>2,p=!d||f||d-e>2&&!c.getPartialFragment(e);if(g||p)return;this.moved=!1}var v=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(u.len>0||d))return;var m=Math.max(d,u.start||0)-e,y=null!=v&&v.live?2*v.targetduration:2,E=zo(e,c);if(m>0&&(m<=y||E))return void(n.paused||this._trySkipBufferHole(E))}var S=s.detectStallWithCurrentTimeMs,T=self.performance.now(),_=this.waiting,L=this.stalled;if(null===L){if(!(_>0&&T-_<S))return void(this.stalled=T);L=this.stalled=_}var b=T-L;if(!a&&(b>=S||_)&&this.hls){var A;if("ended"===(null==(A=this.mediaSource)?void 0:A.readyState)&&(null==v||!v.live)&&Math.abs(e-((null==v?void 0:v.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(I.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}var R=jt.bufferInfo(n,e,s.maxBufferHole);this._tryFixBufferStall(R,b,e)}else this.nudgeRetry=0}}}},i.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var i=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(i)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(I.STALL_RESOLVED,{})}},i.nudgeOnVideoHole=function(e,t){var i,r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){var s=jt.bufferedInfo(jt.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){var n=jt.timeRangesToArray(r),a=jt.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&a<n.length-1){var o=jt.bufferedInfo(n,e,0).bufferedIndex,l=n[a].end,h=n[a+1].start;if((-1===o||o>a)&&h-l<1&&e-l<2){var u=new Error("nudging playhead to flush pipeline after video hole. currentTime: "+e+" hole: "+l+" -> "+h+" buffered index: "+o);this.warn(u.message),this.media.currentTime+=1e-6;var d=zo(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var c=jt.bufferInfo(this.media,e,0);this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:c.len,bufferInfo:c})}}}}},i._tryFixBufferStall=function(e,t,i){var r,s,n=this.fragmentTracker,a=this.media,o=null==(r=this.hls)?void 0:r.config;if(a&&n&&o){var l=null==(s=this.hls)?void 0:s.latestLevelDetails,h=zo(i,n);if((h||null!=l&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;var u=e.buffered,d=this.adjacentTraversal(e,i);(u&&u.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}},i.adjacentTraversal=function(e,t){var i=this.fragmentTracker,r=e.nextStart;if(i&&r){var s=i.getFragAtPos(t,w),n=i.getFragAtPos(r,w);if(s&&n)return n.sn-s.sn<2}return!1},i._reportStall=function(e){var t=this.hls,i=this.media,r=this.stallReported,s=this.stalled;if(!r&&null!==s&&i&&t){this.stallReported=!0;var n=new Error("Playback stalling at @"+i.currentTime+" due to low buffer ("+it(e)+")");this.warn(n.message),t.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:s}})}},i._trySkipBufferHole=function(e){var t,i=this.fragmentTracker,r=this.media,s=null==(t=this.hls)?void 0:t.config;if(!r||!i||!s)return 0;var n=r.currentTime,a=jt.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){var l=a.len<=s.maxBufferHole,h=a.len>0&&a.len<1&&r.readyState<3,u=o-n;if(u>0&&(l||h)){if(u>s.maxBufferHole){var d=!1;if(0===n){var c=i.getAppendedFrag(0,w);c&&o<c.end&&(d=!0)}if(!d&&e){var f;if(null==(f=this.hls.loadLevelObj)||!f.details)return 0;if(jo(this.hls.inFlightFragments,o))return 0;for(var g=!1,p=e.end;p<o;){var v=zo(p,i);if(!v){g=!0;break}p+=v.duration}if(g)return 0}}var m=Math.max(o+.05,n+.1);if(this.warn("skipping hole, adjusting currentTime from "+n+" to "+m),this.moved=!0,r.currentTime=m,null==e||!e.gap){var y=new Error("fragment loaded with buffer holes, seeking from "+n+" to "+m),E={type:b.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:y,reason:y.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?E.part=e:E.frag=e),this.hls.trigger(I.ERROR,E)}return m}}return 0},i._tryNudgeBuffer=function(e){var t=this.hls,i=this.media,r=this.nudgeRetry,s=null==t?void 0:t.config;if(!i||!s)return 0;var n=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){var a=n+(r+1)*s.nudgeOffset,o=new Error("Nudging 'currentTime' from "+n+" to "+a);this.warn(o.message),i.currentTime=a,t.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{var l=new Error("Playhead still not moving while enough data buffered @"+n+" after "+s.nudgeMaxRetry+" nudges");this.error(l.message),t.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}},r(t,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}($t);function jo(e,t){var i=Yo(e.main);if(i&&i.start<=t)return i;var r=Yo(e.audio);return r&&r.start<=t?r:null}function Yo(e){if(!e)return null;switch(e.state){case lr.IDLE:case lr.STOPPED:case lr.ENDED:case lr.ERROR:return null}return e.frag}function zo(e,t){return t.getAppendedFrag(e,w)||t.getPartialFragment(e)}function Xo(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Qo(e,t,i,r,s){var n=new e(t,i,"");try{n.value=r,s&&(n.type=s)}catch(a){n=new e(t,i,it(s?u({type:s},r):r))}return n}var Jo=function(){var e=Xo();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),Zo=function(){function e(e){var t=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){t.hls&&t.hls.trigger(I.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}var t=e.prototype;return t.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null},t._registerListeners=function(){var e=this.hls;e&&(e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},t._unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},t.onMediaAttaching=function(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)},t.onMediaAttached=function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)},t.onMediaDetaching=function(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&Ua(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})},t.onManifestLoading=function(){this.dateRangeCuesAppended={}},t.createTrack=function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t},t.getID3Track=function(e){if(this.media){for(var t=0;t<e.length;t++){var i=e[t];if("metadata"===i.kind&&"id3"===i.label)return Na(i,this.media),i}return this.media.addTextTrack("metadata","id3")}},t.onFragParsingMetadata=function(e,t){if(this.media&&this.hls){var i=this.hls.config,r=i.enableEmsgMetadataCues,s=i.enableID3MetadataCues;if(r||s){var n=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=Xo();if(a)for(var o=0;o<n.length;o++){var l=n[o].type;if((l!==Or.emsg||r)&&s){var h=Dr(n[o].data),u=n[o].pts,d=u+n[o].duration;d>Jo&&(d=Jo),d-u<=0&&(d=u+.25);for(var c=0;c<h.length;c++){var f=h[c];if(!wr(f)){this.updateId3CueEnds(u,l);var g=Qo(a,u,d,f,l);g&&this.id3Track.addCue(g)}}}}}}},t.updateId3CueEnds=function(e,t){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var s=r.length;s--;){var n=r[s];n.type===t&&n.startTime<e&&n.endTime===Jo&&(n.endTime=e)}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,s=t.type,n=this.id3Track,a=this.hls;if(a){var o=a.config,l=o.enableEmsgMetadataCues,h=o.enableID3MetadataCues;n&&(l||h)&&Ga(n,i,r,"audio"===s?function(e){return e.type===Or.audioId3&&h}:"video"===s?function(e){return e.type===Or.emsg&&l}:function(e){return e.type===Or.audioId3&&h||e.type===Or.emsg&&l})}},t.onLevelUpdated=function(e,t){var i=t.details;this.updateDateRangeCues(i,!0)},t.onLevelPtsUpdated=function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var i=this;if(this.hls&&this.media){var r=this.hls.config,s=r.assetPlayerId,n=r.timelineOffset,a=r.enableDateRangeMetadataCues,o=r.interstitialsController;if(a){var l=Xo();if(s&&n&&!o){var h=e.fragmentStart,u=e.fragmentEnd,d=this.assetCue;d?(d.startTime=h,d.endTime=u):l&&(d=this.assetCue=Qo(l,h,u,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var c,f=this.id3Track,g=e.dateRanges,p=Object.keys(g),v=this.dateRangeCuesAppended;if(f&&t)if(null!=(c=f.cues)&&c.length)for(var m=Object.keys(v).filter((function(e){return!p.includes(e)})),y=function(){var e,t=m[E],r=null==(e=v[t])?void 0:e.cues;delete v[t],r&&Object.keys(r).forEach((function(e){var t=r[e];if(t){t.removeEventListener("enter",i.onEventCueEnter);try{f.removeCue(t)}catch(e){}}}))},E=m.length;E--;)y();else v=this.dateRangeCuesAppended={};var S=e.fragments[e.fragments.length-1];if(0!==p.length&&T(null==S?void 0:S.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var _=function(){var e=p[L],t=g[e],r=t.startTime,s=v[e],n=(null==s?void 0:s.cues)||{},a=(null==s?void 0:s.durationKnown)||!1,h=Jo,u=t.duration;if(t.endDate&&null!==u)h=r+u,a=!0;else if(t.endOnNext&&!a){var d=p.reduce((function(e,i){if(i!==t.id){var r=g[i];if(r.class===t.class&&r.startDate>t.startDate&&(!e||t.startDate<e.startDate))return r}return e}),null);d&&(h=d.startTime,a=!0)}for(var c,f=Object.keys(t.attr),m=0;m<f.length;m++){var y=f[m];if("ID"!==(c=y)&&"CLASS"!==c&&"CUE"!==c&&"START-DATE"!==c&&"DURATION"!==c&&"END-DATE"!==c&&"END-ON-NEXT"!==c){var E=n[y];if(E)!a||null!=s&&s.durationKnown?Math.abs(E.startTime-r)>.01&&(E.startTime=r,E.endTime=h):E.endTime=h;else if(l){var S=t.attr[y];ii(y)&&(S=Y(S));var T=Qo(l,r,h,{key:y,data:S},Or.dateRange);T&&(T.id=e,i.id3Track.addCue(T),n[y]=T,o&&("X-ASSET-LIST"!==y&&"X-ASSET-URL"!==y||T.addEventListener("enter",i.onEventCueEnter)))}}}v[e]={cues:n,dateRange:t,durationKnown:a}},L=0;L<p.length;L++)_()}}}}},e}(),el=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e=t.media,i=t.levelDetails;if(e&&i){t.currentTime=e.currentTime;var r=t.computeLatency();if(null!==r){t._latency=r;var s=t.config,n=s.lowLatencyMode,a=s.maxLiveSyncPlaybackRate;if(n&&1!==a&&i.live){var o=t.targetLatency;if(null!==o){var l=r-o;if(l<Math.min(t.maxLatency,o+i.targetduration)&&l>.05&&t.forwardBufferLength>1){var h=Math.min(2,Math.max(1,a)),u=Math.round(2/(1+Math.exp(-.75*l-t.edgeStalled))*20)/20,d=Math.min(h,Math.max(1,u));t.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&t.changeMediaPlaybackRate(e,1)}}}}},this.hls=e,this.config=e.config,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},t.registerListeners=function(){var e=this.hls;e&&(e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.ERROR,this.onError,this))},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.ERROR,this.onError,this))},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)},t.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)},t.onManifestLoading=function(){this._latency=null,this.stallCount=0},t.onLevelUpdated=function(e,t){var i=t.details;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onError=function(e,t){var i;t.details===A.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(r=this.targetLatency)?void 0:r.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+e.playbackRate+" to "+t),e.playbackRate=t)},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},r(e,[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,i=e.partHoldBack,r=e.targetduration,s=this.config,n=s.liveSyncDuration,a=s.liveSyncDurationCount,o=s.lowLatencyMode,l=this.hls.userConfig,h=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*r);var u=r;return h+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var i=this.levelDetails;if(null===i)return null;var r=i.edge,s=e-t-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}}])}(),tl=function(e){function t(t,i){var r;return(r=e.call(this,t,"level-controller")||this)._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,r._registerListeners(),r}o(t,e);var i=t.prototype;return i._registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.ERROR,this.onError,this)},i._unregisterListeners=function(){var e=this.hls;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.ERROR,this.onError,this)},i.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},i.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},i.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},i.onManifestLoading=function(e,t){this.resetLevels()},i.onManifestLoaded=function(e,t){var i=this,r=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,h=!1;t.levels.forEach((function(e){var t=e.attrs,u=e.audioCodec,d=e.videoCodec;u&&(e.audioCodec=u=Be(u,r)||void 0),d&&(d=e.videoCodec=function(e){for(var t=e.split(","),i=0;i<t.length;i++){var r=t[i].split(".");r.length>2&&"avc1"===r[0]&&(t[i]="avc1."+parseInt(r[1]).toString(16)+("000"+parseInt(r[2]).toString(16)).slice(-4))}return t.join(",")}(d));var c=e.width,f=e.height,g=e.unknownCodecs,p=(null==g?void 0:g.length)||0;if(o||(o=!(!c||!f)),l||(l=!!d),h||(h=!!u),p||u&&!i.isAudioSupported(u)||d&&!i.isVideoSupported(d))i.log('Some or all CODECS not supported "'+t.CODECS+'"');else{var v=t.CODECS,m=t["FRAME-RATE"],y=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],S=t.RESOLUTION,T=t["VIDEO-RANGE"],_=(E||".")+"-"+e.bitrate+"-"+S+"-"+m+"-"+v+"-"+T+"-"+y;if(n[_])if(n[_].uri===e.url||e.attrs["PATHWAY-ID"])n[_].addGroupId("audio",t.AUDIO),n[_].addGroupId("text",t.SUBTITLES);else{var L=a[_]+=1;e.attrs["PATHWAY-ID"]=new Array(L+1).join(".");var b=i.createLevel(e);n[_]=b,s.push(b)}else{var A=i.createLevel(e);n[_]=A,a[_]=1,s.push(A)}}})),this.filterAndSortMediaOptions(s,t,o,l,h)},i.createLevel=function(e){var t=new et(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){var r=new Error('SUPPLEMENTAL-CODECS not supported "'+i.videoCodec+'"');this.log(r.message),t.supportedResult=qe(r,[])}return t},i.isAudioSupported=function(e){return we(e,"audio",this.hls.config.preferManagedMediaSource)},i.isVideoSupported=function(e){return we(e,"video",this.hls.config.preferManagedMediaSource)},i.filterAndSortMediaOptions=function(e,t,i,r,s){var n,a=this,o=[],l=[],h=e,u=(null==(n=t.stats)?void 0:n.parsing)||{};if((i||r)&&s&&(h=h.filter((function(e){var t,i=e.videoCodec,r=e.videoRange,s=e.width,n=e.height;return(!!i||!(!s||!n))&&!!(t=r)&&Qe.indexOf(t)>-1}))),0===h.length)return Promise.resolve().then((function(){if(a.hls){var e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i="one or more CODECS in variant not supported: "+it(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,i){return i.indexOf(e)===t}))),a.warn(i),e+=" ("+i+")");var r=new Error(e);a.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}})),void(u.end=performance.now());t.audioTracks&&il(o=t.audioTracks.filter((function(e){return!e.audioCodec||a.isAudioSupported(e.audioCodec)}))),t.subtitles&&il(l=t.subtitles);var d=h.slice(0);h.sort((function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Qe.indexOf(e.videoRange)-Qe.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var r=Oe(e.videoCodec),s=Oe(t.videoCodec);if(r!==s)return s-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var n=xe(e.codecSet),a=xe(t.codecSet);if(n!==a)return a-n}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var c=d[0];if(this.steering&&(h=this.steering.filterParsedLevels(h)).length!==d.length)for(var f=0;f<d.length;f++)if(d[f].pathwayId===h[0].pathwayId){c=d[f];break}this._levels=h;for(var g=0;g<h.length;g++)if(h[g]===c){var p;this._firstLevel=g;var v=c.bitrate,m=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+h.length+" level(s) found, first bitrate: "+v),void 0===(null==(p=this.hls.userConfig)?void 0:p.abrEwmaDefaultEstimate)){var y=Math.min(v,this.hls.config.abrEwmaDefaultEstimateMax);y>m&&m===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}var E=s&&!r,S=this.hls.config,T=!(!S.audioStreamController||!S.audioTrackController),_={levels:h,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:T&&!E&&o.some((function(e){return!!e.url}))};u.end=performance.now(),this.hls.trigger(I.MANIFEST_PARSED,_)},i.onError=function(e,t){!t.fatal&&t.context&&t.context.type===P&&t.context.level===this.level&&this.checkRetry(t)},i.onFragBuffered=function(e,t){var i=t.frag;if(void 0!==i&&i.type===w){var r=i.elementaryStreams;if(!Object.keys(r).some((function(e){return!!r[e]})))return;var s=this._levels[i.level];null!=s&&s.loadError&&(this.log("Resetting level error count of "+s.loadError+" on frag buffered"),s.loadError=0)}},i.onLevelLoaded=function(e,t){var i,r,s=t.level,n=t.details,a=t.levelInfo;if(!a)return this.warn("Invalid level index "+s),void(null!=(r=t.deliveryDirectives)&&r.skip&&(n.deltaUpdateFailed=!0));if(a===this.currentLevel||t.withoutMultiVariant){0===a.fragmentError&&(a.loadError=0);var o=a.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(s,t,o)}else null!=(i=t.deliveryDirectives)&&i.skip&&(n.deltaUpdateFailed=!0)},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=this.getUrlWithDirectives(t.uri,i),s=this.currentLevelIndex,n=t.attrs["PATHWAY-ID"],a=t.details,o=null==a?void 0:a.age;this.log("Loading level index "+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(n?" Pathway "+n:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+r),this.hls.trigger(I.LEVEL_LOADING,{url:r,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||null})},i.removeLevel=function(e){var t,i=this;if(1!==this._levels.length){var r=this._levels.filter((function(t,r){return r!==e||(i.steering&&i.steering.removeLevel(t),t===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));Ji(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var s=r.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(I.LEVELS_UPDATED,{levels:r})}},i.onLevelsUpdated=function(e,t){var i=t.levels;this._levels=i},i.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,i=e.maxAutoLevel,r=e.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(I.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))},r(t,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}var s=this.currentLevelIndex,n=this.currentLevel,a=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,s!==e||!n||a!==l){this.log("Switching to level "+e+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+s+(a?" with Pathway "+a:""));var h={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(I.LEVEL_SWITCHING,h);var u=o.details;if(!u||u.live){var d=this.switchParams(o.uri,null==n?void 0:n.details,u);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),i=e.filter((function(e){return-1!==t.indexOf(e)}));if(e.length<1)return void this.warn("pathwayPriority "+e+" should contain at least one pathway from list: "+t);this.steering.pathwayPriority=i}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])}(js);function il(e){var t={};e.forEach((function(e){var i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}function rl(){return self.SourceBuffer||self.WebKitSourceBuffer}function sl(){if(!$())return!1;var e=rl();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var nl=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"stream-controller",w)||this).audioCodecSwap=!1,s.level=-1,s._forceStartLoad=!1,s._hasEnoughToStart=!1,s.altAudio=0,s.audioOnly=!1,s.fragPlaying=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s.onMediaPlaying=function(){s.tick()},s.onMediaSeeked=function(){var e=s.media,t=e?e.currentTime:null;if(null!==t&&T(t)&&(s.log("Media seeked to "+t.toFixed(3)),s.getBufferedFrag(t))){var i=s.getFwdBufferInfoAtPos(e,t,w,0);null!==i&&0!==i.len?s.tick():s.warn("Main forward buffer length at "+t+' on "seeked" event '+(i?i.len:"empty")+")")}},s.registerListeners(),s}o(t,e);var i=t.prototype;return i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this)},i.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},i.startLoad=function(e,t){if(this.levels){var i=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var s=r.startLevel;-1===s&&(r.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=r.firstAutoLevel),r.nextLoadLevel=s,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i),this.state=lr.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=lr.STOPPED},i.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},i.doTick=function(){switch(this.state){case lr.WAITING_LEVEL:var e=this.levels,t=this.level,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=lr.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=lr.IDLE;break}break;case lr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===lr.IDLE&&this.doTickIdle(),this.onTickEnd()},i.onTickEnd=function(){var t;e.prototype.onTickEnd.call(this),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},i.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,i=this.levels,r=this.media;if(null!==t&&(r||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var s=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=i&&i[s]){var n=i[s],a=this.getMainFwdBufferInfo();if(null!==a){var o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){var l={};return 2===this.altAudio&&(l.type="video"),this.hls.trigger(I.BUFFER_EOS,l),void(this.state=lr.ENDED)}if(this.buffering){e.loadLevel!==s&&-1===e.manualLevel&&this.log("Adapting to level "+s+" from level "+this.level),this.level=e.nextLoadLevel=s;var h=n.details;if(!h||this.state===lr.WAITING_LEVEL||this.waitForLive(n))return this.level=s,this.state=lr.WAITING_LEVEL,void(this.startFragRequested=!1);var u=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(!(u>=d)){this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);var c=this.backtrackFragment?this.backtrackFragment.start:a.end,f=this.getNextFragment(c,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&ee(f)&&this.fragmentTracker.getState(f)!==Dt){var g,p=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,v=h.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?X:Q,y=(m===Q?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m,w)}f=this.getNextFragmentLoopLoading(f,h,a,w,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,c))}}}}}},i.loadFragment=function(t,i,r){var s=this.fragmentTracker.getState(t);s===Rt||s===kt?ee(t)?this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,i)):e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i):this.clearTrackerIfNeeded(t)},i.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,w)},i.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},i.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},i.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);var s=this.getLevelDetails();if(null!=s&&s.live){var n=this.getMainFwdBufferInfo();if(!n||n.len<2*s.targetduration)return}if(!t.paused&&e){var a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;i=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(t.currentTime+i);if(l){var h=this.followingBufferedFrag(l);if(h){this.abortCurrentFrag();var u=h.maxStartPTS?h.maxStartPTS:h.start,d=h.duration,c=Math.max(l.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},i.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case lr.KEY_LOADING:case lr.FRAG_LOADING:case lr.FRAG_LOADING_WAITING_RETRY:case lr.PARSING:case lr.PARSED:this.state=lr.IDLE}this.nextLoadPosition=this.getLoadPosition()},i.flushMainBuffer=function(t,i){e.prototype.flushMainBuffer.call(this,t,i,2===this.altAudio?"video":null)},i.onMediaAttached=function(t,i){e.prototype.onMediaAttached.call(this,t,i);var r=i.media;ar(r,"playing",this.onMediaPlaying),ar(r,"seeked",this.onMediaSeeked)},i.onMediaDetaching=function(t,i){var r=this.media;r&&(or(r,"playing",this.onMediaPlaying),or(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,e.prototype.onMediaDetaching.call(this,t,i),i.transferMedia||(this._hasEnoughToStart=!1)},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(I.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},i.onManifestParsed=function(e,t){for(var i,r,s=!1,n=!1,a=0;a<t.levels.length;a++){var o=t.levels[a].audioCodec;o&&(s=s||-1!==o.indexOf("mp4a.40.2"),n=n||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&n&&!("function"==typeof(null==(r=rl())||null==(i=r.prototype)?void 0:i.changeType)),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},i.onLevelLoading=function(e,t){if(this.levels&&this.state===lr.IDLE){var i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=lr.WAITING_LEVEL)}},i.onLevelLoaded=function(e,t){var i,r=this.levels,s=this.startFragRequested,n=t.level,a=t.details,o=a.totalduration;if(r){this.log("Level "+n+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+", cc ["+a.startCC+", "+a.endCC+"] duration:"+o);var l=t.levelInfo,h=this.fragCurrent;!h||this.state!==lr.FRAG_LOADING&&this.state!==lr.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();var u=0;if(a.live||null!=(i=l.details)&&i.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,u),this.hls.trigger(I.LEVEL_UPDATED,{details:a,level:n}),this.state===lr.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=lr.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}else this.warn("Levels were reset while loading level "+n)},i.synchronizeToLiveEdge=function(e){var t=this.config,i=this.media;if(i){var r=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||s<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn("Playback: "+s.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+r.toFixed(3)),"buffered"===this.config.liveSyncMode){var h,u=jt.bufferInfo(i,r,0);if(null==(h=u.buffered)||!h.length)return void(i.currentTime=r);if(u.start<=s)return void(i.currentTime=r);var d=jt.bufferedInfo(u.buffered,s,0).nextStart;d&&(i.currentTime=d)}else i.currentTime=r}}},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,s=e.payload,n=this.levels;if(n){var a=n[i.level];if(a){var o=a.details;if(!o)return this.warn("Dropping fragment "+i.sn+" of level "+i.level+" after level details were reset"),void this.fragmentTracker.removeFragment(i);var l=a.videoCodec,h=o.PTSKnown||!o.live,u=null==(t=i.initSegment)?void 0:t.data,d=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Ws(this.hls,w,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,p=new Wt(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),v=this.initPTS[i.cc];c.push(s,u,d,l,i,r,o.totalduration,h,p,v)}else this.warn("Level "+i.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i.onAudioTrackSwitching=function(e,t){var i=this,r=this.hls,s=2===this.altAudio;if(ut(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.fragmentTracker.removeAllFragments(),r.once(I.BUFFER_FLUSHED,(function(){i.hls&&i.hls.trigger(I.AUDIO_TRACK_SWITCHED,t)})),void r.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(I.AUDIO_TRACK_SWITCHED,t)}},i.onAudioTrackSwitched=function(e,t){var i=ut(t.url,this.hls);if(i){var r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i?2:0,this.tick()},i.onBufferCreated=function(e,t){var i,r,s=t.tracks,n=!1;for(var a in s){var o=s[a];if("main"===o.id){if(r=a,i=o,"video"===a){var l=s[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log("Alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,s=i.type===w;if(s){if(this.fragContextChanged(i))return this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===lr.PARSED&&(this.state=lr.IDLE));var n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),ee(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}var a=this.media;a&&(!this._hasEnoughToStart&&jt.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())},i.onError=function(e,t){var i;if(t.fatal)this.state=lr.ERROR;else switch(t.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(w,t);break;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==lr.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==P||(this.state=lr.IDLE);break;case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case A.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},i.onFragLoadEmergencyAborted=function(){this.state=lr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==X||!this.altAudio){var r=(i===Q?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,i,w),this.tick())}},i.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels},i.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},i.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log("could not seek to "+i+", already seeking at "+t);var r=this.timelineOffset;r&&i&&(i+=r);var s=this.getLevelDetails(),n=jt.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0)))&&(this.log("adjusting start position by "+o+" to match buffer start"),i+=o,this.startPosition=i),t<i&&(this.log("seek to target start position "+i+" from current time "+t+" buffer start "+a),e.currentTime=i)}}},i._getAudioCodec=function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t},i._loadBitrateTestFrag=function(e,t){var i=this;e.bitrateTest=!0,this._doFragLoad(e,t).then((function(e){var r=i.hls,s=null==e?void 0:e.frag;if(s&&!i.fragContextChanged(s)){t.fragmentError=0,i.state=lr.IDLE,i.startFragRequested=!1,i.bitrateTest=!1;var n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(I.FRAG_LOADED,e),s.bitrateTest=!1}})).catch((function(t){i.state!==lr.STOPPED&&i.state!==lr.ERROR&&(i.warn(t),i.resetFragmentLoading(e))}))},i._handleTransmuxComplete=function(e){var t=this.playlistType,i=this.hls,r=e.remuxResult,s=e.chunkMeta,n=this.getCurrentContext(s);if(n){var a=n.frag,o=n.part,l=n.level,h=r.video,u=r.text,d=r.id3,c=r.initSegment,f=l.details,g=this.altAudio?void 0:r.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=lr.PARSING,c){var p=c.tracks;if(p){var v=a.initSegment||a;if(this.unhandledEncryptionError(c,a))return;this._bufferInitSegment(l,p,v,s),i.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:t,tracks:p})}var m=c.initPTS,y=c.timescale,E=this.initPTS[a.cc];if(T(m)&&(!E||E.baseTime!==m||E.timescale!==y)){var S=c.trackId;this.initPTS[a.cc]={baseTime:m,timescale:y,trackId:S},i.trigger(I.INIT_PTS_FOUND,{frag:a,id:t,initPTS:m,timescale:y,trackId:S})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);var _=f.fragments[a.sn-1-f.startSN],L=a.sn===f.startSN,b=!_||a.cc>_.cc;if(!1!==r.independent){var A=h.startPTS,R=h.endPTS,P=h.startDTS,k=h.endDTS;if(o)o.elementaryStreams[h.type]={startPTS:A,endPTS:R,startDTS:P,endDTS:k};else if(h.firstKeyFrame&&h.independent&&1===s.id&&!b&&(this.couldBacktrack=!0),h.dropped&&h.independent){var D=this.getMainFwdBufferInfo(),w=(D?D.end:this.getLoadPosition())+this.config.maxBufferHole,C=h.firstKeyFramePTS?h.firstKeyFramePTS:A;if(!L&&w<C-this.config.maxBufferHole&&!b)return void this.backtrack(a);b&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,R,a.start,k,!0)}else L&&A-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,A,R,P,k),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,s,L||b)}else{if(!L&&!b)return void this.backtrack(a);a.gap=!0}}if(g){var M=g.startPTS,O=g.endPTS,x=g.startDTS,F=g.endDTS;o&&(o.elementaryStreams[X]={startPTS:M,endPTS:O,startDTS:x,endDTS:F}),a.setElementaryStreamInfo(X,M,O,x,F),this.bufferFragmentData(g,a,o,s)}if(f&&null!=d&&d.samples.length){var N={id:t,frag:a,details:f,samples:d.samples};i.trigger(I.FRAG_PARSING_METADATA,N)}if(f&&u){var B={id:t,frag:a,details:f,samples:u.samples};i.trigger(I.FRAG_PARSING_USERDATA,B)}}}else this.resetWhenMissingContext(s)},i.logMuxedErr=function(e){this.warn((ee(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},i._bufferInitSegment=function(e,t,i,r){var s=this;if(this.state===lr.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));var n=t.audio,a=t.video,o=t.audiovideo;if(n){var l=e.audioCodec,h=Ue(n.codec,l);"mp4a"===h&&(h="mp4a.40.5");var u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h=-1!==h.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=n.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&-1===u.indexOf("firefox")&&(h="mp4a.40.5")}h&&-1!==h.indexOf("mp4a.40.5")&&-1!==u.indexOf("android")&&"audio/mpeg"!==n.container&&(h="mp4a.40.2",this.log("Android: force audio codec to "+h)),l&&l!==h&&this.log('Swapping manifest audio codec "'+l+'" for "'+h+'"'),n.levelCodec=h,n.id=w,this.log("Init audio buffer, container:"+n.container+", codecs[selected/level/parsed]=["+(h||"")+"/"+(l||"")+"/"+n.codec+"]"),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=w;var c=a.codec;if(4===(null==c?void 0:c.length))switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e"}this.log("Init video buffer, container:"+a.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+c+"]"+(a.codec!==c?" parsed-corrected="+a.codec:"")+(a.supplemental?" supplemental="+a.supplemental:"")),delete t.audiovideo}o&&(this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+e.codecs+"/"+o.codec+"]"),delete t.video,delete t.audio);var f=Object.keys(t);if(f.length){if(this.hls.trigger(I.BUFFER_CODECS,t),!this.hls)return;f.forEach((function(e){var n=t[e].initSegment;null!=n&&n.byteLength&&s.hls.trigger(I.BUFFER_APPENDING,{type:e,data:n,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}},i.getMainFwdBufferInfo=function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,w)},i.backtrack=function(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=lr.IDLE},i.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var i=e.currentTime;if(jt.isBuffered(e,i)?t=this.getAppendedFrag(i):jt.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;var r=this.fragPlaying,s=t.level;r&&t.sn===r.sn&&r.level===s||(this.fragPlaying=t,this.hls.trigger(I.FRAG_CHANGED,{frag:t}),r&&r.level===s||this.hls.trigger(I.LEVEL_SWITCHED,{level:s}))}}},r(t,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return T(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(T(t)){var i=this.getLevelDetails(),r=this.currentFrag||(i?ft(null,i.fragments,t):null);if(r){var s=r.programDateTime;if(null!==s){var n=s+1e3*(t-r.start);return new Date(n)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(hr),al=function(e){function t(t,i){var r;return(r=e.call(this,"key-loader",i)||this).config=void 0,r.keyIdToKeyInfo={},r.emeController=null,r.config=t,r}o(t,e);var i=t.prototype;return i.abort=function(e){for(var t in this.keyIdToKeyInfo){var i=this.keyIdToKeyInfo[t].loader;if(i){var r;if(e&&e!==(null==(r=i.context)?void 0:r.frag.type))return;i.abort()}}},i.detach=function(){for(var e in this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}},i.destroy=function(){for(var e in this.detach(),this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}},i.createKeyLoadError=function(e,t,i,r,s){return void 0===t&&(t=A.KEY_LOAD_ERROR),new Vt({type:b.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})},i.loadClear=function(e,t,i){var r=this;if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(var s,n=function(){var s=t[a];if(e.cc<=s.cc&&(!ee(e)||!ee(s)||e.sn<s.sn)||!i&&a==o-1)return{v:r.emeController.selectKeySystemFormat(s).then((function(e){if(r.emeController){s.setKeyFormat(e);var t=yi(e);return t?r.emeController.getKeySystemAccess([t]):void 0}}))}},a=0,o=t.length;a<o;a++)if(s=n())return s.v;if(this.config.requireKeySystemAccessOnStart){var l=Si(this.config);if(l.length)return this.emeController.getKeySystemAccess(l)}}return null},i.load=function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(i){return t.loadInternal(e,i)})):this.loadInternal(e)},i.loadInternal=function(e,t){var i,r;t&&e.setKeyFormat(t);var s=e.decryptdata;if(!s){var n=new Error(t?"Expected frag.decryptdata to be defined after setting format "+t:"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: "+(this.emeController&&this.config.emeEnabled)+")");return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,n))}var a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+a+'"')));var o=ol(s),l=this.keyIdToKeyInfo[o];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(r=l)&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then((function(t){var i=t.keyInfo;return s.key=i.decryptdata.key,{frag:e,keyInfo:i}}))}switch(this.log((this.keyIdToKeyInfo[o]?"Rel":"L")+"oading"+(s.keyId?" keyId: "+j(s.keyId):"")+" URI: "+s.uri+" from "+e.type+" "+e.level),l=this.keyIdToKeyInfo[o]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+s.method+'"')))}},i.loadKeyEME=function(e,t){var i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then((function(t){return e.mediaKeySessionContext=t,i}))).catch((function(i){throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i}))}return Promise.resolve(i)},i.loadKeyHTTP=function(e,t){var i=this,r=this.config,s=new(0,r.loader)(r);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((function(n,a){var o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,t,r,s){var o=r.frag,l=r.keyInfo,h=ol(l.decryptdata);if(!o.decryptdata||l!==i.keyIdToKeyInfo[h])return a(i.createKeyLoadError(o,A.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,l.loader=null,n({frag:o,keyInfo:l})},onError:function(e,r,s,n){i.resetLoader(r),a(i.createKeyLoadError(t,A.KEY_LOAD_ERROR,new Error("HTTP Error "+e.code+" loading key "+e.text),s,u({url:o.url,data:void 0},e)))},onTimeout:function(e,r,s){i.resetLoader(r),a(i.createKeyLoadError(t,A.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:function(e,r,s){i.resetLoader(r),a(i.createKeyLoadError(t,A.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,h,d)}))},i.resetLoader=function(e){var t=e.frag,i=e.keyInfo,r=e.url,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null);var n=ol(i.decryptdata)||r;delete this.keyIdToKeyInfo[n],s&&s.destroy()},t}(F);function ol(e){if(e.keyFormat!==pi){var t=e.keyId;if(t)return j(t)}return e.uri}function ll(e){switch(e.type){case k:return C;case D:return M;default:return w}}function hl(e,t){var i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}var ul=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.createInternalLoader=function(e){var t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var i=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:R,url:i,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var i=t.id,r=t.level,s=t.pathwayId,n=t.url,a=t.deliveryDirectives,o=t.levelInfo;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:P,url:n,deliveryDirectives:a,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var i=t.id,r=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:k,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onSubtitleTrackLoading=function(e,t){var i=t.id,r=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:D,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onLevelsUpdated=function(e,t){var i=this.loaders[P];if(i){var r=i.context;r&&!t.levels.some((function(e){return e===r.levelOrTrack}))&&(i.abort(),delete this.loaders[P])}},t.load=function(e){var t,i,r,s=this,a=this.hls.config,o=this.getInternalLoader(e);if(o){var l=this.hls.logger,h=o.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives))return void(h.url===e.url?l.log("[playlist-loader]: ignore "+e.url+" ongoing request"):l.log("[playlist-loader]: ignore "+e.url+" in favor of "+h.url));l.log("[playlist-loader]: aborting previous loader for type: "+e.type),o.abort()}if(i=e.type===R?a.manifestLoadPolicy.default:n({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),o=this.createInternalLoader(e),T(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===P&&null!==e.level?r=this.hls.levels[e.level].details:e.type===k&&null!==e.id?r=this.hls.audioTracks[e.id].details:e.type===D&&null!==e.id&&(r=this.hls.subtitleTracks[e.id].details),r)){var u=r.partTarget,d=r.targetduration;if(u&&d){var c=1e3*Math.max(3*u,.8*d);i=n({},i,{maxTimeToFirstByteMs:Math.min(c,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,i.maxTimeToFirstByteMs)})}}var f=i.errorRetry||i.timeoutRetry||{},g={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},p={onSuccess:function(e,t,i,r){var n=s.getInternalLoader(i);s.resetInternalLoader(i.type);var a=e.data;t.parsing.start=performance.now(),Di.isMediaPlaylist(a)||i.type!==R?s.handleTrackOrLevelPlaylist(e,t,i,r||null,n):s.handleMasterPlaylist(e,t,i,r)},onError:function(e,t,i,r){s.handleNetworkError(t,i,!1,e,r)},onTimeout:function(e,t,i){s.handleNetworkError(t,i,!0,void 0,e)}};o.load(e,g,p)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,i=t.autoStartLoad,r=t.startPosition,s=e.forceStartLoad;(i||s)&&(this.hls.logger.log((i?"auto":"force")+" startLoad with configured startPosition "+r),this.hls.startLoad(r))}},t.handleMasterPlaylist=function(e,t,i,r){var s=this,n=this.hls,a=e.data,o=hl(e,i),l=Di.parseMasterPlaylist(a,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);var h=l.contentSteering,u=l.levels,d=l.sessionData,c=l.sessionKeys,f=l.startTimeOffset,g=l.variableList;this.variableList=g,u.forEach((function(e){var t=e.unknownCodecs;if(t)for(var i=s.hls.config.preferManagedMediaSource,r=e.audioCodec,n=e.videoCodec,a=t.length;a--;){var o=t[a];we(o,"audio",i)?(e.audioCodec=r=r?r+","+o:o,ke.audio[r.substring(0,4)]=2,t.splice(a,1)):we(o,"video",i)&&(e.videoCodec=n=n?n+","+o:o,ke.video[n.substring(0,4)]=2,t.splice(a,1))}}));var p=Di.parseMasterPlaylistMedia(a,o,l),v=p.AUDIO,m=void 0===v?[]:v,y=p.SUBTITLES,E=p["CLOSED-CAPTIONS"];m.length&&(m.some((function(e){return!e.url}))||!u[0].audioCodec||u[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ti({}),bitrate:0,url:""}))),n.trigger(I.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:y,captions:E,contentSteering:h,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:c,startTimeOffset:f,variableList:g})},t.handleTrackOrLevelPlaylist=function(e,t,i,r,s){var n=this.hls,a=i.id,o=i.level,l=i.type,h=hl(e,i),u=T(o)?o:T(a)?a:0,d=ll(i),c=Di.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===R){var f={attrs:new ti({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=t.loading.start+Yi(c,0),n.trigger(I.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,e,t,i,r,s)},t.handleManifestParsingError=function(e,t,i,r,s){this.hls.trigger(I.ERROR,{type:b.NETWORK_ERROR,details:A.MANIFEST_PARSING_ERROR,fatal:t.type===R,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})},t.handleNetworkError=function(e,t,i,r,s){void 0===i&&(i=!1);var n="A network "+(i?"timeout":"error"+(r?" (status "+r.code+")":""))+" occurred while loading "+e.type;e.type===P?n+=": "+e.level+" id: "+e.id:e.type!==k&&e.type!==D||(n+=" id: "+e.id+' group-id: "'+e.groupId+'"');var a=new Error(n);this.hls.logger.warn("[playlist-loader]: "+n);var o=A.UNKNOWN,l=!1,h=this.getInternalLoader(e);switch(e.type){case R:o=i?A.MANIFEST_LOAD_TIMEOUT:A.MANIFEST_LOAD_ERROR,l=!0;break;case P:o=i?A.LEVEL_LOAD_TIMEOUT:A.LEVEL_LOAD_ERROR,l=!1;break;case k:o=i?A.AUDIO_TRACK_LOAD_TIMEOUT:A.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case D:o=i?A.SUBTITLE_TRACK_LOAD_TIMEOUT:A.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);var d={type:b.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(r){var c=(null==t?void 0:t.url)||e.url;d.response=u({url:c,data:void 0},r)}this.hls.trigger(I.ERROR,d)},t.handlePlaylistLoaded=function(e,t,i,r,s,n){var a=this.hls,o=r.type,l=r.level,h=r.levelOrTrack,u=r.id,d=r.groupId,c=r.deliveryDirectives,f=hl(t,r),g=ll(r),p="number"==typeof r.level&&g===w?l:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(v+" "+e.url),!a.config.ignorePlaylistParsingErrors)return void a.trigger(I.ERROR,{type:b.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:r,level:p,parent:g,networkDetails:s,stats:i});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case R:case P:if(p)if(h){if(h!==a.levels[p]){var m=a.levels.indexOf(h);m>-1&&(p=m)}}else p=0;a.trigger(I.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:p||0,id:u||0,stats:i,networkDetails:s,deliveryDirectives:c,withoutMultiVariant:o===R});break;case k:a.trigger(I.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:c});break;case D:a.trigger(I.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:c})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(I.ERROR,{type:b.NETWORK_ERROR,details:A.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:r,level:p,parent:g,networkDetails:s,stats:i})}},e}(),dl=function(){function e(t){void 0===t&&(t={}),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new y,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var i=this.logger=K(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=Wo(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var n=("level"===e?"playlist":e)+"LoadPolicy",a=void 0===t[n],o=[];s.forEach((function(i){var s=e+"Loading"+i,l=t[s];if(void 0!==l&&a){o.push(s);var h=r[n].default;switch(t[n]={default:h},i){case"TimeOut":h.maxLoadTimeMs=l,h.maxTimeToFirstByteMs=l;break;case"MaxRetry":h.errorRetry.maxNumRetry=l,h.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":h.errorRetry.retryDelayMs=l,h.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=l,h.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+n+'": '+it(t[n]))})),u(u({},r),t)}(e.DefaultConfig,t,i);this.userConfig=t,r.progressive&&function(e,t){var i=e.loader;i!==Uo&&i!==Vo?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=Uo,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(r,i);var s=r.abrController,n=r.bufferController,a=r.capLevelController,o=r.errorController,l=r.fpsController,h=new o(this),d=this.abrController=new s(this),c=new wt(this),f=r.interstitialsController,g=f?this.interstitialsController=new f(this,e):null,p=this.bufferController=new n(this,c),v=this.capLevelController=new a(this),m=new l(this),E=new ul(this),S=r.contentSteeringController,T=S?new S(this):null,_=this.levelController=new tl(this,T),L=new Zo(this),b=new al(this.config,this.logger),A=this.streamController=new nl(this,c,b),R=this.gapController=new qo(this,c);v.setStreamController(A),m.setStreamController(A);var P=[E,_,A];g&&P.splice(1,0,g),T&&P.splice(1,0,T),this.networkControllers=P;var k=[d,p,R,v,m,L,c];this.audioTrackController=this.createController(r.audioTrackController,P);var D=r.audioStreamController;D&&P.push(this.audioStreamController=new D(this,c,b)),this.subtitleTrackController=this.createController(r.subtitleTrackController,P);var w=r.subtitleStreamController;w&&P.push(this.subtititleStreamController=new w(this,c,b)),this.createController(r.timelineController,k),b.emeController=this.emeController=this.createController(r.emeController,k),this.cmcdController=this.createController(r.cmcdController,k),this.latencyController=this.createController(el,k),this.coreComponents=k,P.push(h);var C=h.onErrorOut;"function"==typeof C&&this.on(I.ERROR,C,h),this.on(I.MANIFEST_LOADED,E.onManifestLoaded,E)}e.isMSESupported=function(){return sl()},e.isSupported=function(){return function(){if(!sl())return!1;var e=$();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(t){return e.isTypeSupported(Me(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Me(t,"audio"))})))}()},e.getMediaSource=function(){return $()};var t=e.prototype;return t.createController=function(e,t){if(e){var i=new e(this);return t&&t.push(i),i}return null},t.on=function(e,t,i){void 0===i&&(i=this),this._emitter.on(e,t,i)},t.once=function(e,t,i){void 0===i&&(i=this),this._emitter.once(e,t,i)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,i,r){void 0===i&&(i=this),this._emitter.off(e,t,i,r)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,i){return this._emitter.emit(e,t,i)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var i=e===I.ERROR;this.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){this.logger.log("destroy"),this.trigger(I.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},t.attachMedia=function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument ("+e+")");this.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var i="media"in e,r=i?e.media:e,s=i?e:{media:r};this._media=r,this.trigger(I.MEDIA_ATTACHING,s)}},t.detachMedia=function(){this.logger.log("detachMedia"),this.trigger(I.MEDIA_DETACHING,{}),this._media=null},t.transferMedia=function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(I.MEDIA_DETACHING,{transferMedia:e}),e},t.loadSource=function(e){this.stopLoad();var t=this.media,i=this._url,r=this._url=S.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+r),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(I.MANIFEST_LOADING,{url:e})},t.startLoad=function(e,t){void 0===e&&(e=-1),this.logger.log("startLoad("+e+(t?", <skip seek to start>":"")+")"),this.started=!0,this.resumeBuffering();for(var i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);},t.stopLoad=function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);},t.resumeBuffering=function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((function(e){e.resumeBuffering&&e.resumeBuffering()})))},t.pauseBuffering=function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((function(e){e.pauseBuffering&&e.pauseBuffering()})))},t.swapAudioCodec=function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.recoverMediaError=function(){this.logger.log("recoverMediaError");var e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))},t.removeLevel=function(e){this.levelController.removeLevel(e)},t.setAudioOption=function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null},t.setSubtitleOption=function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null},t.getMediaDecodingInfo=function(e,t){return void 0===t&&(t=this.allAudioTracks),je(e,st(t),navigator.mediaCapabilities)},r(e,[{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"loadingEnabled",get:function(){return this.started}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"inFlightFragments",get:function(){var e,t=((e={})[w]=this.streamController.inFlightFrag,e);return this.audioStreamController&&(t[C]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[M]=this.subtititleStreamController.inFlightFrag),t}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(r){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(i+16*Math.random())%16|0;return i=Math.floor(i/16),("x"==e?t:3&t|8).toString(16)}))}}}()),e}},{key:"levels",get:function(){return this.levelController.levels||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return Xe.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var i=e.length,r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(var s=e;s--;){var n=t[s].attrs["HDCP-LEVEL"];if(n&&n<=r)return s}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency},set:function(e){this.latencyController.targetLatency=e}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}}],[{key:"version",get:function(){return Ks}},{key:"Events",get:function(){return I}},{key:"MetadataSchema",get:function(){return Or}},{key:"ErrorTypes",get:function(){return b}},{key:"ErrorDetails",get:function(){return A}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:$o},set:function(t){e.defaultConfig=t}}])}();return dl.defaultConfig=void 0,dl},e.exports=r()}(!1)},424:(e,t)=>{"use strict";t.h=s;var i=2147483647;function r(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return n(e,t,i)}function n(e,t,i){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var i=0|u(e,t),n=r(i),a=n.write(e,t);a!==i&&(n=n.slice(0,a));return n}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(m(e,ArrayBuffer)||e&&m(e.buffer,ArrayBuffer))return function(e,t,i){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(i||0))throw new RangeError('"length" is outside of buffer bounds');var r;r=void 0===t&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,t):new Uint8Array(e,t,i);return r.__proto__=s.prototype,r}(e,t,i);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return s.from(n,t,i);var a=function(e){if(s.isBuffer(e)){var t=0|h(e.length),i=r(t);return 0===i.length||e.copy(i,0,0,t),i}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?r(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function a(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function o(e){return a(e),r(e<0?0:0|h(e))}function l(e){for(var t=e.length<0?0:0|h(e.length),i=r(t),s=0;s<t;s+=1)i[s]=255&e[s];return i}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function u(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||m(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var i=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===i)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return v(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;default:if(n)return r?-1:v(e).length;t=(""+t).toLowerCase(),n=!0}}function d(e,t,i,r){i=Number(i)||0;const s=e.length-i;r?(r=Number(r))>s&&(r=s):r=s;const n=t.length;let a;for(r>n/2&&(r=n/2),a=0;a<r;++a){const r=parseInt(t.substr(2*a,2),16);if(y(r))return a;e[i+a]=r}return a}function c(e,t,i,r){return p(v(t,e.length-i),e,i,r)}function f(e,t,i,r){return p(function(e){const t=[];for(let i=0;i<e.length;++i)t.push(255&e.charCodeAt(i));return t}(t),e,i,r)}function g(e,t,i,r){return p(function(e,t){let i,r,s;const n=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)i=e.charCodeAt(a),r=i>>8,s=i%256,n.push(s),n.push(r);return n}(t,e.length-i),e,i,r)}function p(e,t,i,r){let s;for(s=0;s<r&&!(s+i>=t.length||s>=e.length);++s)t[s+i]=e[s];return s}function v(e,t){var i;t=t||1/0;for(var r=e.length,s=null,n=[],a=0;a<r;++a){if((i=e.charCodeAt(a))>55295&&i<57344){if(!s){if(i>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&n.push(239,191,189);continue}s=i;continue}if(i<56320){(t-=3)>-1&&n.push(239,191,189),s=i;continue}i=65536+(s-55296<<10|i-56320)}else s&&(t-=3)>-1&&n.push(239,191,189);if(s=null,i<128){if((t-=1)<0)break;n.push(i)}else if(i<2048){if((t-=2)<0)break;n.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;n.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return n}function m(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.from=function(e,t,i){return n(e,t,i)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,i){return function(e,t,i){return a(e),e<=0?r(e):void 0!==t?"string"==typeof i?r(e).fill(t,i):r(e).fill(t):r(e)}(e,t,i)},s.allocUnsafe=function(e){return o(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var i;if(void 0===t)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=s.allocUnsafe(t),n=0;for(i=0;i<e.length;++i){var a=e[i];if(m(a,Uint8Array)&&(a=s.from(a)),!s.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(r,n),n+=a.length}return r},s.byteLength=u,s.prototype._isBuffer=!0,s.prototype.copy=function(e,t,i,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var n=r-i;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,i,r);else if(this===e&&i<t&&t<r)for(var a=n-1;a>=0;--a)e[a+t]=this[a+i];else Uint8Array.prototype.set.call(e,this.subarray(i,r),t);return n},s.prototype.write=function(e,t,i,r){if(void 0===t)r="utf8",i=this.length,t=0;else if(void 0===i&&"string"==typeof t)r=t,i=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(i)?(i>>>=0,void 0===r&&(r="utf8")):(r=i,i=void 0)}const s=this.length-t;if((void 0===i||i>s)&&(i=s),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let n=!1;for(;;)switch(r){case"hex":return d(this,e,t,i);case"utf8":case"utf-8":return c(this,e,t,i);case"ascii":case"latin1":case"binary":return f(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,i);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),n=!0}}},832:function(e,t,i){var r;!function(s){"use strict";function n(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function a(e,t,i,r,s,a){return n((o=n(n(t,e),n(r,a)))<<(l=s)|o>>>32-l,i);var o,l}function o(e,t,i,r,s,n,o){return a(t&i|~t&r,e,t,s,n,o)}function l(e,t,i,r,s,n,o){return a(t&r|i&~r,e,t,s,n,o)}function h(e,t,i,r,s,n,o){return a(t^i^r,e,t,s,n,o)}function u(e,t,i,r,s,n,o){return a(i^(t|~r),e,t,s,n,o)}function d(e,t){var i,r,s,a,d;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var c=1732584193,f=-271733879,g=-1732584194,p=271733878;for(i=0;i<e.length;i+=16)r=c,s=f,a=g,d=p,c=o(c,f,g,p,e[i],7,-680876936),p=o(p,c,f,g,e[i+1],12,-389564586),g=o(g,p,c,f,e[i+2],17,606105819),f=o(f,g,p,c,e[i+3],22,-1044525330),c=o(c,f,g,p,e[i+4],7,-176418897),p=o(p,c,f,g,e[i+5],12,1200080426),g=o(g,p,c,f,e[i+6],17,-1473231341),f=o(f,g,p,c,e[i+7],22,-45705983),c=o(c,f,g,p,e[i+8],7,1770035416),p=o(p,c,f,g,e[i+9],12,-1958414417),g=o(g,p,c,f,e[i+10],17,-42063),f=o(f,g,p,c,e[i+11],22,-1990404162),c=o(c,f,g,p,e[i+12],7,1804603682),p=o(p,c,f,g,e[i+13],12,-40341101),g=o(g,p,c,f,e[i+14],17,-1502002290),c=l(c,f=o(f,g,p,c,e[i+15],22,1236535329),g,p,e[i+1],5,-165796510),p=l(p,c,f,g,e[i+6],9,-1069501632),g=l(g,p,c,f,e[i+11],14,643717713),f=l(f,g,p,c,e[i],20,-373897302),c=l(c,f,g,p,e[i+5],5,-701558691),p=l(p,c,f,g,e[i+10],9,38016083),g=l(g,p,c,f,e[i+15],14,-660478335),f=l(f,g,p,c,e[i+4],20,-405537848),c=l(c,f,g,p,e[i+9],5,568446438),p=l(p,c,f,g,e[i+14],9,-1019803690),g=l(g,p,c,f,e[i+3],14,-187363961),f=l(f,g,p,c,e[i+8],20,1163531501),c=l(c,f,g,p,e[i+13],5,-1444681467),p=l(p,c,f,g,e[i+2],9,-51403784),g=l(g,p,c,f,e[i+7],14,1735328473),c=h(c,f=l(f,g,p,c,e[i+12],20,-1926607734),g,p,e[i+5],4,-378558),p=h(p,c,f,g,e[i+8],11,-2022574463),g=h(g,p,c,f,e[i+11],16,1839030562),f=h(f,g,p,c,e[i+14],23,-35309556),c=h(c,f,g,p,e[i+1],4,-1530992060),p=h(p,c,f,g,e[i+4],11,1272893353),g=h(g,p,c,f,e[i+7],16,-155497632),f=h(f,g,p,c,e[i+10],23,-1094730640),c=h(c,f,g,p,e[i+13],4,681279174),p=h(p,c,f,g,e[i],11,-358537222),g=h(g,p,c,f,e[i+3],16,-722521979),f=h(f,g,p,c,e[i+6],23,76029189),c=h(c,f,g,p,e[i+9],4,-640364487),p=h(p,c,f,g,e[i+12],11,-421815835),g=h(g,p,c,f,e[i+15],16,530742520),c=u(c,f=h(f,g,p,c,e[i+2],23,-995338651),g,p,e[i],6,-198630844),p=u(p,c,f,g,e[i+7],10,1126891415),g=u(g,p,c,f,e[i+14],15,-1416354905),f=u(f,g,p,c,e[i+5],21,-57434055),c=u(c,f,g,p,e[i+12],6,1700485571),p=u(p,c,f,g,e[i+3],10,-1894986606),g=u(g,p,c,f,e[i+10],15,-1051523),f=u(f,g,p,c,e[i+1],21,-2054922799),c=u(c,f,g,p,e[i+8],6,1873313359),p=u(p,c,f,g,e[i+15],10,-30611744),g=u(g,p,c,f,e[i+6],15,-1560198380),f=u(f,g,p,c,e[i+13],21,1309151649),c=u(c,f,g,p,e[i+4],6,-145523070),p=u(p,c,f,g,e[i+11],10,-1120210379),g=u(g,p,c,f,e[i+2],15,718787259),f=u(f,g,p,c,e[i+9],21,-343485551),c=n(c,r),f=n(f,s),g=n(g,a),p=n(p,d);return[c,f,g,p]}function c(e){var t,i="",r=32*e.length;for(t=0;t<r;t+=8)i+=String.fromCharCode(e[t>>5]>>>t%32&255);return i}function f(e){var t,i=[];for(i[(e.length>>2)-1]=void 0,t=0;t<i.length;t+=1)i[t]=0;var r=8*e.length;for(t=0;t<r;t+=8)i[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return i}function g(e){var t,i,r="0123456789abcdef",s="";for(i=0;i<e.length;i+=1)t=e.charCodeAt(i),s+=r.charAt(t>>>4&15)+r.charAt(15&t);return s}function p(e){return unescape(encodeURIComponent(e))}function v(e){return function(e){return c(d(f(e),8*e.length))}(p(e))}function m(e,t){return function(e,t){var i,r,s=f(e),n=[],a=[];for(n[15]=a[15]=void 0,s.length>16&&(s=d(s,8*e.length)),i=0;i<16;i+=1)n[i]=909522486^s[i],a[i]=1549556828^s[i];return r=d(n.concat(f(t)),512+8*t.length),c(d(a.concat(r),640))}(p(e),p(t))}function y(e,t,i){return t?i?m(t,e):g(m(t,e)):i?v(e):g(v(e))}void 0===(r=function(){return y}.call(t,i,t,e))||(e.exports=r)}()},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var i={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(r())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return i.isAndroid()||i.isAndroidWebView()?t.ANDROID_WEB:i.isIOS()||i.isIpad()||i.isIOSWebView()?t.IOS_WEB:i.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(r())},isPC:function(){return!n(s("os "))&&!n(s("android[/ ]"))},isIOS:function(){return n(s("os "))},isIpad:function(){return r().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return n(s("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(r())},isMobile:function(){return i.isAndroid()||i.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(r())},isFirefox:function(){return/firefox/i.test(r())},isChrome:function(){return/chrome/i.test(r())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=r();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=r();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return i.isAndroidWebView()||i.isIOSWebView()},device:t,getBrowser:function(){return i.isX5()?"X5":i.isAndroidWebView()?"Android-WebView":i.isIOSWebView()?"iOS-WebView":i.isChrome()?"Chrome":i.isFirefox()?"Firefox":i.isIpadSafari()?"iPad-Safari":i.isIOSSafari()?"iPhone-Safari":i.isSafari()?"Mac-Safari":"Unknown"}};function r(){return navigator.userAgent.toLowerCase()}function s(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(r())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=i}},t={};function i(r){var s=t[r];if(void 0!==s)return s.exports;var n=t[r]={exports:{}};return e[r].call(n.exports,n,n.exports,i),n.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var r={};return(()=>{"use strict";i.d(r,{default:()=>Mi});const e={DC_SIGNAL:"SIGNAL",DC_SIGNAL_BATCH:"SIGNAL_BATCH",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_PIECE_CANCEL:"PIECE_CANCEL",DC_CLOSE:"CLOSE",DC_DISCONNECT:"DISCONNECT",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",BM_FATAL_ERROR:"BM_FATAL_ERROR",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PROGRESS:"SYN_PROGRESS",MEDIA_REBUFFER:"MEDIA_REBUFFER"},t={...e,SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_GET_MEDIA:"SW_GET_MEDIA",SW_DEBUG:"SW_DEBUG",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED"};var s=i(415),n=i.n(s),a=i(424),o=i(558),l=i.n(o);const h="__PROXY_IDENTIFIER__";const u=64e3;function d(){return!0}function c(e){return new URL(location.href).searchParams.get(e)}function f(e,t,i){const r=new URL(e);return r.searchParams.append(t,i),r.href}function g(){return Date.parse(new Date)/1e3}function p(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function v(e){return new Promise((t=>setTimeout(t,e)))}function m(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function y(e){const t=a.h.from(e),i=new a.h(e.byteLength);return t.copy(i),i}function E(){return location.protocol.startsWith("https")}function S(e,t,i){if(e.size<=t)return;const r=[...e.keys()];do{const t=r.shift();i&&i(e.get(t)),e.delete(t)}while(e.size>t)}function T(e,t){if(e.size<=t)return;const i=[...e.values()];do{e.delete(i.shift())}while(e.size>t)}function _(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function L(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const i=Number(t[0]),r=t[1]?Number(t[1]):-1;return{rangeStart:i,rangeEnd:r>=0?r+1:void 0}}function b(e){return e.split("?")[0]}function A(){let e=new Date,t=e.getHours(),i=e.getMinutes(),r=e.getSeconds(),s=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}.${s}`}function I(e){return e&&"function"==typeof e}function R(e,t,i,r,s,n){e.sendPartialBuffer(i,r,{from:s,incompletes:n})&&(r.length<i.attachments?function(e,t,i){e.addStreamListener(i,t.remotePeerId,((e,i,r,s,n)=>{r?t.sendMsgPieceAbort(s,i,!0):t.uploading&&t.send(s),n&&(t.uploading=!1)}))}(t,e,!!i.reverse):e.uploading=!1)}const P=e=>0===p(0,1)?[null,e]:[e,null];function k(e,t,i){return 1===e.length?t.length>=1&&i.length>=1?t[0].weight>i[0].weight?[t[0],e[0]]:[e[0],i[0]]:t.length>=1?[t[0],e[0]]:i.length>=1?[e[0],i[0]]:P(e[0]):[t.length>=1?t[0]:null,i.length>=1?i[0]:null]}function D(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}async function w(e){if(crypto.subtle)try{const t=await crypto.subtle.digest("SHA-256",e),i=String.fromCharCode.apply(null,new Uint8Array(t));return btoa(i)}catch(e){}}class C{constructor(e,t){this.target=t,this.type=e}}class M extends C{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class O extends C{constructor(e=1e3,t="",i){super("close",i),this.code=e,this.reason=t,this.wasClean=!0}}const x=()=>{if("undefined"!=typeof WebSocket)return WebSocket},F={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1};class N{constructor(e,t,i={}){this._listeners={error:[],message:[],open:[],close:[]},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._messageQueue=[],this._closeCalled=!1,this._connectLock=!1,this._shouldReconnect=!0,this._retryCount=-1,this._binaryType="blob",this._url=e,this._protocols=t,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect(),this._handleOpen=this._handleOpen.bind(this),this._handleClose=this._handleClose.bind(this),this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this)}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return N.CONNECTING}get OPEN(){return N.OPEN}get CLOSING(){return N.CLOSING}get CLOSED(){return N.CLOSED}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?N.CLOSED:N.CONNECTING}get url(){return this._ws?this._ws.url:""}close(e=1e3,t){this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws&&this._ws.readyState!==this.CLOSED&&this._ws.close(e,t)}reconnect(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._ws.send(e);else{const{maxEnqueuedMessages:t=F.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&this._messageQueue.push(e)}}addEventListener(e,t){this._listeners[e]&&this._listeners[e].push(t)}dispatchEvent(e){const t=this._listeners[e.type];if(t)for(const i of t)this._callEventListener(e,i);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=F.reconnectionDelayGrowFactor,minReconnectionDelay:t=F.minReconnectionDelay,maxReconnectionDelay:i=F.maxReconnectionDelay}=this._options;let r=0;return this._retryCount>0&&(r=t*Math.pow(e,this._retryCount-1),r>i&&(r=i)),r}_wait(){return new Promise((e=>{setTimeout(e,this._getNextDelay())}))}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:e=F.maxRetries,connectionTimeout:t=F.connectionTimeout,WebSocket:i=x()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(r=i)||!r||2!==r.CLOSING)throw Error("No valid WebSocket class provided");var r;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new i(e,this._protocols):new i(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout((()=>this._handleTimeout()),t))})).catch((e=>{this._connectLock=!1,this._handleError(new M(Error(e.message),this))}))}}_handleTimeout(){this._handleError(new M(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new O(e,t,this))}catch(e){}}}_acceptOpen(){this._retryCount=0}_callEventListener(e,t){"handleEvent"in t?t.handleEvent(e):t(e)}_handleOpen(e){const{minUptime:t=F.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout((()=>this._acceptOpen()),t),this._ws.binaryType=this._binaryType,this._messageQueue.forEach((e=>this._ws.send(e))),this._messageQueue=[],this.onopen&&this.onopen(e),this._listeners.open.forEach((t=>this._callEventListener(e,t)))}_handleMessage(e){this.onmessage&&this.onmessage(e),this._listeners.message.forEach((t=>this._callEventListener(e,t)))}_handleError(e){this._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),this.onerror&&this.onerror(e),this._listeners.error.forEach((t=>this._callEventListener(e,t))),this._connect()}_handleClose(e){this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this._listeners.close.forEach((t=>this._callEventListener(e,t)))}_removeListeners(){this._ws&&(this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const B={debug:3,info:4,warn:5,error:6};class U{constructor(e,t,i,r){this.wsAddr=`${e}?app=${t}&id=${i}&v=${r}`,this.destroyed=!1;try{this._ws=this._init()}catch(e){console.error(e)}}_init(){const e={maxRetries:3,minReconnectionDelay:p(5e3,15e3),maxReconnectionDelay:6e5,maxEnqueuedMessages:200};return new N(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const i=B[e];this._ws.send(JSON.stringify({records:[{level:i,text:`${A()}: ${t}`}]}))}sendBatch(e){const t=[];for(let i of e)t.push({level:B[i.levelKey],text:i.message});this._ws.send(JSON.stringify({records:t}))}destroy(){this._ws&&(this._ws.close(1e3),this._ws=null,this.destroyed=!0)}}const G=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}},H=(e,t,i)=>{((e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)})(e,{value:t,duration:i,startTime:Date.now()})},K={debug:0,info:1,warn:2,error:3,none:4};const V=class{constructor(e){this.logLevel=e,this.onlineDebug=!1,this.logCache=[];try{console.debug=console.log}catch(e){console.debug=console.info}"debug"!==e&&"info"!==e||(this.logLevel="error"),G("SW_DEBUG")&&(this.logLevel="debug"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in K||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in K)this[e]=console[e];this._hookLogFunc(((e,t)=>{this.logUploader&&this.logUploader.send(e,t)}))}enableReport(e){this.reportUrl=e,this._hookLogFunc(((e,t)=>{this.reportUrl?(this.logCache.push({levelKey:e,message:`${A()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,i,r,s=5e3){this.reportUrl&&!this.reporter&&(e&&this.logCache.unshift({levelKey:"info",message:e}),this.reporter=new U(this.reportUrl,t,i,r),this.reporter._ws.addEventListener("open",(()=>{this.reportUrl=void 0,this.reporter.sendBatch(this.logCache),setTimeout((()=>{this.reporter.destroy(),this.reporter=null}),s)}),{once:!0}))}_hookLogFunc(e){for(let t in K){const i=this[t];this[t]=r=>{e(t,r),i(r)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in K)K[e]<K[this.logLevel]?this[e]=d:this[e]=console[e]}get isDebugLevel(){return K[this.logLevel]<=2||this.onlineDebug}};let $;const W="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>($||($=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),q=65536;function j(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class Y extends(n()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||Y.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Y.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=m(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void W((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{e.debug=!0,this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var i;!t.address||t.address.endsWith(".local")?(i="Ignoring unsupported ICE candidate.",console.warn(i)):(e.debug=!0,this.destroy(e))}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,W((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,W((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=q),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{e.debug=!0,this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}get isBufferedAmountHigh(){return this._channel.bufferedAmount>q}write(e,t){if(this.destroyed)return t(new Error("cannot write after peer is destroyed"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(e)}this.isBufferedAmountHigh?this._cb=t:t(null)}else this._chunk=e,this._cb=t}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=j(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=j(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((i=>{const r=[];i.forEach((e=>{r.push(t(e))})),e(null,r)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((i=>{if(this.destroyed)return;const r=[];i.result().forEach((e=>{const i={};e.names().forEach((t=>{i[t]=e.stat(t)})),i.id=e.id,i.type=e.type,i.timestamp=e.timestamp,r.push(t(i))})),e(null,r)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,i)=>{if(this.destroyed)return;t&&(i=[]);const r={},s={},n={};let a=!1;i.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(r[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(s[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(n[e.id]=e)}));const o=e=>{a=!0;let t=s[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let i=r[e.remoteCandidateId];i&&(i.ip||i.address)?(this.remoteAddress=i.ip||i.address,this.remotePort=Number(i.port)):i&&i.ipAddress?(this.remoteAddress=i.ipAddress,this.remotePort=Number(i.portNumber)):"string"==typeof e.googRemoteAddress&&(i=e.googRemoteAddress.split(":"),this.remoteAddress=i[0],this.remotePort=Number(i[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(i.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(n[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(n).length&&!Object.keys(s).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect");for(let e of this._pendingData)this.emit("data",e);this._pendingData=[]}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>q||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=a.h.from(t)),this._connected?this.emit("data",t):this._pendingData.length<10&&this._pendingData.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}Y.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Y.channelConfig={};const z=Y;class X{constructor(e,t,i,r,s=0,n={}){this.sn=e,this.segId=t,this.data=i,this.fromPeerId=r,this.level=s,this.ext=n}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var Q=i(365),J=i.n(Q);class Z extends(n()){static get defaultPacketSize(){return u}static get VERSION(){return"8"}constructor(e,t,i,r,s,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=s,this.isInitiator=r,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,i),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=u,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.useBackupSignal=!1,this.gotPeersTS=0,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.incomingSignal=[],this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,i){this.remotePeerId=i,this.channelId=this.isInitiator?`${t}-${i}`:`${i}-${t}`,i&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(e.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=g(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:t,sentSignal:i,signalName:r}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${i} signalName ${r}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:i,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,i,r){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${r} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:i,seg_id:r}))))}addStreamListener(e,t,i){this.streamListeners.push({handler:i,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_initPeerChannel(){const t=new z({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let i=!0;(this.connected||this.notFatalClosed)&&(i=!1);let r=t.message;t.debug&&(r=`${r} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,i,r)})),t.on("signal",(t=>{t.candidate&&!t.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(t),this.sentSignal=!0,this.emit(e.DC_SIGNAL,t))}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.intermediator?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,this.incomingSignal=[],clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:i}=this;if("string"==typeof t){let r;try{r=JSON.parse(t)}catch(e){return void i.error(e)}if(!r)return void i.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(r);let s,n=r.event;switch(s=n!==e.DC_PLAYLIST&&n!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${n}`,i.debug(`datachannel receive ${s} from ${this.remotePeerId}`),n){case e.DC_HAVE:if(this.emit(r.event,r),!r.sn)return;this.config.live||(r.sn<this.startSN&&(this.startSN=r.sn),r.sn>this.endSN&&(this.endSN=r.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=g(),this.timeReceivePiece=performance.now(),this.pieceMsg=r,this._prepareForBinary(r.attachments,r.seg_id,r.sn,r.size),this.emit(r.event,r);break;case e.DC_PIECE_CANCEL:i.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(r.event,r),this.sendMsgPieceAbort("transfer canceled",r.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(r.event,r);break;case e.DC_REQUEST:this._handleRequestMsg(r);break;case e.DC_PIECE_ACK:this._handlePieceAck(r.seg_id,r.size,r.miss);break;case e.DC_STATS:this._handleStats(r);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(r);break;case e.DC_METADATA:this._handleMetadata(r);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,r)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:i.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:i.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(r.event,r.fatal||!1);break;default:this.emit(r.event,r)}}else{if(!t)return void i.error("datachannel on data is undefined!");if(!this.downloading){const r=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return i.warn(r),void this.emit(e.DC_ERROR,!1,r)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,i)=>{this.connected&&"disconnected"===t&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(e.DC_DISCONNECT))}))}sendJson(t){if(!this.remotePeerId)return!1;t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const i=JSON.stringify(t);return i.length>u?(this.logger.error("string to send is too large"),!1):this.send(i,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();t?("string"!=typeof t&&(this.bytesUploaded+=t.byteLength),this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,void this.emit(e.DC_ERROR,!1,t.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){const i=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,i)}return!1}sendMsgHave(t,i,r={}){const s=r.reverse||void 0;delete r.reverse,this.sendJson({event:s?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:i,...r})}sendPieceNotFound(t,i,r={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:i||void 0,sn:t,...r})}sendPeers(t){this.sendJson({event:e.DC_PEERS,peers:t})}sendPeersRequest(){this.sendJson({event:e.DC_GET_PEERS})}sendMsgStats(t,i={}){const r={event:e.DC_STATS,total_conns:t,...i};this.sendJson(r)}sendMsgPlaylist(t,i,r){const s=this.playlistMap.get(t);if(s&&s.seq>=r)return;const n={event:e.DC_PLAYLIST,url:t,data:i,seq:r};this.playlistMap.set(t,{data:i,seq:r}),this.sendJson(n)}sendMsgSignal(t,i,r){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:i,data:r})}sendMsgSignalReject(t,i,r,s=!1){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:i,reason:r,fatal:s})}sendMetaData(t,i,r,s,n=!1){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!J().isMobile(),mobile_net:n,channel:this.channel,version:"2.16.3",sequential:i,peers:r,region:s})}sendPartialBuffer(e,t,i={}){if(!this.sendMsgPiece(e,i))return!1;for(let e=0;e<t.length;e++)this.send(t[e]);return!0}sendMsgPiece(e,t={}){if(!this.uploading)return this.logger.info("not uploading, cancel send buffer"),!1;this.datasToSend=[],this.bytesUploaded=0,e.ext||(e.ext={}),e.ext.from&&t.from&&t.from.length<2500&&(t.from=`${e.ext.from}-${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const i={...e,ext:t};return this.sendJson(i)}sendBuffer(t,i,r,s={}){const n=s.reverse||void 0;if(delete s.reverse,!r)return void this.logger.error("sendBuffer payload is undefined!");let a=r.byteLength,o=0,l=0;a%this.packetSize==0?l=a/this.packetSize:(l=Math.floor(a/this.packetSize)+1,o=a%this.packetSize);let h={event:e.DC_PIECE,attachments:l,seg_id:i,sn:t,level:s.level,size:a,reverse:n};if(delete s.level,!this.sendMsgPiece(h,s))return;const u=function(e,t,i,r){let s=[];if(r){let n;for(let r=0;r<i-1;r++)n=e.slice(r*t,(r+1)*t),s.push(n);n=e.slice(e.byteLength-r,e.byteLength),s.push(n)}else{let r;for(let n=0;n<i;n++)r=e.slice(n*t,(n+1)*t),s.push(r)}return s}(r,this.packetSize,l,o);this._sendBufferArray(u,n),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}requestDataById(t,i,r=!1,s={}){const n={event:e.DC_REQUEST,seg_id:t,sn:i,...s,urgent:r};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${t} in queue`),r?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}requestDataBySN(t,i=!1,r={}){const s={event:e.DC_REQUEST,sn:t,...r,urgent:i};this.downloading?(this.logger.info(`add req ${t} in queue`),i?this.sendReqQueue.unshift(s):this.sendReqQueue.push(s)):this._realRequestData(s)}_sendBufferArray(e,t=!1){const i=t?e.reverse():e;for(let e=0;e<i.length;e++)this.send(i[e])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0,this._loadedBytes=0}shouldWaitForRemain(e){return 0!==this.bufArrSize&&(0!==this.timeReceivePiece&&this.currentLoadSpeed()>=this.minRequiredSpeed(e))}close(t){t||(this.notFatalClosed=!0),this.emit(e.DC_CLOSE,t)}receiveSignal(e,t){if("answer"===e.type){if(this.gotAnswer||this.gotOffer)return;this.gotAnswer=!0}else if("offer"===e.type){if(this.gotOffer||this.gotAnswer)return;this.gotOffer=!0}this.gotSignal=!0,t&&this.incomingSignal.push(t),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:i}=t;i(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(t=!0){this.logger.info(`destroy datachannel ${this.channelId}`),clearTimeout(this.chokeTimer),clearTimeout(this.connTimeout),this._notifyDownloadListenersAbort("upstream peer is closed");let i={event:e.DC_CLOSE,fatal:t};this.sendJson(i),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:i,reverse:r}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let s=r?this.remainAttachments+1:i-this.remainAttachments;const n=0===this.remainAttachments;if(this.emit(e.DC_PIECE_DATA,this.bufSN,this.segId,t,s,n,this.pieceMsg),this.streamListeners.length>0)for(let e of this.streamListeners){const{handler:i}=e;i(this.bufSN,this.segId,!1,t,n)}if(n){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:e.DC_PIECE_ACK,seg_id:this.segId,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(r)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:i,seq:r}=e;this.playlistMap.set(t,{data:i,seq:r})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const i=this.playlistMap.get(e);return i.seq<=t||i.seq>t+2?null:i}_handleMetadata(t){const{logger:i}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,i.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const r=t.channel;if(this.channel!==r){const t=`peer channel ${r} not matched!`;return i.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){i.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:r}=this.config;if(r&&t.token!==r)return void this.emit(e.DC_ERROR,!0,`super peer token ${t.token} not matched!`)}t.region&&(this.region=t.region);switch(t.platform){case e.DC_PLAT_ANDROID:this.platform=e.DC_PLAT_ANDROID;break;case e.DC_PLAT_IOS:this.platform=e.DC_PLAT_IOS;break;case e.DC_PLAT_WEB:this.platform=e.DC_PLAT_WEB}if(this.mobile=t.mobile||!1,this.mobileNet=t.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===e.DC_PLAT_WEB||!1,this.sequential=t.sequential,i.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,i.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(e.DC_METADATA,t),t.field&&!this.config.live&&t.sequential){const{field:e}=t;if(Array.isArray(e))this._handleField(e);else for(let t in e)this._handleField(e[t])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=g();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPos=e.pos)}_handleRequestMsg(t){if(this.dataExchangeTs=g(),this.uploading)return this.logger.warn(`${this.remotePeerId} is uploading when receive request`),void this.sendPieceNotFound(t.sn,t.seg_id,{level:t.level});this.uploading=!0,this.emit(e.DC_REQUEST,t)}_handlePieceAck(t,i,r){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(i/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),r>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${r}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:i})}_prepareForBinary(e,t,i,r){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=i,this.expectedSize=r}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let i=a.h.concat(this.bufArr);const r=i.byteLength;if(r===this.expectedSize){let t=i.buffer;const r=new X(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,r,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${r}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,i=performance.now()-this.timeSendRequest;if((e||!(i<1e3))&&(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>=3&&!this.choked)){this.choked=!0;const e=30*this.miss;e<=150?(t.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,t.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*e)):t.warn(`datachannel ${this.channelId} is choked permanently`)}}get bufArrSize(){return this.downloading?this.pieceMsg.attachments-this.remainAttachments:0}loadtimeout(){const{logger:e,pieceMsg:t}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded`),this.checkIfNeedChoke(),!0}sendMsgPieceAbort(t,i,r=!1){const s=this.datasToSend.length;if(!r&&!this.uploading&&0===s)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(i,this.bytesUploaded,0),this.bytesUploaded=0;const n={event:e.DC_PIECE_ABORT,reason:`${t}, remains ${s}`};return this.sendJson(n)}loadedBytes(){return this._loadedBytes}currentLoadSpeed(){return 0===this.timeReceivePiece?0:this.loadedBytes()/(performance.now()-this.timeReceivePiece)}minRequiredSpeed(e){return(this.pieceMsg.size-this.loadedBytes())/e}}const ee=Z,te={DPlayer:"dplayer",CBPlayer:"cbplayer",jwplayer:"jwplayer",videojs:"videojs",Clappr:"clappr",ckplayer:"ckplayer",MediaElementPlayer:"mediaelement",MediaElement:"mediaelement",TcPlayer:"tcplayer",flowplayer:"flowplayer",Chimee:"chimee",ChimeePlayer:"chimee",HlsJsPlayer:"xgplayer",fluidPlayer:"fluidplayer",OpenPlayer:"openplayer",Plyr:"plyr",Playerjs:"playerjs",Aliplayer:"aliplayer",shaka:"shakaplayer",RadiantMP:"rmp",bitmovin:"bitmovin"};const ie={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class re extends(n()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===c("_p2p")),e.tag&&e.tag.length>20)throw new Error("Tag is too long");if(e.appName&&e.appName.length>30)throw new Error("appName is too long");if(e.appId&&e.appId.length>30)throw new Error("appId is too long");if(e.token&&e.token.length>20)throw new Error("Token is too long");this.segmentLoadCount=0,this.rangeTested=!1,this.trackerTried=!1,this.playerName=function(){let e;for(let t in te)if(self[t]){e=te[t];break}return e}()}resumeTracker(){this.tracker&&!this.trackerTried&&!this.tracker.connected&&this.config.p2pEnabled&&(this.tracker.resumeP2P(),this.trackerTried=!0)}onTrackerResume(e){e.report_url&&this.logger.enableReport(e.report_url)}startRangeRequestTimer(){const{config:e,logger:t}=this;let i=0;const r=()=>{this.curTsUri&&function(e,t,i,r=2e3,s=!1){const n=new XMLHttpRequest;let a=e;return s&&(a=f(e,h,!0)),t=t||"bytes=0-0",new Promise(((s,o)=>{n.open("GET",a,!0),n.responseType="arraybuffer",n.timeout=r,n.onreadystatechange=e=>{if(4===n.readyState){const e=n.status;206===e?s(n.response):o(`status ${e} url ${a} range ${t}`)}},n.onerror=e=>{o("request error")},n.ontimeout=e=>{o("timeout")},n.setRequestHeader("Range",t),i&&i(n,e),n.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((s=>{e.httpRangeSupported=!1,t&&t.warn(s),i<3&&(this.rangeRequestTimer=setTimeout(r,6e4)),i++})).finally((()=>{t&&t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(r,0)}initLogger(){const{config:e}=this;e.showSlogan&&console.log(`%cLet the browsers become your unlimitedly scalable CDN!\n%c${self.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldA==")}`,"color: dodgerblue; padding:20px 0; font-size: x-large","font-size: medium; padding-bottom:15px");const t=new V(e.logLevel);return e.logger=this.logger=t,t}getExtraForStats(){return{}}getExtraForPeersRequest(){const e={};return e.num_want=this._getNumWant(),e}_getNumWant(){const{tracker:e}=this;if(!e.scheduler)return;const t=e.scheduler.peersNum;return t>0&&e.maxConnsActive-t>0?e.maxConnsActive-t:void 0}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return I(t)?(i,r)=>`${e}-${t(i,r)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,i=`wss://${self.atob(function(e){let t="c2lnbmFsY2xvdWQuc3dhcm1jbG91ZC5vcmc=";switch(e){case"hk":t="c2lnbmFsLnN3YXJtY2xvdWQub3Jn";break;case"us":t="b3BlbnNpZ25hbC5zd2FybWNsb3VkLm9yZw==";break;case"cn":t="Z3ouc3dhcm1jbG91ZC5uZXQ="}return t}(t.trackerZone))}`;t.signalConfig&&(t.wsSignalerAddr=t.signalConfig);const{wsSignalerAddr:r}=t;if(r){let s;"object"==typeof r?(r.main||(r.main=i),s=r.main):"string"==typeof r&&(s=r,t.wsSignalerAddr={main:s}),s===i&&(s=void 0),s&&!t.wsSignalerAddr.backup&&(e=l().parseURL(s).netLoc.substring(2))}else t.wsSignalerAddr={main:i,byDefault:!0};return e}get commonBrowserInfo(){const e=J().getPlatform(),t=J().getNetType()||"wifi";this.netType=t;const{main:i,backup:r,byDefault:s}=this.config.wsSignalerAddr||{};return{signal:i,custom_signal:!s||void 0,signal2:r,device:e,netType:t,player:this.playerName}}get isMobileNet(){return"wifi"!==this.netType&&"ethernet"!==this.netType}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",i=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,i)};e?self.removeEventListener(t,i):self.addEventListener(t,i)}destroy(){clearTimeout(this.rangeRequestTimer),this.disableP2P(!0),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return re.version}static isSupported(){const e=m();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,i){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${i}`);let r=4;return t<=2?r=1.5:t<=3?r=2:t<=4?r=2.5:t<=5?r=3:t<=6&&(r=3.5),r}emitEvent(e,...t){this.emit(e,...t);const i=ie[e];i&&I(this.config[i])&&this.config[i](...t)}}re.version="2.16.3",re.protocolVersion=ee.VERSION;const se=re;function ne(){if(!function(){if("object"==typeof self)return self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}())return!1;const e=self.SourceBuffer||self.WebKitSourceBuffer;return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function ae(e,t){let i;if(e&&("string"==typeof e?(i=document.querySelector(e),oe(i)||(i=function(e){const t=document.getElementById(e);if(oe(t))return t;if(!t)return null;const i=t.getElementsByTagName("*");for(let e=0;e<i.length;e++)if(oe(i[e]))return i[e];return null}(e))):e instanceof HTMLMediaElement&&(i=e)),!i){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?i=e[0]:(t&&(i=e.find((e=>e.src===t))),i||(i=e.find((e=>e.currentTime>0))))}return i}function oe(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function le(e,t,i,r=0,s=0){const n=u;let a=r,o=s||i-1;const l=Math.floor(i/n),h=i%n>0?l+1:l;if(e>=0&&(a+=(e+1)*n),t>=0&&t<h){o-=i%n+(h-t-1)*n}return{rangeStart:a,rangeEnd:o+1}}function he(e,t){return`${e}-${t}`}function ue(e,t,i,r){let s=i.split("?")[0];return s.startsWith("http")&&(s=s.split("://")[1]),r?`${s}|${r}`:`${s}`}function de(e,t){return"number"!=typeof t&&(t=Number(t)),`${t}-${e}`}let ce={wsMaxRetries:10,p2pEnabled:!0,signalCompact:!0,wifiOnly:!1,memoryCacheLimit:{pc:419430400,mobile:104857600},dcDownloadTimeout:25,logLevel:"error",webRTCConfig:{},token:void 0,appName:void 0,appId:void 0,prefetchNum:3,showSlogan:!1,trickleICE:!0,announceLocation:"eu",trackerZone:void 0,geoIpPreflight:!0,ICEPreflight:!0,useDiskCache:!0,startFromSegmentOffset:3,getStats:function(e,t,i){},getPeerId:function(e){},getPeersInfo:function(e){}};const fe={...ce,httpLoadTime:0,sharePlaylist:!1,useHttpRange:!0,hlsjsInstance:null,proxyOnly:!1,proxyFirst:!1,p2pBlackList:["vtt","webvtt","key"],live:!0,swFile:"./sw.js",swScope:"./",swAutoRegister:!0,mediaElem:void 0,httpStreamEnabled:!0,diskCacheLimit:{pc:1572864e3,mobile:1048576e3},strictSegmentId:!1,prefetchOnly:!1},ge=1e3;function pe(e){const t=new Promise(((t,i)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>i(e.error)})),i=(r=ge,s="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(s)}),r))));var r,s;return Promise.race([t,i])}const ve={};async function me(e,t,i=!0){const r=ve[e]||{};r.promise||(r.promise=new Promise((e=>r.resolve=e)),ve[e]=r,Ee(e,t,r.resolve,i));const s=await r.promise;return delete r.promise,s}const ye={};async function Ee(e,t,i,r){if(!ye[e]){const r=indexedDB.open(e);return r.onupgradeneeded=()=>{const e=r.result;t.forEach((t=>{e.createObjectStore(t)}))},void i(ye[e]=await pe(r))}if(r)try{t.forEach((t=>{ye[e].transaction(t)})),i(ye[e])}catch(s){console.error(`Could not open a transaction on "${e}" due to ${s.name} (${s.message}). Trying to reopen the connection...`),delete ye[e],Ee(e,t,i,r)}else i(ye[e])}let Se;function Te(){return Se||(Se=createStore("keyval-store","keyval")),Se}function _e(e,t=Te()){return t("readonly",(t=>pe(t.get(e))))}function Le(e,t,i=Te()){return i("readwrite",(i=>(i.put(t,e),pe(i.transaction))))}function be(e,t=Te()){return t("readwrite",(t=>(t.delete(e),pe(t.transaction))))}function Ae(e=Te()){return e("readwrite",(e=>(e.clear(),pe(e.transaction))))}function Ie(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},pe(e.transaction)}const Re="size";class Pe extends(n()){constructor(e,t){super(),this.name="SegmentStore",this.logger=t.logger,this.logger.info(`use ${this.name}`),this.engine=e,this.channel=e.channel;const i=e.browserInfo.device;this.isPC=i===J().device.PC_WEB||i===J().device.PC_NATIVE,this.maxBufSize=this.isPC?t.diskCacheLimit.pc:t.diskCacheLimit.mobile,this.overflowed=!1,this.countErrors=0,this.isCleared=!0,this.destroyed=!1}async setupStore(){if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate(),t=Math.floor(e.quota-e.usage);t<this.maxBufSize&&(this.maxBufSize=t-104857600)}return new Promise((async(e,t)=>{if(this.isPC&&this.maxBufSize<419430400||!this.isPC&&this.maxBufSize<104857600)return void t("disk storage not enough");const i=this.stores;let r;try{r=function(e,t){let i=me(e,t);return t.map((r=>(s,n)=>i.then((a=>{try{const e=a.transaction(r,s).objectStore(r);return n(e)}catch(a){i=me(e,t),i.then((e=>n(e.transaction(r,s).objectStore(r))))}}))))}(this.channel,i)}catch(e){return void t(e)}this._createStores(r),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return Le(Re,0,this.metaStore)}currBufSize(){return new Promise((async(t,i)=>{try{const r=await _e(Re,this.metaStore);if(isNaN(r))return this.engine.emit(e.BM_FATAL_ERROR),void i("size is NaN");t(r)}catch(e){i(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:i}=this;if(_(t.data))return new Promise((r=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),this.countErrors=0,r()})).catch((e=>{this._handleFataError(),e&&(i.warn(`putSeg ${e}`),("QuotaExceededError"===e.name||e.inner&&"QuotaExceededError"===e.inner.name)&&this.currBufSize().then((e=>{this._trimDisk(e,!0)})).catch((e=>{this.logger.error(`trimDisk ${e}`)}))),r()}))}));i.error(`putSeg ${t.segId} is not buffer`)}_handleFataError(){this.countErrors++,this.countErrors>=3&&(this.engine.emit(e.BM_FATAL_ERROR),this.countErrors=0)}_decreaseBufSize(e){this.currBufSize().then((t=>{t&&Le(Re,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(e){this.destroyed||this.currBufSize().then((t=>{Le(Re,t+e,this.metaStore),this._trimDisk(t+e)})).catch((e=>{this.logger.warn(`increaseBufSize ${e}`)}))}clear(e=!1){if(!this.isCleared){this.logger.warn("clear segment store");try{this._clearDisk(e)}catch(e){}this.isCleared=!0}}_clearDisk(e){Ae(this.segmentsStore),e?this._initMetaStore():Ae(this.metaStore),this.overflowed=!1}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}static toSegment(e){const t=new X(e.sn,e.segId,e.data,e.fromPeerId,e.level,e.ext);return t.from=e.from,t}}const ke=Pe;const De=class extends ke{constructor(e,t){super(e,t),this.loadingSN=-1,this.stores=["segments","id2Sn","metadata"]}_createStores(e){this.segmentsStore=e[0],this.id2SnStore=e[1],this.metaStore=e[2]}async hasSegOfId(e){if(!e)return Promise.resolve(!1);let t;try{t=await _e(e,this.id2SnStore)}catch(e){return Promise.resolve(!1)}return new Promise((i=>{void 0!==t?_e(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?i(!0):i(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),i(!1)})):i(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let i;try{i=await _e(e,this.id2SnStore)}catch(e){return null}return new Promise((r=>{void 0!==i?_e(i,this.segmentsStore).then((i=>{if(this.countErrors=0,i&&i.length>0){const s=i.find((t=>t.segId===e));if(!s)return void r(null);if(!_(s.data))return t.error(`getSegById ${s.sn} is not buffer`),void r(null);r(ke.toSegment(s))}else r(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),r(null)})):r(null)}))}getSegIdBySN(e){return new Promise((t=>{_e(e,this.segmentsStore).then((e=>{e&&e.length>0?t(e[0].segId):t(null)})).catch((e=>{this.logger.warn(`getSegIdBySN ${e}`),t(null)}))}))}_addSeg(e){const{segId:t,sn:i,size:r}=e;return Le(t,i,this.id2SnStore),new Promise(((s,n)=>{_e(i,this.segmentsStore).then((async a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(await this._segmentToCache(e)),Le(i,a,this.segmentsStore).then((()=>{this._increaseBufSize(r),s(e)})).catch((e=>{n(e)}))):s(e):Le(i,[await this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(r),s(e)})).catch((e=>{n(e)}))})).catch((e=>{n(e)}))}))}async _trimDisk(t,i=!1){if(this.isCleared||this.destroyed)return;let r=this.maxBufSize;const{logger:s}=this;i&&(r=t-104857600,r<0&&(r=0)),t<r||(s.warn(`_trimDisk currentSize ${t} upBound ${r}`),function(e=Te()){return e("readonly",(e=>{if(e.getAllKeys)return pe(e.getAllKeys());const t=[];return Ie(e,(e=>t.push(e.key))).then((()=>t))}))}(this.segmentsStore).then((async i=>{const n=i.sort(((e,t)=>e-t));let a=0;do{if(a++>10){s.warn("too much loops in SegmentStore");break}const i=n.shift();if(void 0===i){s.warn("lastSN not found");continue}if(i>=this.loadingSN){s.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const r=n[0],o=await _e(i,this.segmentsStore);if(!o){s.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),be(i,this.segmentsStore).then((()=>{this._decreaseBufSize(parseInt(l))})),o.forEach((t=>{be(t.segId,this.id2SnStore),s.info(`pop seg ${t.segId} size ${t.data.byteLength}`),this.emit(e.BM_LOST,{sn:i,segId:t.segId,next:r,level:t.level})})),t-=l,s.info(`pop sn ${i} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=r)})))}async _segmentToCache(e){const{ext:t={}}=e;let i=t.hash;i||(i=await w(e.data));const r={data:e.data,level:e.level,segId:e.segId,sn:e.sn,fromPeerId:e.fromPeerId,ext:{}};return i&&(r.ext.hash=i),r}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}Ae(this.id2SnStore).catch((e=>{}))}};class we extends(n()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const i=e.browserInfo.device;if(this.maxBufSize=i===J().device.PC_WEB||i===J().device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,this.isLive=t.live,this.isLive)this.maxBufSize=47185920;else{if(0===this.maxBufSize)throw new Error("cannot use SegmentCache");const e=function(){const{memory:e}=performance;return e?e.jsHeapSizeLimit-e.usedJSHeapSize:-1}();e>=0&&e<this.maxBufSize&&(this.maxBufSize=e-31457280)}this._segPool=new Map,this._currBufSize=0,this.overflowed=!1,this.isCleared=!0,this.destroyed=!1}get currBufSize(){return this._currBufSize}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}async putSeg(e){this.destroyed||(this.isCleared=!1,this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),_(e.data)?this._addSeg(e):this.logger.error(`putSeg ${e.segId} is not buffer`))}clear(){this.isCleared||(this.logger.warn("clear segment cache"),this._segPool.clear(),this._currBufSize=0,this.isCleared=!0,this.overflowed=!1)}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const Ce=we;const Me=class extends Ce{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,i)=>{const r=this.id2Sn.get(e);this._segPool.has(r)?t(this._segPool.get(r).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((i,r)=>{if(!this._segPool.has(t))return void i(null);const s=this._segPool.get(t).find((t=>t.segId===e));i(s||null)}))}getSegIdBySN(e){return new Promise(((t,i)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}async _addSeg(t){const{logger:i}=this,{segId:r,sn:s,size:n,ext:a={}}=t;if(this.id2Sn.set(r,s),a.hash||(a.hash=await w(t.data),t.ext=a),this._segPool.has(s)){this._segPool.get(s).push(t)}else this._segPool.set(s,[t]);this._currBufSize+=parseInt(n);const o=this._segPool.size;if(this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t),this._currBufSize<this.maxBufSize||o<=5)return;let l=Array.from(this._segPool.keys());this.isLive||(l=l.sort(((e,t)=>e-t)));let h=0;do{if(h++>10){i.error("too much loops in SegmentCache");break}const t=l.shift();if(void 0===t){i.error("lastSN not found");continue}const r=l[0],s=this._segPool.get(t);if(!s){i.error("lastSeg not found");continue}let n=0;s.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(t),s.forEach((i=>{this.id2Sn.delete(i.segId),this.emit(e.BM_LOST,{sn:t,segId:i.segId,next:r,level:i.level})})),i.info(`pop sn ${t} size ${n} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>5)}clear(){super.clear(),this.id2Sn.clear()}};var Oe=i(832),xe=i.n(Oe);function Fe(e,t){for(const i in t)Object.defineProperty(e,i,{value:t[i],enumerable:!0,configurable:!0});return e}const Ne=function(e,t,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof t&&(i=t,t=void 0),null!=t&&(i.code=t);try{return Fe(e,i)}catch(t){i.message=e.message,i.stack=e.stack;const r=function(){};return r.prototype=Object.create(Object.getPrototypeOf(e)),Fe(new r,i)}};class Be{constructor(){this.p2p=0,this.share=0,this.http=0}recordP2p(e){this.p2p+=e}recordShare(e){this.share+=e}recordHttp(e){this.http+=e}resetTraffic(){this.p2p=0,this.share=0,this.http=0}get healthRatio(){if(0===this.http)return 1e3;let e=Math.round((this.p2p+this.share)/this.http*100);return e<=0&&(e=1),e}}const Ue="SW_GEOIP_KEY",Ge=2592e5,He=432e5,Ke="TRACKER_EXPT",Ve="IPAPI_ERROR",$e="uY2R",We="LmNv",qe="uYnll",je="bQ==",Ye="Z3o",ze=Symbol("httpDownloaded"),Xe=Symbol("p2pDownloaded"),Qe=Symbol("p2pUploaded");class Je extends(n()){constructor(e,t,i,r,s){let n;super(),this.config=e.config;let a=this.config.announceLocation;switch(this.config.trackerZone&&(a=this.config.trackerZone),a){case"hk":n="aGsubWVzaGlmeS5jbG91ZA==";break;case"us":n="dXMubWVzaGlmeS5jbG91ZA==";break;case"cn":n=Ye+$e+qe+We+je;break;default:n="ZXUubWVzaGlmeS5jbG91ZA=="}this.engine=e,this.key=t||void 0,Array.isArray(r)&&(r=r[Math.floor(Math.random()*r.length)]),this.baseUrl=r||`https://${self.atob(n)}/v1`,this.channelId=self.btoa(i),this.timestamp=g(),this.health=new Be;const o=l().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,""),function(e,t){function i(e,t,i,r,s){return h(i-219,s)}var r,s,n=e();function a(e,t,i,r,s){return h(s- -994,e)}function o(e,t,i,r,s){return h(r-233,t)}function l(e,t,i,r,s){return h(s-305,i)}for(;;)try{if(156690===-parseInt(o(0,246,0,247))/1*(-parseInt(o(0,243,0,248))/2)+-parseInt(o(0,238,0,245))/3+parseInt(a(-1e3,0,0,0,-989))/4*(-parseInt(i(0,0,225,0,216))/5)+-parseInt((r=-180,s=-173,h(s- -181,r)))/6*(parseInt(l(0,0,324,0,324))/7)+-parseInt(a(-991,0,0,0,-990))/8*(parseInt(l(0,0,313,0,307))/9)+-parseInt(l(0,0,310,0,305))/10+-parseInt(a(-968,0,0,0,-974))/11*(-parseInt(i(0,0,226,0,216))/12))break;n.push(n.shift())}catch(e){n.push(n.shift())}}(d);function h(e,t){var i=d();return(h=function(e,t){return i[e-=0]})(e,t)}const u=function(e,t,i,r,s,n){let a=location.hostname;a===h(-922- -923,-915)&&n&&(a=n+"."+a);return 13,xe()(a+"2.16.3"+i+r+s,e).substr(0,8)}(this.timestamp,0,this.announce,this.channelId,s.type,this.key);function d(){var e=["13055AgbnUs","2739cfXSxI","CxYEuy093515".split("").reverse().join(""),"localhost","OCXDId9".split("").reverse().join(""),"yek".split("").reverse().join(""),"QyapiZ8635101".split("").reverse().join(""),"scRrUF02".split("").reverse().join(""),"bNcslL58187".split("").reverse().join(""),"QEbZrW65772".split("").reverse().join(""),"12gYmKGR","emantsoh".split("").reverse().join(""),"dIlennahc".split("").reverse().join(""),"pmatsemit".split("").reverse().join(""),"676614MZdLCs","type","hpNRbU1".split("").reverse().join(""),"133332xoUKrS","announce","lmia","substr"];return(d=function(){return e})()}h(895-878,886),this.native=!(!s.bundle||!window.electron&&!navigator.userAgent.toLowerCase().includes("electron")),this.announceInfo={...s,channel:this.channelId,ts:this.timestamp,version:"2.16.3",v:u,announce:this.announce,k:it(this.key)},this.announceURL=`${this.baseUrl}/channel`,this.reportFails=0,this.statsRequesting=!1,this.forbidden=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[ze]=0,this[Xe]=0,this[Qe]=0,this.speed=0,this.offline=!1,this.errsBufStalled=0,this.mediaRequests=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,i)=>{if((e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return!(!e.duration||!e.startTime)&&Date.now()-e.startTime<e.duration}catch(e){return!1}})(Ue)){const i=G(Ue);e.info("found local geo data"),t(i)}else fetch(self.atob("aHR0cHM6Ly9wcm8uaXAtYXBpLmNvbS9qc29uP2ZpZWxkcz0yMTgxODI2JmtleT1YT3BpYW5zUmdZeEdUaG8=")).then((e=>e.json())).then((e=>{if("success"!==e.status){const t=new Error(`preflight status ${e.status}`);throw Ne(t,Ve)}{const i=e.mobile?He:Ge;H(Ue,e,i),t(e)}})).catch((e=>{i(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(Ne(new Error("request timeout"),Ve))}),600)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(t.code!==Ke){const t=G(Ue);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:i,isp:r,as:s,mobile:n,countryCode:a,continentCode:o}=e;n&&(this.announceInfo.netType="cellular");const l=s.split(" ")[0].substr(2);this.announceInfo={...this.announceInfo,lat:t,lon:i,isp:r,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,i)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>{if(!e.ok){const t=e.status>=500&&e.status<600;throw Ne(new Error(`server response code is ${e.status}`),Ke,{retry:t})}return e.json()})).then((e=>{if(!this.engine)throw Ne(new Error("runtime error"),Ke,{retry:!1});const i=e.data;if(i.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:i}=e.data;throw Ne(new Error(i),Ke,{retry:t>=5e3})}if(i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),i.min_conns||(i.min_conns=8),(!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval&&i.peers){if(this.peerId=this.id=i.id,i.report_interval<20&&(i.report_interval=20),this.btStats(i.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,!this.announceInfo.asn&&i.asn){const{country:e,asn:t,mobile:r,isp:s,lat:n,lon:a}=i;this.announceInfo={...this.announceInfo,country:e,asn:t},H(Ue,{countryCode:e,as:`AS${t}`,mobile:r,isp:s,lat:n,lon:a,status:"success"},r?He:Ge)}t(i)}else this.engine&&(this.engine.p2pEnabled=!1)})).catch((t=>{e.error(`btAnnounce error ${t}`);const r=t.code||Ke,s=!t.code||t.retry;i(Ne(t,r,{retry:s}))}))}))}btStats(e=10){this.heartbeater=setInterval((()=>{this.postStats()}),1e3*e)}postStatsWithBeacon(){if(this.offline)return;this.offline=!0;let e={off:!0};this.statsRequesting||(e={...e,...this._makeStatsBody()}),this.statsURL&&navigator.sendBeacon&&navigator.sendBeacon(this.statsURL,JSON.stringify(e))}postStats(){const{logger:t}=this.engine;this.statsRequesting=!0,fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.statsRequesting=!1,this.reportFails=0,e.text()))).then((i=>{let r;if(r=i?JSON.parse(i):{ret:0,data:{}},-1===r.ret)clearInterval(this.heartbeater),t.error(`${r.data.msg} code ${r.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:i=0,failConns:r=0,rebuffers:s=0,requests:n=0,errsInternalExpt:a=0}=this.lastStats||{};this[ze]>=e&&(this[ze]-=e),this[Xe]>=t&&(this[Xe]-=t),this[Qe]>=i&&(this[Qe]-=i),this.failConns>=r&&(this.failConns-=r),this.errsBufStalled>=s&&(this.errsBufStalled-=s),this.mediaRequests>=n&&(this.mediaRequests-=n),this.errsInternalExpt>=a&&(this.errsInternalExpt-=a),this.exptMsg&&(this.exptMsg=void 0)}})).catch((e=>{t.error(`btStats error ${e}`),this.statsRequesting=!1,this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e,t=!1){const{logger:i}=this.engine,{asn:r,country:s}=this.announceInfo;let n={exclusions:e,asn:r,country:s,ratio:this.health.healthRatio,urgent:t||void 0},a={};return this.engine.getExtraForPeersRequest&&(a=this.engine.getExtraForPeersRequest()),n=Object.assign({},n,a),new Promise(((e,t)=>{this.reportFails>=3?t(new Error("reportFails >= 3")):fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(n)}).then((e=>e.json())).then((i=>{-1===i.ret?t(i.data.msg):e(i.data)})).catch((e=>{i.error(`btGetPeers error ${e}`),t(e)})).finally((()=>{this.health.resetTraffic()}))}))}increFailConns(){this.failConns++}increRebuffers(){this.engine.emitEvent("bufferStalled"),this.errsBufStalled++}increMediaRequests(){this.mediaRequests++,this.engine.emit(e.MEDIA_REBUFFER,this.errsBufStalled>=2)}reportFlow(e){const t=Math.round(e/1024);this.engine.emitEvent("httpDownloaded",t),this[ze]+=t,this.totalHTTPDownloaded+=t,this.health.recordHttp(t),this._emitStats()}reportDCTraffic(e,t){const i=Math.round(e/1024);this[Xe]+=i,this.totalP2PDownloaded+=i,this.health.recordP2p(i),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",i,this.speed),this._emitStats()}reportUploaded(e=0){const t=Math.round(e/1024);this.engine.emitEvent("p2pUploaded",t),this.totalP2PUploaded+=t,this.health.recordShare(t),this[Qe]+=t,this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),this.removeAllListeners(),clearInterval(this.heartbeater)}_emitStats(){const{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:i}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:i,p2pDownloadSpeed:this.speed});const{getStats:r}=this.config;I(r)&&r(t,i,e,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let i={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,rebuffers:this.errsBufStalled||void 0,requests:this.mediaRequests||void 0,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[ze])||0,p2p:Math.round(this[Xe])||0,share:Math.round(this[Qe])||0,asn:e,country:t},r={};this.engine.getExtraForStats&&(r=this.engine.getExtraForStats()),i=Object.assign({},i,r),this.lastStats=JSON.parse(JSON.stringify(i)),Object.keys(i).forEach((e=>{0===i[e]&&delete i[e]}));const{logger:s}=this.engine;return s.isDebugLevel&&s.info(`report ${JSON.stringify(i)}`),this.exptMsg&&(i.exptMsg="2.16.3 "+this.exptMsg),i}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":it(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const Ze=Je;function et(e,t){const i=tt();return(et=function(e,t){return i[e-=0]})(e,t)}function tt(){const e=["CsLPpZ8932212".split("").reverse().join(""),"htgnel".split("").reverse().join(""),"UZpUzY5895021".split("").reverse().join(""),"yJZuxA9452121".split("").reverse().join(""),"tAedoCrahc".split("").reverse().join(""),"btoa","q#<K@C".split("").reverse().join(""),"1164HyWkyu","4154136SJSwNe","IITNvu6344771".split("").reverse().join(""),"edoCrahCmorf".split("").reverse().join(""),"554Biqadw","oShtCc7412072".split("").reverse().join("")];return(tt=function(){return e})()}function it(e){if(!e)return;const t=et(-822- -830,-826);let i="".split("").reverse().join("");const r=t.length;for(let s=0;s<e.length;s++){const n=e.charCodeAt(s)^t.charCodeAt(s%r);i+=String.fromCharCode(n)}return self.btoa(i)}!function(e,t){const i=e();function r(e,t,i,r,s){return et(e-92,s)}function s(e,t,i,r,s){return et(s-930,i)}for(;;)try{if(377468===parseInt(s(0,0,944,0,939))/1*(parseInt(s(0,0,936,0,930))/2)+parseInt(s(0,0,929,0,935))/3+parseInt(s(0,0,939,0,941))/4+-parseInt((n=-995,a=-995,et(n- -999,a)))/5+parseInt(r(94,0,0,0,91))/6+-parseInt(r(93,0,0,0,92))/7+-parseInt(r(102,0,0,0,107))/8)break;i.push(i.shift())}catch(e){i.push(i.shift())}var n,a}(tt);class rt extends(n()){constructor(e,t){super(),this.logger=e,t.startsWith("wss")?this.addr=t.replace("wss","https"):t.startsWith("ws")&&(this.addr=t.replace("ws","http")),this.connected=!1,this.retryCount=0,this.closed=!1,this.msgQueue=[],this.posting=!1,this.pollingTs=0}start(){this.closed=!1,this._hello((()=>{this._longPolling()}))}_hello(e){fetch(this.addr+"&hello",{method:"POST"}).then((e=>{if(!e.ok)throw new Error("hello response was not ok");return e.json()})).then((t=>{this.connected=!0,e(),this.onopen&&this.onopen(t.ver)})).catch((e=>{this.closed=!0,this.onerror&&this.onerror(e)}))}send(e){this.msgQueue.push(e),this.posting||this._realSend([...this.msgQueue])}_realSend(e){0!==e.length&&(this.posting=!0,this.msgQueue=[],fetch(this.addr,{method:"POST",body:JSON.stringify(e)}).then((()=>{this.posting=!1,this.msgQueue.length>0&&this._realSend([...this.msgQueue])})).catch((e=>{this.logger.error(e),this.posting=!1})))}close(){this.connected&&(this.closed=!0,this.connected=!1,this.abortController&&(this.abortController.abort(),this.abortController=null),this.onclose&&this.onclose())}destroy(){this.close(),this.removeAllListeners()}_longPolling(){if(this.closed)return;this.pollingTs=g(),this.abortController=new AbortController;const e=this.abortController.signal;fetch(this.addr,{signal:e}).then((e=>{if(!e.ok)throw new Error("polling response was not ok");return e.text()})).then((async e=>{e&&this.onmessage&&this.onmessage(JSON.parse(e)),this.retryCount=0;const t=g()-this.pollingTs;JSON.stringify(e)===JSON.stringify(this.lastData)&&t<10&&(this.logger.warn(`wait ${10-t}s for next polling`),await v(1e3*(10-t))),this.lastData=e,this._longPolling()})).catch((e=>{this.connected&&(this.retryCount<=3?(this.retryCount++,this._longPolling()):(this.connected=!1,this.onerror&&this.onerror(e)))}))}}const st=class{constructor(e,t,i,r="main"){this.logger=e,this.config=t,this.wsAddr=i,this.serverVersion=0,this.pingInterval=95e3,this.name=r,this.normalClosed=!1,this.lastSendTs=performance.now(),this.pollingClient=new rt(e,i);try{this._ws=this._init()}catch(t){e.error(t),this._startPolling()}}get batchSupported(){return this.serverVersion>=50}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:p(15e3,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20,connectionTimeout:7e3};let t=new N(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.normalClosed=!1,this.pollingClient.connected?this.pollingClient.close():this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{this.lastSendTs=performance.now();let i=JSON.stringify(e);t.push(i)},t.addEventListener("message",(e=>{let t=e.data;const i=JSON.parse(t),r=i.action;if("pong"!==r){if("ver"!==r)return"close"===r?(this.logger.warn(`server close signal ${this.name} reason ${i.reason}`),void this.close()):void("signals"!==r?this.onmessage&&this.onmessage(i,this.name):this._onSignalBatch(i.data));this.serverVersion=i.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),e.code>=5e3||e.code<4e3?(this.onclose&&this.onclose(),this._stopPing()):this.close()})),t.addEventListener("error",(e=>{this._stopPing(),this.onerror&&this.onerror(e),this._startPolling()})),t}forcePolling(){this.pollingClient.connected||(this.close(),this.pollingClient=new rt(this.logger,this.wsAddr),this._startPolling())}_startPolling(){this.pollingClient.connected||(this.logger.info(`${this.name} start polling`),this.pollingClient.start(),this._setupPolling(this.pollingClient))}sendDebug(e,t,i){this._send({action:"debug",details:t,ping:i||void 0,to:e})}sendSignal(e,t){const i={action:"signal",to:e,data:t};this._send(i)}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let i of t)this.sendSignal(e,i)}sendReject(e,t,i){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const r={action:"reject",to:e,reason:t,fatal:i};this._send(r)}_send(e){this.pollingClient.connected?this.pollingClient.send(e):this._ws&&this._ws.send(e)}_startPing(e){this.connected&&(this.pingTimer=setTimeout((()=>{const e=95e3-(performance.now()-this.lastSendTs);if(e>=0)return this._startPing(e);const t={action:"ping"};this._ws&&this._ws.push(JSON.stringify(t)),this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),15e3),this._startPing(this.pingInterval)}),e))}_stopPing(){clearTimeout(this.pingTimer),clearTimeout(this.pongTimer)}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3)})(),this.pollingClient.close(),this.normalClosed=!0}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.pollingClient.destroy()}get connected(){return!!this.pollingClient.connected||this._connected}get _connected(){return!!this._ws&&this._ws.readyState===N.OPEN}_setupPolling(e){e.onopen=e=>{e&&(this.serverVersion=e),this.logger.info(`${this.name} polling opened`),this.onopen&&this.onopen()},e.onerror=e=>{this._connected||this.onerror&&this.onerror(e)},e.onclose=()=>{this._connected||this.onclose&&this.onclose()},e.onmessage=e=>{if(this.onmessage)for(let t of e)"signals"===t.action?this._onSignalBatch(t.data):this.onmessage(t,this.name)}}_onSignalBatch(e){if(this.onmessage)for(let t of e)t.action||(t.action="signal"),this.onmessage(t,this.name)}},nt=class{constructor(e,t,i,r){this.logger=e,this.config=t,this.mainAddr=i,this.backupAddr=r,this.mainWS=this._init(i),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(r,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let i=new st(this.logger,this.config,e,t);return i.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},i.onmessage=e=>{this.onmessage&&this.onmessage(e,i.name)},i.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},i.onerror=e=>{this.onerror&&this.onerror(e)},i}sendSignalBatch(e,t,i){if(i){const r=this._getWSByName(i);r&&r.sendSignalBatch(e,t)}else this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected&&this.backupWS.sendSignalBatch(e,t)}sendSignal(e,t,i){this.sendSignalBatch(e,[t],i)}sendReject(e,t,i,r){if(r){const s=this._getWSByName(r);if(s)return void s.sendReject(e,t,i)}this.mainConnected?this.mainWS.sendReject(e,t,i):this.backupConnected?this.backupWS.sendReject(e,t,i):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,i){this.mainConnected&&this.mainWS.sendDebug(e,t,i)}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close(),this.normalClosed=!0}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(e){this.mainWS&&"backup"!==e&&this.mainWS.reconnect(),this.backupWS&&"main"!==e&&this.backupWS.reconnect()}forcePolling(e){this.mainWS&&"backup"!==e&&this.mainWS.forcePolling(),this.backupWS&&"main"!==e&&this.backupWS.forcePolling()}destroy(){this.close(),clearTimeout(this.backupTimer),this.mainWS=null,this.backupWS=null,this.destroyed=!0}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}};const at=function(e,t,i=40){var r=null,s=!1,n=i;return function(i=!1){if(i)return clearTimeout(r),void(s=!1);s||(s=!0,r=setTimeout((function(){e.call(t,n),s=!1,r=null}),1e3*n),n*=1.1)}};class ot{constructor(e,t,i=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=i,this.pool=[],t.ICEPreflight&&this.reset(),this.trickle=!1}reset(){this.destroy();for(let e=0;e<this.poolSize;e++)this.pool.push(this._createPeer())}_createPeer(){return new ee(this.engine,void 0,void 0,!0,this.config,{trickle:this.trickle})}get available(){return 0!==this.pool.length&&this.pool[0].signalMsgs.length>0}getPeer(){if(0===this.pool.length)return this._createPeer();const e=this.pool.shift();return this.pool.length<5&&this.pool.push(this._createPeer()),e}destroy(){for(let e of this.pool)e.destroy(!0);this.pool=[]}}const lt=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,i=0,r="";for(const s of e){if("="===s)break;const e=this.CHARSET.indexOf(s);for(t=t<<this.BITS_PER_BASE64_CHAR|e,i+=this.BITS_PER_BASE64_CHAR;i>=this.BITS_PER_BYTE;){i-=this.BITS_PER_BYTE;r+=(t>>i&(1<<this.BITS_PER_BYTE)-1).toString(16).padStart(2,"0").toUpperCase()}}let s="";for(let e=0;e<r.length;e++)s+=r[e],e%2==1&&e!==r.length-1&&(s+=":");return s}},ht="typ host",ut="generation 0",dt="network-cost",ct="rport",ft="0.0.0.0",gt={V:"v=",O:"o=",S:"s=",C:"c=",A:"a=",M:"m=",T:"t="},pt={U:"ice-ufrag:",P:"ice-pwd:",F:"fingerprint:",C:"candidate:",S:"sctp-port:",M:"max-message-size:"},vt={1:"sha-1",2:"sha-224",3:"sha-256",4:"sha-384",5:"sha-512",6:"md5",7:"md2",8:"token"},mt={P:`${ht} ${ut} ${dt} 999`,W:`${ct} 0 ${ut} ${dt} 999`,H:ht,S:"typ srflx",R:ct,A:"raddr",V:ft,F:"ufrag",G:`${ct} 0 ${ut}`,N:dt,E:"network-id",C:"tcptype active",Q:`${ut}`,U:"udp",T:"tcp"},yt={P:"application",U:"UDP/DTLS/SCTP",S:"DTLS/SCTP",D:"webrtc-datachannel"},Et={4:"IP4",6:"IP6"},St={0:ft},Tt=e=>(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in mt&&(e=mt[e]),e))).join(" "));function _t(e,t){let i=e.split("~"),r=[];i=i.map((e=>{let t=e.slice(0,1),i=e.slice(1);if(t in gt&&(t=gt[t]),"a="===t){let e=i.slice(0,1);const t=i.slice(1);e in pt&&(e=pt[e],i=e+t)}return t+i})),r.push("v=0"),r.push("s=-"),r.push("t=0 0"),r.push("a=msid-semantic: WMS");let s=0;i.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),i=[];i.push("-");const s=t.shift();if(s&&i.push(s),0===t.length)i.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&i.push(e),0===t.length)i.push("IN IP4 127.0.0.1");else{i.push("IN");const e=t.shift();e&&i.push(e);const r=t.shift();r&&i.push(r)}}r.splice(1,0,`o=${i.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(Lt,(e=>yt[e]))}(e),r.push(e),r.push("a=setup:"+(t?"actpass":"active")),r.push(`a=mid:${s}`),void s++;if(e.startsWith("a=candidate:"))return e=Tt(e),void r.push(e);if(e.startsWith("a=fingerprint:")){let[t,i]=e.slice(14).split(" ");return t in vt&&(t=vt[t]),i=lt.decode(i),void r.push(`a=fingerprint:${t} ${i}`)}if(e.startsWith("c=")){let[t,i]=e.slice(2).split(" ");return t in Et&&(t=Et[t]),i in St&&(i=St[i]),void r.push(`c=IN ${t} ${i}`)}"I"!==e?"Z"!==e?"B"!==e?r.push(e):r.push("a=sendrecv"):r.push("a=ice-options:ice2,trickle"):r.push("a=ice-options:trickle")}}));const n=r.length-1;return r.splice(n,0,`a=group:BUNDLE ${Array.from(Array(s).keys()).join(" ")}`),r.join("\r\n")}const Lt=new RegExp(Object.keys(yt).join("|"),"g");class bt extends(n()){constructor(e,t,i,r){super(),this.engine=e,this.logger=e.logger,this.config=r,this.connected=!1,this.scheduler=i,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set;const s=J().isMobile();this.peerPool=new ot(e,r,15),this.signalerWs=null,this.fetcher=t,this.peers=[],this.requestPeersQueue=[],this.minConns=5,this.stuns=[],this.requestMorePeers=at(this._requestMorePeers,this,p(35,45)),this.maxConns=s?15:22,this.maxConnsActive=s?10:13,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.requestPeersWaitCount=0,this.gotSignalFails={main:0,backup:0,limit:5},this.fuseRate=-1,this.overloaded=!1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:t,config:i,fetcher:r}=this,{btAnnounce:s,btAnnouncePreflight:n}=r,{wsSignalerAddr:a,wifiOnly:o,geoIpPreflight:l}=i;(l?n:s).call(r).then((e=>{const{scheduler:i}=this;if(!i)return;t.peerId=this.peerId=e.id,this.minConns=e.min_conns,i.minConns=this.minConns;const s=e.peers;i.notifyPeersLoaded(s.length),s.length>this.gotSignalFails.limit&&(this.gotSignalFails.limit=s.length),t.netType=r.announceInfo.netType,(e.wifi_only||o)&&t.isMobileNet&&(i.downloadOnly=!0,this.logger.info("downloadOnly mode"));const n=a.main;let l=a.backup;e.signal&&!e.signal2&&(l=void 0),this.signalerWs=this._initSignalerWs(e.signal||n,e.signal2||l,e.token,e.token2),0===s.length?this.requestMorePeers():this.peers=this._filterPeers(s),t.emitEvent("peerId",this.peerId),e.stun&&e.stun.length>0&&(this.stuns=e.stun),e.debug&&(this.logger.enableDebug(),e.log_url&&(this.logUploader=new U(e.log_url,this.fetcher.key||location.hostname,this.peerId,"2.16.3"),this.logger.setUploader(this.logUploader))),t.onTrackerResume&&t.onTrackerResume(e),e.fuse_rate&&(this.fuseRate=e.fuse_rate),e.overload&&(this.overloaded=!0,this.logger.warn("server overloaded, degrade signaling")),this.logger.info(`announce request response ${JSON.stringify(e,null,2)}`),/^.\d{2}/.test(this.peerId)||(this.maxConnsActive=1,this.maxConns=2)})).catch((i=>{if(this.scheduler&&("TRACKER_EXPT"===i.code&&t.emitEvent(e.EXCEPTION,i),this.scheduler.notifyPeersLoaded(0),i.retry)){const e=p(15e3,4e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.postStatsWithBeacon(),this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.peerPool.destroy(),this.peerPool=null,this.failedDCMap.clear(),this.notFoundDCSet.clear(),this.logUploader&&(this.logUploader.destroy(),this.logUploader=null),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer),clearTimeout(this.requestPeersTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}isPeerConnectedOrFailed(e){return!e||(this.DCMap.has(e)||this.failedDCMap.has(e)||e===this.peerId)}_filterPeers(e){const t=[];return e.filter((e=>!this.isPeerConnectedOrFailed(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator})})),t}_tryConnectToAllPeers(){const{logger:e}=this;if(0!==this.peers.length)for(this._checkDCMap(),e.info(`try connect to ${this.peers.length} peers, map size ${this.DCMap.size} limit ${this.maxConnsActive} peersNum ${this.scheduler.peersNum}`);this.peers.length>0&&!(this.DCMap.size>=this.maxConnsActive);){let t=this.peers.shift();if(this.isPeerConnectedOrFailed(t.id))continue;const i=t.intermediator;this.signalerWs.connected||i&&this.DCMap.has(i)?(e.debug(`create DataChannel ${t.id} intermediator ${i}`),this._createDatachannel(t.id,!0,i)):e.info(`skip peer ${t.id} without intermediator`)}else e.info("no peers after filter")}_handleSendSignal(e,t){const i=e.remotePeerId;if(e.intermediator){const r=this.DCMap.get(e.intermediator);if(r){let s=!0;for(let e of t)r.sendMsgSignal(i,this.peerId,e)||(s=!1);if(s)return;this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,this.signalerWs.sendSignalBatch(i,t,e.signalName)}_setupDC(t){t.on(e.DC_SIGNAL,(e=>{this._handleSendSignal(t,[e])})).on(e.DC_SIGNAL_BATCH,(e=>{this._handleSendSignal(t,e)})).on(e.DC_PEER_SIGNAL,(e=>{const i=e.to_peer_id||e.to,r=e.from_peer_id||e.from,s=e.action;if(i&&r&&s)if(i!==this.peerId){this.logger.info(`relay signal for ${r}`);const n=this.DCMap.get(i);if(n){if("signal"!==s)return void n.sendMsgSignalReject(i,r,e.reason,e.fatal);if(n.sendMsgSignal(i,r,e.data))return}t.sendMsgSignal(r,i)}else"signal"===s?this._handleSignalMsg(r,e,t.remotePeerId):this._handSignalRejected(r,e)})).on(e.DC_GET_PEERS,(()=>{const e=g(),i=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?15:22)&&!e.super));if(i&&i.length>0){const r=[];i.forEach((i=>{if(i.remotePeerId===t.remotePeerId||i.remotePeerId===this.peerId)return;if(!this.config.live&&(i.currentPos-t.currentPos>600||i.currentPos<t.currentPos))return;e-i.timeJoin>50&&r.push({id:i.remotePeerId,...i.region})})),this.logger.info(`send ${r.length} peers to ${t.remotePeerId}`),t.sendPeers(r)}})).on(e.DC_PEERS,(e=>{const i=e.peers;this.logger.info(`receive ${i.length} peers from ${t.remotePeerId}`),i&&i.length>0&&(i.forEach((e=>{e.intermediator=t.remotePeerId,e.region||(e.region={})})),this.requestPeersQueue.push(...i)),this.requestPeersWaitCount--,this.requestPeersWaitCount<=0&&this._handleRequestedPeers()})).once(e.DC_ERROR,((e,i)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${i}`),this.scheduler&&(this.scheduler.deletePeer(t),this._destroyAndDeletePeer(t.remotePeerId,e),this.fetcher&&(t.connected||e&&this.fetcher.increFailConns(),e&&this.failedDCMap.set(t.remotePeerId,`DC_FAILED ${i}`),this._doSignalFusing(this.scheduler.peersNum),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:i,data:r})=>{const{logger:s,signalerWs:n,gotSignalFails:a}=this,{remotePeerId:o,useBackupSignal:l,isInitiator:h}=t,u=l?"backup":"main";if(e?a[u]=0:(a[u]++,a[u]>=a.limit&&(a[u]=0,s.warn("gotSignalFails many, forcePolling"),n.forcePolling(u))),i&&e&&h&&(this.failedDCMap.set(o,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!e&&h&&!l&&this._tryBackupSignal(t,o,r))return t._startTimer(),void s.warn(`${o} conn timeout, try backup signal`);this._destroyAndDeletePeer(o,!1),this._doPeersRequest()})).once(e.DC_CLOSE,(e=>{this.logger.info(`datachannel ${t.channelId} closed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(t.remotePeerId,e),e&&this.failedDCMap.set(t.remotePeerId,"DC_CLOSE"),this._doPeersRequest()})).once(e.DC_OPEN,(()=>{t.isInitiator&&this.scheduler.handshakePeer(t)})).once(e.DC_METADATA,(e=>{const{scheduler:i}=this;t.isInitiator||i.handshakePeer(t),i.handleMetaData(t,e);const r=this.DCMap.size>=this.maxConnsActive;this.requestMorePeers(r),t.intermediator&&this.peersIncrement++,this._doSignalFusing(i.peersNum)}))}_doPeersRequest(){const e=this.scheduler.peersNum;!this.signalerWs.connected||this.overloaded&&e>this.minConns?this._requestPeersFromPeers(e):this.requestMorePeers(),this._tryConnectToAllPeers()}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e<=this.minConns&&this.signalerWs.normalClosed&&(this.logger.warn(`low conns ${e}, reconnect signaler`),this.signalerWs.reconnect())}_initSignalerWs(t,i,r,s){const n=(e,t)=>{let i=`${e}?id=${this.peerId}&p=web&v=2.16.3&b=1`;return this.config.signalCompact&&(i=`${i}&c=1`),t&&(i=`${i}&token=${t}`),i};let a,o=n(t,r);if(i&&i!==t){let e=n(i,s);a=new nt(this.logger,this.config,o,e)}else a=new st(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this.engine.emitEvent("serverConnected",!0),this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let i=e.action;const r=e.from_peer_id||e.from;if(r)switch(i){case"signal":this._handleSignalMsg(r,e,null,t);break;case"reject":this._handSignalRejected(r,e);break;default:this.logger.warn(`Signal websocket unknown action ${i}`)}else this.logger.warn("fromPeerId is missed")},a.onclose=()=>{this.connected=!1,this.engine.emitEvent("serverConnected",!1)},a.onerror=t=>{t.message&&this.logger.warn(`signal err: ${t.message}`),t.message&&this.engine.emitEvent(e.EXCEPTION,Ne(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const i=`signaling ${e} rejected`;this.logger.warn(`${i}, reason ${t.reason}`);const r=this.DCMap.get(e);r&&!r.connected&&(r.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,i),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,i,r="main"){return!(!(this.signalerWs.backupConnected&&e&&i.length>0&&"main"===r)||e.useBackupSignal)&&(e.useBackupSignal=!0,e.signalName="backup",e.intermediator=void 0,this.signalerWs.sendSignalBatch(t,i,"backup"),!0)}_handleSignalMsg(e,t,i,r){if(!this.scheduler)return;const{logger:s}=this;if(t.data){if(this.failedDCMap.has(e))return void this._sendSignalReject(e,`${e} ${this.failedDCMap.get(e)||"unknown"}`,i,r,!0);this._handleSignal(e,t.data,i,r)}else{const t=this.DCMap.get(e);if(!t)return;if(this._tryBackupSignal(t,e,t.signalMsgs,r))return void this.logger.warn(`${e} not found from main, try backup signal`);if(t.useBackupSignal)return;this._destroyAndDeletePeer(e),s.info(`signaling ${e} not found`);const{scheduler:n}=this;n.waitForPeer&&(n.waitingPeers--,0===n.waitingPeers&&n.notifyPeersLoaded(0)),this.requestMorePeers(),this._tryConnectToAllPeers(),i||this.notFoundDCSet.add(e)}}_handleSignal(e,t,i,r){let s=t;"string"==typeof s?s=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:Tt(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),i="O"===e[0];return{type:i?"offer":"answer",sdp:_t(t,i)}})(s):t=void 0;const n=s.type,{logger:a}=this;let o=this.DCMap.get(e);if(o){if(o.connected)return void a.info("datachannel had connected, signal ignored");if("offer"===n&&o.isInitiator){if(!(this.peerId>e))return void a.warn(`${e} signal type wrong ${n}, ignored`);a.warn(`${e} signal type wrong ${n}, convert to non initiator`),this._destroyAndDeletePeer(e,!1),o=this._createDatachannel(e,!1,i)}}else{if("answer"===n){const t=`${e} type wrong ${n}`;return a.warn(t),this._sendSignalReject(e,t,i,r),void this._destroyAndDeletePeer(e,!1)}if(a.debug(`receive node ${e} connection request`),this.DCMap.size>=this.maxConns){const t=`reach limit ${this.maxConns}`;return a.warn(t),void this._sendSignalReject(e,t,i,r)}o=this._createDatachannel(e,!1,i)}o&&(r&&(o.signalName=r),o.receiveSignal(s,t))}_createDatachannel(e,t,i){if(!this.fetcher)return;let r;if(t&&this.peerPool.available)r=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${r.signalMsgs.length}`),r.intermediator=i,r.assignPeerId(this.peerId,e);else{let s=this.config.trickleICE;this.overloaded&&(s=!1),r=new ee(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:i,trickle:!i&&s})}return this.DCMap.set(e,r),this._setupDC(r),r}_sendSignalReject(e,t,i,r,s){if(i){const r=this.DCMap.get(i);if(r&&r.sendMsgSignalReject(e,this.peerId,t,s))return}this.signalerWs.sendReject(e,t,s,r)}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this,i=this.scheduler.peersNum;i>=this.maxConnsActive||(t.info(`requestMorePeers after delay ${e}, peersIncrement ${this.peersIncrement}`),i<3||i<this.minConns&&this.peersIncrement<=3&&!this.gotPeersFromTracker?this._requestPeersFromServer(i):this._requestPeersFromPeers(i)||this._requestPeersFromServer(i),this.peersIncrement=0)}_requestPeersFromServer(e){const{logger:t}=this;this.failedDCMap.size>50&&(this.failedDCMap=new Map([...this.failedDCMap].slice(-50))),this.notFoundDCSet.size>20&&(this.notFoundDCSet=new Set([...this.notFoundDCSet].slice(-20))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCMap.keys(),...this.notFoundDCSet.keys()],0===e).then((e=>{e&&e.peers&&(t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=this._filterPeers(e.peers),this._tryConnectToAllPeers())})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0}_requestPeersFromPeers(e){return!!this.requestPeersTimer||(e>=this.maxConnsActive||(this.requestPeersWaitCount=this.scheduler.requestPeers(),0!==this.requestPeersWaitCount&&(this.gotPeersFromTracker=!1,this.requestPeersTimer=setTimeout((()=>{this.logger.warn("requestPeersTimer timeout"),this._handleRequestedPeers()}),1e4),!0)))}_handleRequestedPeers(){if(clearTimeout(this.requestPeersTimer),this.requestPeersTimer=void 0,this.fetcher){if(this.requestPeersQueue.length>0){const e=function(e,t){const i=[],r=new Set;for(let t of e)r.has(t.id)||(r.add(t.id),i.push(t));const{asn:s,country:n}=t;if(!s||!n||i.length<2)return i;const a=i.filter((e=>!e.asn&&!e.country)),o=i.filter((e=>e.country===n&&e.asn!==s)),l=i.filter((e=>e.asn===s&&e.country===n)),h=i.filter((e=>!a.includes(e)&&!l.includes(e)&&!o.includes(e)));return l.concat(o).concat(a).concat(h)}(this.requestPeersQueue,this.fetcher.announceInfo);this.peers=this._filterPeers(e),this.requestPeersQueue=[]}this._tryConnectToAllPeers()}}_destroyAndDeletePeer(e,t=!0){const i=this.DCMap.get(e);return!!i&&(i.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=g();for(let t of this.DCMap.values()){const i=e-t.timeJoin;e-t.timeJoin>30&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${i} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}}const At=bt;class It extends se{constructor(e={},t=null){if(super(e),e.validateSegment||(e.validateSegment=function(e,t){return!0}),this.hlsjs=t,this.config=Object.assign({useDiskCache:!e.live},fe,e),t){this.HLSEvents=t.constructor.Events;const e=t.constructor.version;this.hlsjsVersion=e,this.config.isHlsV0=e&&"0"===e.split(".")[0]}this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t}=this.config,i=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(i=this.makeChannelId(e,t));return{channelIdMaker:i,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo}}}setupElectron(){this.browserInfo.device===Q.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e=super.getExtraForStats();return!this.config.live&&this.media&&(e.pos=Math.round(this.media.currentTime)),this.multiBitrate&&this.currentLevel!==this.lastLevel&&(e.level=this.currentLevel+"",this.lastLevel=this.currentLevel),e}getExtraForPeersRequest(){const e=super.getExtraForPeersRequest();return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){super.destroy()}async initSegmentManager(e){const{logger:i,config:r}=this;if(self.indexedDB&&r.useDiskCache&&!r.live){const e=new De(this,r);try{await e.setupStore(),this.bufMgr=e}catch(e){i.warn(e),this.bufMgr=new Me(this,r)}}else this.bufMgr=new Me(this,r);if(this.bufMgr.maxBufSize<=0)throw new Error("bufMgr state is invalid");"SegmentStore"===this.bufMgr.name&&(this.removeAllListeners(t.BM_FATAL_ERROR),this.once(t.BM_FATAL_ERROR,(()=>{i.warn("SegmentStoreFatalError, switch to SegmentCache"),this.bufMgr.destroy(),this.bufMgr=new Me(this,r),e&&e(this.bufMgr)})))}generateTag(){let e=(0,Q.getBrowser)();return e.includes("iPhone")&&"HlsSwP2pEngine"===this.engineName&&(e=`${e}_p`),this.playerName&&(e=`${e}_${this.playerName}`),e}async _init(e,t,i){const{logger:r,config:s}=this;if(!se.isSupported())throw new Error("webrtc is not supported");await this.initSegmentManager((e=>{if(this.tracker){const{scheduler:t}=this.tracker;t.bufferManager=e,t.bitset.clear()}})),i.live||this.media&&(i.pos=Math.round(this.media.currentTime)),i.tag=void 0===s.tag?this.generateTag():s.tag;let n=new Ze(this,s.token,encodeURIComponent(e),s.announce||"",i);this.fetcher=n,this.tracker=new At(this,n,t,s),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?ue:he)}_onHlsError(e,i){if(!i||!this.hlsjs)return;const{logger:r,tracker:s,config:n}=this;if(!r)return;const a=`${i.type} fatal ${i.fatal} details ${i.details} reason ${i.reason}`;if(i.fatal?r.error(a):r.warn(a),"networkError"===i.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:o}=this.browserInfo,l=`${o||""} hlsjs ${this.hlsjsVersion} ${location.href}`,h=this.hlsjs.constructor.ErrorDetails;switch(i.details){case h.BUFFER_STALLED_ERROR:if("HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),s&&s.scheduler){const e=s.scheduler;r.warn(`buffered: ${1e3*e.getBufferedDuration()} fragLoading ${e.fragLoading} isCritical ${e.isCritical()}`)}break;case h.INTERNAL_EXCEPTION:if(i.event&&"demuxerWorker"!==i.event){i.error||(i.error={});const e=`${i.error.message} event ${i.event} ${l}`;this.fetcher&&i.fatal&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=e),r.error(`INTERNAL_EXCEPTION event ${i.event} err ${i.error.message}`),this.emitEvent(t.EXCEPTION,Ne(i.error,"HLSJS_EXPT")),r.report(e,i.event,this.peerId,"2.16.3")}break;default:const e=i.details===h.FRAG_PARSING_ERROR;if(i.fatal||e){"mediaError"===i.type&&s&&s.scheduler&&s.scheduler.disconnectLoadingPeer(void 0,this.peerId).then((e=>{e&&s.scheduler.clearCache()}));const e=`${i.type} ${i.details} ${i.err||""} ${l}`;r.report(e,i.details,this.peerId,"2.16.3")}}}}class Rt{constructor(){this.method=null,this.key=null,this.iv=null,this._uri=null}get uri(){return!this._uri&&this.reluri&&(this._uri=o.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}class Pt{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[Pt.ElementaryStreamTypes.AUDIO]:!1,[Pt.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=o.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url}set url(e){this._url=e}get byteRange(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;let e=[];if(this.rawByteRange){const t=this.rawByteRange.split("@",2);if(1===t.length){const t=this.lastByteRangeEndOffset;e[0]=t||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get decryptdata(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}get endProgramDateTime(){if(!Number.isFinite(this.programDateTime))return null;let e=Number.isFinite(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}addElementaryStream(e){this._elementaryStreams[e]=!0}hasElementaryStream(e){return!0===this._elementaryStreams[e]}createInitializationVector(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let i=e;return e&&e.method&&e.uri&&!e.iv&&(i=new Rt,i.method=e.method,i.baseuri=e.baseuri,i.reluri=e.reluri,i.iv=this.createInitializationVector(t)),i}}class kt{constructor(e){this.endCC=0,this.endSN=0,this.fragments=[],this.initSegment=null,this.live=!0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=e,this.version=null}get hasProgramDateTime(){return!(!this.fragments[0]||!Number.isFinite(this.fragments[0].programDateTime))}}const Dt=/^(\d+)x(\d+)$/,wt=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class Ct{constructor(e){"string"==typeof e&&(e=Ct.parseAttrList(e));for(let t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}decimalInteger(e){const 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=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}enumeratedString(e){return this[e]}decimalResolution(e){const t=Dt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,i={};for(wt.lastIndex=0;null!==(t=wt.exec(e));){let e=t[2],r='"';0===e.indexOf(r)&&e.lastIndexOf(r)===e.length-1&&(e=e.slice(1,-1)),i[t[1]]=e}return i}}const Mt=Ct,Ot={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}};const xt=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Ft=/#EXT-X-MEDIA:(.*)/g,Nt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),Bt=/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/,Ut=/\.(mp4|m4s|m4v|m4a)$/i;class Gt{static findGroup(e,t){if(!e)return null;let i=null;for(let r=0;r<e.length;r++){const s=e[r];s.id===t&&(i=s)}return i}static convertAVC1ToAVCOTI(e){let t,i=e.split(".");return i.length>2?(t=i.shift()+".",t+=parseInt(i.shift()).toString(16),t+=("000"+parseInt(i.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let i,r=[];function s(e,t){["video","audio"].forEach((i=>{const r=e.filter((e=>function(e,t){const i=Ot[t];return!!i&&!0===i[e.slice(0,4)]}(e,i)));if(r.length){const s=r.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${i}Codec`]=s.length>0?s[0]:r[0],e=e.filter((e=>-1===r.indexOf(e)))}})),t.unknownCodecs=e}for(xt.lastIndex=0;null!=(i=xt.exec(e));){const e={},n=e.attrs=new Mt(i[1]);e.url=Gt.resolve(i[2],t);const a=n.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=n.decimalInteger("AVERAGE-BANDWIDTH")||n.decimalInteger("BANDWIDTH"),e.name=n.NAME,s([].concat((n.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=Gt.convertAVC1ToAVCOTI(e.videoCodec)),r.push(e)}return r}static parseMasterPlaylistMedia(e,t,i,r=[]){let s,n=[],a=0;for(Ft.lastIndex=0;null!==(s=Ft.exec(e));){const e={},o=new Mt(s[1]);if(o.TYPE===i){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=i,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=Gt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),r.length){const t=Gt.findGroup(r,e.groupId);e.audioCodec=t?t.codec:r[0].codec}e.id=a++,n.push(e)}}return n}static parseLevelPlaylist(e,t){let i,r,s=0,n=0,a=new kt(t),o=new Rt,l=0,h=null,u=new Pt,d=null;for(Nt.lastIndex=0;null!==(i=Nt.exec(e));){const e=i[1];if(e){u.duration=parseFloat(e);const t=(" "+i[2]).slice(1);u.title=t||null,u.tagList.push(t?["INF",e,t]:["INF",e])}else if(i[3]){if(Number.isFinite(u.duration)){const e=s++;u.start=n,u.levelkey=o,u.sn=e,u.cc=l,u.baseurl=t,u.relurl=(" "+i[3]).slice(1),Ht(u,h),a.fragments.push(u),h=u,n+=u.duration,u=new Pt}}else if(i[4]){if(u.rawByteRange=(" "+i[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(u.lastByteRangeEndOffset=e)}}else if(i[5])u.rawProgramDateTime=(" "+i[5]).slice(1),u.tagList.push(["PROGRAM-DATE-TIME",u.rawProgramDateTime]),null===d&&(d=a.fragments.length);else{for(i=i[0].match(Bt),r=1;r<i.length&&void 0===i[r];r++);const e=(" "+i[r+1]).slice(1),n=(" "+i[r+2]).slice(1);switch(i[r]){case"#":u.tagList.push(n?[e,n]:[e]);break;case"PLAYLIST-TYPE":a.type=e.toUpperCase();break;case"MEDIA-SEQUENCE":s=a.startSN=parseInt(e);break;case"TARGETDURATION":a.targetduration=parseFloat(e);break;case"VERSION":a.version=parseInt(e);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"DIS":l++,u.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":l=parseInt(e);break;case"KEY":var c=new Mt(e),f=c.enumeratedString("METHOD"),g=c.URI,p=c.hexadecimalInteger("IV");f&&(o=new Rt,g&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(f)>=0&&(o.method=f,o.baseuri=t,o.reluri=g,o.key=null,o.iv=p));break;case"START":let r=new Mt(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(r)&&(a.startTimeOffset=r);break;case"MAP":let h=new Mt(e);u.relurl=h.URI,u.rawByteRange=h.BYTERANGE,u.baseurl=t,u.sn="initSegment",a.initSegment=u,u=new Pt,u.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${i}`)}}}return u=h,u&&!u.relurl&&(a.fragments.pop(),n-=u.duration),a.totalduration=n,a.averagetargetduration=n/a.fragments.length,a.endSN=s-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>Ut.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),u=new Pt,u.relurl=a.fragments[0].relurl,u.baseurl=t,u.level=id,u.sn="initSegment",a.initSegment=u,a.needSidxRanges=!0),d&&function(e,t){let i=e[t];for(let r=t-1;r>=0;r--){const t=e[r];t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(a.fragments,d),a}}function Ht(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Number.isFinite(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}const Kt={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},Vt=(e,t,i,r,s=!1)=>{const[n,a,o]=$t(e,t,i,r);return s&&n.length>=1?P(n[0]):n.length>=2?[n[0],n[1]]:k(n,a,o)},$t=(e,t,i,r)=>{const s=[],{COMPLETE:n,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=Kt;return[n,a,o].forEach((n=>{s.push(Wt(e,n,t,i,r))})),s},Wt=(e,t,i,r,s)=>e.filter((e=>e.bitset.hasWithId(i,r,s,t)));class qt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const i=Number(e);if(i<0)continue;const r=new Map;if(t[e])for(let i of t[e])r.set(i,{state:Kt.COMPLETE,segId:void 0,size:void 0});this.levelMap.set(i,r)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,i,r=Kt.ANY){if(t<0)return!1;const s=this._createOrGetSet(t).get(e);return!!s&&((!i||!s.segId||s.segId===i)&&(r===Kt.ANY||s.state===r))}has(e,t,i=Kt.ANY){return this.hasWithId(e,t,void 0,i)}hasCompleteOr(e,t,i=Kt.COMPLETE){const r=this._createOrGetSet(t).get(e);return!!r&&(r.state===Kt.COMPLETE||r.state===i)}getObj(e,t){let i=this._createOrGetSet(t).get(e);return i||(i={}),i}getSegId(e,t){return this.getObj(e,t).segId}getSize(e,t){return this.getObj(e,t).size}getState(e,t){return this.getObj(e,t).state}delete(e,t){return this._createOrGetSet(t).delete(e)}add(e,t,i,r,s){if("number"!=typeof(n=e)||n%1!=0)return;var n;this._createOrGetSet(t).set(e,{state:r,segId:i,size:s}),this.isLive&&this._trimBitset(e)}array(e){const t=this._createOrGetSet(e);return this._keysForStateComplete(t)}allArray(){let e={};return this.levelMap.forEach(((t,i)=>{e[i]=this._keysForStateComplete(t)})),e}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetSet(e).size}_createOrGetSet(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}_trimBitset(e){const t=e-20;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[i,r]of e)r.state===Kt.COMPLETE&&t.push(i);return t}}class jt{constructor(){this.levelMap=new Map}totalLevels(){return this.levelMap.size}has(e,t){return this._createOrGetMap(t).has(e)}delete(e,t){return this._createOrGetMap(t).delete(e)}decre(e,t){const i=this._createOrGetMap(t);if(i.has(e)){let t=i.get(e);1===t?i.delete(e):i.set(e,t-1)}}incre(e,t){const i=this._createOrGetMap(t);if(i.has(e)){let t=i.get(e);i.set(e,t+1)}else i.set(e,1)}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetMap(e).size}_createOrGetMap(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}}const Yt=class{constructor(){this.peerMap=new Map}isEmpty(){return 0===this.peerMap.size}size(){return this.peerMap.size}clear(){this.peerMap.clear()}getPeers(){return[...this.peerMap.values()]}getPeerValues(){return this.peerMap.values()}hasPeer(e){return this.peerMap.has(e)}addPeer(e,t){this.peerMap.set(e,t)}getPeerIds(){return[...this.peerMap.keys()]}removePeer(e){this.peerMap.delete(e)}getPeersOrderByWeight(){const e=this.getAvailablePeers();return e.sort(((e,t)=>0===t.weight?1:0===e.weight?-1:t.weight-e.weight)),e}getPeer(e){return this.peerMap.get(e)}getAvailablePeers(){return this.getPeers().filter((e=>e.isAvailableUrgently))}},zt=Symbol("shareOnly");class Xt extends(n()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Yt,this.fragLoading=!1,this._setupEngine&&this._setupEngine(),this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[zt]=!1,this.downloadOnly=!1,this.loadedPeerNum=0,this.minConns=5}get isMobileNet(){return this.engine.isMobileNet}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const e=this.getStatsForPeer();let t=this.peersNum;const i=g();this.getPeers().forEach((r=>{t>this.minConns+1&&(i-r.dataExchangeTs>120||i-r.gotStatsTs>=83)?(this.logger.warn(`close dead peer ${r.remotePeerId} level ${r.currentLevel}`),r.close(!1),t--):r.connected&&r.sendMsgStats(t,e)}))}),4e4)}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}requestPeers(){const e=g();let t=0;for(let i of this.getPeers())i.mobileNet||i.super||(e-i.gotPeersTS<60?this.logger.warn(`${i.remotePeerId} just got peers, ignored`):(i.sendPeersRequest(),i.gotPeersTS=e,t++));return t}chokePeerRequest(t){const i={event:e.DC_CHOKE};t?t.sendJson(i):this._broadcastToPeers(i)}unchokePeerRequest(t){const i={event:e.DC_UNCHOKE};t?t.sendJson(i):this._broadcastToPeers(i)}stopRequestFromPeers(){for(let e of this.getPeers())e.choked=!0}resumeRequestFromPeers(){for(let e of this.getPeers())e.choked=!1}setShareOnly(){this[zt]=!0}deletePeer(e){e.downloading&&this._handlePieceAborted(e.remotePeerId),this.peerManager.hasPeer(e.remotePeerId)&&this.peerManager.removePeer(e.remotePeerId),this._peersStats(this.peerManager.getPeerIds())}getPeers(){return[...this.peerManager.getPeerValues()]}addPeer(e){const{logger:t}=this;this.peerManager.addPeer(e.remotePeerId,e),this[zt]&&(e.choked=!0);const i=this.peerManager.getPeerIds();this._peersStats(i);const{asn:r,country:s}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${s||""} asn ${r||""}, now has ${i.length} peers`)}hasPeer(e){return this.peerManager.hasPeer(e)}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const{logger:e}=this,t=this.getIdlePeer().length;if(e.info(`peers: ${this.peersNum} idle peers: ${t}`),t<this.peersNum){const t=this.peerManager.getPeers(),i=t.filter((e=>e.downloading));e.warn(`downloading: ${i.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of i)e.warn(`${t.remotePeerId} loading ${t.segId} remains ${t.remainAttachments} total ${t.pieceMsg.attachments}`)}return t>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(t){this.bufMgr=t,t.on(e.BM_LOST,(({sn:e,segId:t,next:i,level:r})=>{this._broadcastLost(e,t,r),this.onBufferManagerLost(e,t,i,r)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,i,r,s){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:i||void 0,level:r},s)}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),clearTimeout(this.checkTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(t){const{logger:i}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),i.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{i.warn(`peer ${t.remotePeerId} download aborted, reason ${e.reason}`),this._handlePieceAborted(t.remotePeerId),this.config.live&&this.checkPeers&&this.checkPeers()})).on(e.DC_DISCONNECT,(()=>{this.peersNum>=this.minConns&&(this.logger.warn(`close disconnected peer ${t.remotePeerId}`),t.close(!1))}))}_broadcastToPeers(e,t){for(let i of this.getPeers())t&&i===t||i.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;I(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(i=this.loadedPeerNum)?3:.5*i+1.67);var i;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const i=this.requestingMap.get(e);if(i)return void i.removeStreamListener(t);const r=this.segmentBuilderMap.get(e);r&&r.removeStreamListener(t)}setTargetPeersFromGroup(e,t,i,r){if(e.hasReversePeer){if((i=t.concat(i)).length>0)return this.targetPeers.forwardPeer=i[0],!0}else if(e.hasForwardPeer&&(r=t.concat(r)).length>0)return this.targetPeers.reversePeer=r[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=k(t,i,r),this.targetPeers.some((e=>!!e)))}}const Qt=Xt;class Jt extends(n()){constructor(){super(),this.internalMap=new Map}has(e){return this.internalMap.has(e)}set(e,t){this.internalMap.set(e,t),S(this.internalMap,13,(e=>{e&&e.destroy()}))}get(e){return this.internalMap.get(e)}delete(e){const t=this.internalMap.get(e);t&&(t.destroy(),this.internalMap.delete(e))}get size(){return this.internalMap.size}clear(){this.internalMap.clear(),this.removeAllListeners()}get activePeers(){let e=0;return[...this.internalMap.values()].forEach((t=>{t.hasForwardPeer&&!t.forwardCanceled&&(e+=1),t.hasReversePeer&&!t.reverseCanceled&&(e+=1)})),e}}const Zt=0,ei=1,ti=2,ii=3;class ri extends(n()){constructor(){super(),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.timeout=0,this.withCredentials=!1,this.status=0,this.readyState=this.UNSENT,this.headers=new Map,this.responseHeaders=null,this.on("load",(e=>{this.onload&&this.onload(e)})),this.on("abort",(e=>{this.onabort&&this.onabort(e)})),this.on("error",(e=>{this.onerror&&this.onerror(e)})),this.on("loadstart",(e=>{this.onloadstart&&this.onloadstart(e)})),this.on("progress",(e=>{this.onprogress&&this.onprogress(e)})),this.on("timeout",(e=>{this.ontimeout&&this.ontimeout(e)})),this.on("loadend",(e=>{this.onloadend&&this.onloadend(e)})),this.on("readystatechange",(()=>{this.onreadystatechange&&this.onreadystatechange()}))}setRequestHeader(e,t){this.headers.set(e,t)}addEventListener(e,t){this.addListener(e,t)}removeEventListener(e,t){this.removeListener(e,t)}overrideMimeType(){}getAllResponseHeaders(){if(!this.responseHeaders)return null;let e="";return this.responseHeaders.forEach(((t,i)=>{e+=`${i}: ${t}\n`})),e}getResponseHeader(e){return this.responseHeaders?this.responseHeaders.get(e):null}open(){this.readyState=this.OPENED,this.emit("loadstart")}abort(){this.readyState=this.DONE,this.status=0,this.emit("loadend")}send(){}_emitEvent(e){this.emit(e,{type:e,target:this})}}const si=/(\d+)-(\d+)\/(\d+)/;function ni(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class ai{constructor(e){this.fetchSetup=e.fetchSetup||oi,this.xhrSetup=e.xhrSetup,this.controller=new self.AbortController,this.stats=D(),this.packetSize=u,this.fakeXhr=new ri}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.xhrSetup=this.fakeXhr=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.callbacks&&this.callbacks.onUpdate&&this.callbacks.onUpdate(void 0,!1,!0),this.controller.abort())}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;r.trequest=r.loading.start;let s=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal);const n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l=2e4}=t.loadPolicy||{},h=i.onUpdate,u=i.onBodyStart;this.context=e,this.config=t,this.callbacks=i,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),s=function(e,t){e.withCredentials&&(t.credentials="include");for(let[i,r]of e.headers)t.headers.set(i,r);return t}(this.fakeXhr,s)),this.request=this.fetchSetup(e,s),clearTimeout(this.requestTimeout),t.timeout=o&&Number.isFinite(o)?o:l,this.requestTimeout=setTimeout((()=>{this.abortInternal(),this.fakeXhr._emitEvent("timeout"),this.fakeXhr._emitEvent("loadend"),i.onTimeout&&i.onTimeout(r,e,this.response)}),this.fakeXhr.timeout||t.timeout);const d="then"in(c=this.request)&&c.then instanceof Function?this.request.then(self.fetch):self.fetch(this.request);var c;const{fakeXhr:f}=this;f.readyState=f.OPENED,f.emit("readystatechange"),f._emitEvent("loadstart"),d.then((s=>{this.response=this.loader=s;const a=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout&&i.onTimeout(r,e,this.response)}),l-(a-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new li(t||"fetch, bad network response",e,s)}r.tfirst=r.loading.first=a,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=si.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Number.isFinite(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||r.total;let o=0;try{const e=s.headers.get("Content-Range").split("/");2===e.length&&(o=parseInt(e[1],10))}catch(e){}const{fakeXhr:d}=this;return d.readyState=d.HEADERS_RECEIVED,d.responseHeaders=s.headers,d.emit("readystatechange"),h&&"0"!==r.total?(u&&u(r.total,o),this.loadProgressively(s,r,e,h)):(d.emit("progress",new ProgressEvent("progress",{lengthComputable:!1})),n?s.arrayBuffer():"json"===e.responseType?s.json():s.text())})).then((t=>{const{response:s}=this;clearTimeout(this.requestTimeout),r.tload=r.loading.end=Math.max(performance.now(),r.loading.first);const n=t[a];n&&(r.loaded=r.total=n);const o={url:s.url,data:t,code:s.status};i.onProgress&&i.onProgress(r,e,t,s),i.onSuccess&&i.onSuccess(o,r,e,s)})).catch((t=>{if(clearTimeout(this.requestTimeout),r.aborted)return;const s=t&&t.code||0,n=t?t.message:null;i.onError&&i.onError({code:s,text:n},e,t?t.details:null,r)}))}loadProgressively(e,t,i,r){const s=e.body.getReader();let n=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>s.read().then((({value:i,done:s})=>{const{fakeXhr:c}=this;if(c.readyState!==c.LOADING&&(c.readyState=c.LOADING,c.emit("readystatechange")),i&&(n+=i.length),s){if(l.byteLength>0)if(n<=this.packetSize){const e=(0,a.h)(n);l.copy(e,0,o*this.packetSize,l.byteLength),r(e,!0)}else{const e=function(e,t){const i=e.byteLength-t,r=[];let s=t,n=Math.floor(i/u),o=i%u;for(let t=0;t<n;t++){const t=(0,a.h)(u);e.copy(t,0,s,s+u),r.push(t),s+=u}if(o>0){const t=(0,a.h)(o);e.copy(t,0,s,s+o),r.push(t)}return r}(l,o*this.packetSize);for(let t=0;t<e.length;t++)r(e[t],t===e.length-1)}const t=l.buffer,{fakeXhr:i}=this,{status:s,statusText:h,url:d}=e;return i.readyState=i.DONE,i.responseText=s,i.status=h,i.responseURL=d,i.responseType="arraybuffer",i.response=t,i.emit("readystatechange"),i._emitEvent("load"),i._emitEvent("loadend"),Promise.resolve(t)}if(t.loaded+=i.length,c.emit("progress",new ProgressEvent("progress",{lengthComputable:!0,loaded:t.loaded,total:t.total})),this.callbacks.onLoaded&&this.callbacks.onLoaded({total:t.total,loaded:t.loaded,first:!h},this.context),h=!0,l=a.h.concat([l,i]),n>=this.packetSize){n-=this.packetSize;const e=(0,a.h)(this.packetSize);l.copy(e,0,o*this.packetSize,(o+1)*this.packetSize),o++,r(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function oi(e,t){return new self.Request(e.url,t)}class li extends Error{constructor(e,t,i){super(e),this.code=t,this.details=i}}class hi extends(n()){constructor(e,t,i=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=i,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=2e3,this.proxied=!1,this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.forwardBufList=[],this.reverseBufList=[],this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.rangeRequesting=!1,this.waitingRemain=!1,this.httpLoaded=0,this.p2pLoaded=0,this.deadline=0,this.forwardCanceled=!1,this.reverseCanceled=!1,this.firstReceived=!1,this.alreadyOutput=!1,this.pieceMsg={}}get isDownloading(){return this.timeReceivePiece>0}get isAlmostDeadline(){return this.rangeRequesting||this.alreadyOutput}hasPeer(e){return!!e&&(e===this.forwardPeer||e===this.reversePeer)}get streamListeners(){return[...this.reverseStreamListeners,...this.forwardStreamListeners].length}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg,i=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let r of i){const{handler:i}=r;i(e,t,!0,"aborted by synthesizer")}this._resetStreamListeners()}_resetStreamListeners(){this.reverseStreamListeners.length=0,this.forwardStreamListeners.length=0}_notifyStreamListenersRemain(){if(this.forwardStreamListeners.length>0){for(let e=this.forwardOffset+1;e<this.bufArr.length;e++)this._notifyStreamListeners(!1,this.bufArr[e],e);this.forwardStreamListeners=[]}if(this.reverseStreamListeners.length>0){for(let e=this.reverseOffset-1;e>=0;e--)this._notifyStreamListeners(!0,this.bufArr[e],e);this.reverseStreamListeners=[]}}addStreamListener(e,t,i){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:i,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:i}=this.pieceMsg,r=r=>r.filter((r=>r.peerId!==e||(r.handler(t,i,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=r(this.forwardStreamListeners),this.reverseStreamListeners=r(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let i=performance.now();e<=0?setTimeout((()=>{this._handleTimeout(!1,!1)}),0):(this.firstPieceTimer=setTimeout((()=>{if(this.firstReceived)return;const e=()=>{this.logger.warn(`switch to http, firstReceived ${this.firstReceived}`),this._handleTimeout(!1)};if(this.timeReceivePiece>0){const t=(this.timeReceivePiece-i)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=i+e,this._startTimer(e,t))}setExtra(e={}){e.url&&(this.url=e.url),e.rangeStart&&(this.rangeStart=e.rangeStart),e.rangeEnd&&(this.rangeEnd=e.rangeEnd),e.httpLoadTime&&(this.httpLoadTime=e.httpLoadTime),e.proxied&&(this.proxied=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup),e.headers&&(this.headers=e.headers),e.segId&&!this.pieceMsg.seg_id&&(this.pieceMsg.seg_id=e.segId)}get hasForwardPeer(){return!!this.forwardPeer}get hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}get isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}get isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1,t),!0))}setReversePeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0,t),!0))}setPeer(e,t,i){return t?this.setReversePeer(e,i):this.setForwardPeer(e,i)}deletePeer(e){const t=e===this.reversePeer;this._detachPeer(e),t?this.reversePeer=null:this.forwardPeer=null,(this.isEmpty||this.deadline>0)&&this._handleTimeout(!1,!1)}terminate(){this._handleTimeout(!1,!1)}get hasPartialBuffer(){return this.hasForwardBuffer||this.hasReverseBuffer}get hasForwardBuffer(){return this.forwardOffset>=0}get hasReverseBuffer(){return this.pieceMsg&&this.reverseOffset<this.pieceMsg.attachments}get isForwardBufferFull(){return this.pieceMsg&&this.forwardOffset>=this.pieceMsg.attachments-1}get isReverseBufferFull(){return this.reverseOffset<=0}_cancelP2p(e=!1){const{seg_id:t,sn:i,level:r}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(i,r,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(i,r,t),this.reverseCanceled=!0)}detachPeers(){this._detachPeer(this.forwardPeer),this._detachPeer(this.reversePeer)}destroy(){this._notifyStreamListenersAbort(),this.removeAllListeners(),this.destroyed=!0,this._detachPeer(this.forwardPeer),this.forwardPeer=null,this.forwardOffset=-1,this._detachPeer(this.reversePeer),this.reversePeer=null,this.reverseOffset=1e4,this.bufArr=[],this.forwardStreamListeners=[],this.reverseStreamListeners=[],this._abortLoading()}_abortLoading(){clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._cancelP2p(),this.httpLoader&&(this.logger.warn("abort syn httpLoader"),this.httpLoader.abort(),this.httpLoader=void 0)}_detachPeer(t){if(!t)return;const i=t===this.reversePeer?this.reverseEvents:this.forwardEvents;i&&i&&t.off(e.DC_PIECE_DATA,i.onPieceData).off(e.DC_PIECE,i.onPiece).off(e.DC_PIECE_NOT_FOUND,i.onPieceNotFound).off(e.DC_PIECE_ABORT,i.onPieceAbort)}_receivePacket(t,i,r,s=!0){const{seg_id:n,sn:o,level:l,size:h,ext:u}=this.pieceMsg,d=i-1;if(this.bufArr[d]?(this.logger.warn(`syn bufArr ${n} already has ${d} size ${r.byteLength}`),this.bufArr[d]=r):(s?this.p2pLoaded+=r.byteLength:this.httpLoaded+=r.byteLength,this.emit(e.SYN_PROGRESS,{total:h,loaded:this.p2pLoaded+this.httpLoaded,first:!this.firstReceived,segId:n,sn:o}),this.firstReceived=!0,this.bufArr[d]=r,t?this.reverseOffset=d:this.forwardOffset=d,this._notifyStreamListeners(t,r,d)),this.forwardOffset!==this.reverseOffset-1)return!0;this.rangeRequesting||(this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0)),clearTimeout(this.timer),this._notifyStreamListenersRemain();const c=performance.now()-this.timeStart,f=h/c;let g=a.h.concat(this.bufArr);const p=g.byteLength;if(p===h){if(this.alreadyOutput)return!1;this.alreadyOutput=!0,this._abortLoading();let t=g.buffer;const i=new X(o,n,t,this.getFromPeerId(),l,u);this.emit(e.SYN_OUTPUT,i,{speed:f,time:c,p2p:this.p2pLoaded,http:this.httpLoaded})}else{this.logger.error(`${n} expectedSize ${h} != byteLength ${p} forward ${this.forwardOffset} reverse ${this.reverseOffset}`);for(let e=0;e<this.bufArr.length;e++)this.logger.error(`piece ${e} size ${this.bufArr[e].byteLength}`);this.emit(e.SYN_ERROR,this.pieceMsg,Zt),this._disconnectPeers()}}_disconnectPeers(){[this.forwardPeer,this.reversePeer].forEach((t=>{t&&t.emit(e.DC_ERROR,!0)}))}_checkPieceSize(e){const{size:t,seg_id:i,sn:r}=this.pieceMsg;return!e||!t||e===t||(this.logger.warn(`checkPieceSize ${i||r} size not match ${t} ${e}`),!1)}_setupPeer(t,i,r){const{logger:s}=this;0===this.timeStart&&(this.timeStart=performance.now()),r&&!this.pieceMsg.size&&(this.pieceMsg.size=r);const n=(i,r,n,a,o,l)=>{if(this.destroyed)return;if(!this._validateMsg(i,l.level,r))return void s.error(`onPieceData ${r||i} size ${n.byteLength} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(a<this.pieceMsg.attachments&&n.byteLength!==u)return s.error(`${r} dataSn ${a} size is ${n.byteLength}`),this.emit(e.SYN_ERROR,this.pieceMsg,Zt),void this._disconnectPeers();const{reverse:h}=l;this._receivePacket(h,a,n)&&!this.waitingRemain&&!this.rangeRequesting&&this.deadline>0&&this._shouldSwitch()&&(s.warn("should switch to http"),clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._handleTimeout(!1,!1))},a=e=>{if(this.destroyed)return;const{attachments:i,size:r,sn:n,level:a,seg_id:o,ext:l={}}=e;let h=!0;(r<=999||!this._validateMsg(n,a,o))&&(s.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),h=!1),this._checkPieceSize(r)||(h=!1);const{ext:u}=this.pieceMsg;if(u&&l.hash&&u.hash&&l.hash!==u.hash&&(this.logger.warn(`syn ${o||n} hash not match ${l.hash} ${u.hash}`),h=!1),!h)return t.cancelDownload(n,a,o),void this.deletePeer(t);0===this.bufArr.length?(this.pieceMsg={...this.pieceMsg,seg_id:o,size:r,attachments:i,ext:l},this.reverseOffset=i,this.bufArr=new Array(i),this.timeReceivePiece=performance.now()):!this.pieceMsg.ext.hash&&l.hash&&(this.pieceMsg.ext.hash=l.hash)},o=e=>{this.destroyed||this.deletePeer(t)},l=()=>{this.destroyed||this.deletePeer(t)},h={onPieceData:n,onPiece:a,onPieceNotFound:o,onPieceAbort:l};i?this.reverseEvents=h:this.forwardEvents=h,t.on(e.DC_PIECE_DATA,n).once(e.DC_PIECE,a).once(e.DC_PIECE_NOT_FOUND,o).once(e.DC_PIECE_ABORT,l)}_shouldSwitch(){const e=u,t=this.pieceMsg.size-e*this.loadedPackets;return this.coordinator.shouldSwitchToHttp(t,this.deadline,this.p2pSpeed,e,this.httpLoadTime)}_startTimer(e,t=!0){this.timer=setTimeout(this._handleTimeout.bind(this,t),e)}get loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(t=!1,i=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:r,size:s,attachments:n}=this.pieceMsg;if(!s||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${r} url ${this.url}`),void this.emit(e.SYN_ERROR,this.pieceMsg,Zt);if(t&&this.timeReceivePiece>0&&n){this.logger.warn(`syn ${this.loadedPackets} of ${n} packets loaded`);const e=this.httpLoadTime>3e3?3e3:this.httpLoadTime;if(this.shouldWaitForRemain(e))return this.waitingRemain=!0,this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}if(i){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const i=e.currentLoadSpeed(),r=t.currentLoadSpeed();return i===r?e.timeSendRequest-t.timeSendRequest:i-r})).shift();e&&e.loadtimeout()}if((this.rangeSupported||!this.hasPartialBuffer)&&this.url)return this._cancelP2p(!0),this._loadRemainBufferByHttp();this._notifyStreamListenersAbort(),this.emit(e.SYN_ERROR,this.pieceMsg,ii)}shouldWaitForRemain(e){return!this.isEmpty&&this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed,i=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${i}`),t>=i}minRequiredSpeed(e){let t=0;return[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(t+=e.loadedBytes())})),(this.pieceMsg.size-t)/e}get p2pSpeed(){let e=0;return[this.forwardPeer,this.reversePeer].forEach((t=>{t&&(e+=t.currentLoadSpeed())})),e}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull&&e!==t?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}getStreamInfo(e){const t=e?this.reverseBufList:this.forwardBufList;let i,r;return t.length<this.pieceMsg.attachments?(i=this.isFull?"WaitPartialDouble":"WaitPartialSingle",r=1):(i=this.isFull?"SynFullDouble":"SynFullSingle",r=0),{from:i,incompletes:r,bufferList:t}}_loadRemainBufferByHttp(){if(this.rangeRequesting||this.alreadyOutput)return;const{size:t,seg_id:i}=this.pieceMsg,{logger:r}=this,s=this.rangeEnd>0?this.rangeEnd-1:0;let n=this.forwardOffset;const a=performance.now();this.rangeRequesting=!0;let o=le(n,this.reverseOffset,t,this.rangeStart,s);const l=o.rangeEnd-o.rangeStart;r.info(`listeners ${this.streamListeners} continue download ${i} from ${this.url} range: ${o.rangeStart}-${o.rangeEnd}`),this.hasPartialBuffer||(o={});const u=new ai({xhrSetup:this.xhrSetup});this.httpLoader=u;let d={url:this.proxied?f(this.url,h,!0):this.url,...o};let c,g=n+1;const p={onUpdate:(t,i,s)=>{if(!this.destroyed){if(s)return r.warn("httpLoader aborted"),void(this.alreadyOutput||this.emit(e.SYN_ERROR,this.pieceMsg,ei));if(i){const e=c/(performance.now()-a);this.coordinator.addHttpSpeed(e),this.httpLoader=void 0}this.bufArr[g]||this._receivePacket(!1,g+1,t,!1),g++}},onBodyStart:(t,s)=>{if(0===s&&r.warn(`range request fileSize ${s}`),this.destroyed)return;const{size:n}=this.pieceMsg;if(c=t,t!==n||0!==s&&s!==n){let i=!1;s>0&&s!==n?(r.error(`onBodyStart fileSize ${s} != ${n}`),i=!0):t!==l&&(r.error(`onBodyStart size ${t} != expectedSize ${l}`),i=!0),i&&"{}"!==JSON.stringify(o)&&this.emit(e.SYN_ERROR,this.pieceMsg,ei)}else r.warn(`syn range request ${i} resp whole ts`),g=0},onError:t=>{this.destroyed||(r.error(`httpLoader error ${t.text}`),this.emit(e.SYN_ERROR,this.pieceMsg,ei))},onTimeout:()=>{this.destroyed||(r.warn("httpLoader timeout"),this.emit(e.SYN_ERROR,this.pieceMsg,ti))}};u.load(d,{timeout:15e3},p)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class ui extends hi{constructor(e,i,r,s,n,a=!1,o){super(e,i,a,o),this.pieceMsg={event:t.DC_PIECE,sn:r,level:s,seg_id:n},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,i){const{sn:r,seg_id:s,attachments:n}=this.pieceMsg,a=e&&0===i||!e&&i===n-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;e?this.reverseBufList.push(t):this.forwardBufList.push(t),a&&(this.forwardBufList.push([...this.reverseBufList].reverse()),this.reverseBufList.push([...this.forwardBufList].reverse()));for(let e of o){const{handler:i}=e;i(r,s,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,i){return(!this.pieceMsg.seg_id||i===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}}class di{constructor(){this.meanHttpSpeed=0,this.loaderHttpSpeed=0}addHttpSpeed(e){this.meanHttpSpeed=this._cal(this.meanHttpSpeed,e)}addLoaderHttpSpeed(e,t){t&&e&&(this.loaderHttpSpeed=this._cal(this.loaderHttpSpeed,t/e))}getMeanTimeToLoaded(e){return this.loaderHttpSpeed?e/this.loaderHttpSpeed:500}shouldSwitchToHttp(e,t,i,r,s){if(this.meanHttpSpeed<=0)return!1;if(i>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*s>=e)return!1;return((s+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-i)*i<r}_cal(e,t){return.4*e+.6*t}}class ci extends Qt{constructor(e,t){super(e,t),this.prefetchOnly=t.prefetchOnly,this.bitset=new qt(t.live||!1),this.bitCounts=new jt,this.requestingMap=new Jt,this.segmentBuilderMap=new Jt,this.allowP2pLimit=t.httpLoadTime+1.5,this.playlistInfo=new Map,this.gotPlaylist=!1,this.targetPeers={},this.sequential=!0,this.coordinator=new di,this.loadingSegId="",this.loadingSN=0,this.currPlaySN=0,this.currLostSN=-1,this.nextLostSN=-1,this.config.live?this.maxPrefetchCount=10:(this.maxPrefetchCount=150,this.startCheckPeersTimer())}handshakePeer(e){this._setupDC(e);const{asn:t,country:i}=this.engine.fetcher.announceInfo;e.sendMetaData(this.bitset.allArray(),!0,this.peersNum,{asn:t,country:i},this.isMobileNet)}_receiveDCHave(e,t,i,r){this.bitset.has(e,t)||this.bitCounts.incre(e,t)}_setupDC(e){super._setupDC(e),e.on(t.DC_HAVE,(t=>{if(e.bitset&&t.sn>=0){const{sn:i,level:r,complete:s,seg_id:n,size:a}=t,o=s?Kt.COMPLETE:Kt.PARTIAL_FORWARD;e.bitset.add(i,r,n,o,a),this._receiveDCHave(i,r,n,e),e.isAvailableUrgently&&this._handleDCHave(e,i,r,n,a,o)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:i,level:r,seg_id:s,size:n}=t;e.bitset.hasCompleteOr(i,r,Kt.PARTIAL_REVERSE)||e.bitset.add(i,r,s,Kt.PARTIAL_REVERSE,n),this._receiveDCHave(i,r,s,e),e.isAvailableUrgently&&this._handleDCHave(e,i,r,s,n,Kt.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:i,level:r}=t;e.bitset.has(i,r)&&(e.bitset.delete(i,r),this.bitCounts.decre(i,r))})).on(t.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=7||this.requestingMap.has(de(e.sn,e.level))&&this.notifyAllPeers(e.sn,e.level,e.seg_id,e.size,e.reverse?Kt.PARTIAL_REVERSE:Kt.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:i,level:r}=t,s=de(i,r);this.removeStreamListener(s,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:i,level:r}=t;e.bitset.delete(i,r),this.bitCounts.decre(i,r),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:i}=this,{sn:r,level:s,reverse:n}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(r));const o=()=>{this.bitset.delete(r,s),e.sendPieceNotFound(r,a,{level:s}),this._broadcastLost(r,a,s,e)},l=await this.bufMgr.getSegById(a),h=de(r,s),u=this.requestingMap.get(h);let d=!1;u&&u.isDownloading&&(d=!0);const c=this.segmentBuilderMap.get(h);if(l)if(i.info(`found seg ${a} from bufMgr`),l.level===s){let t="SegmentStore"===this.bufMgr.name?"Disk":"Cache";l.ext.from&&l.ext.from.length<2500&&(t=`${l.ext.from}-${t}`),e.sendBuffer(l.sn,l.segId,l.data,{from:t,level:l.level,reverse:n,hash:l.ext.hash})}else o();else if(!n&&c)i.info(`peer request ${r} wait from builder, sent ${c.bufferList.length}`),R(e,c,c.pieceMsg,c.bufferList,c.source,1);else if(d){i.info(`syn had ${u.loadedPackets} packets, wait remain from upstream ${u.getFromPeerId()}`);const t={...u.pieceMsg,reverse:n},{from:r,incompletes:s,bufferList:a}=u.getStreamInfo(n);R(e,u,t,a,r,s)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new qt(this.config.live,t.field);for(let e in t.field){const i=Number(e);if(i<0)continue;t.field[i].forEach((e=>{this.bitset.has(e,i)||this.bitCounts.incre(e,i)}))}this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e)}}peersHas(e,t){return this.bitCounts.has(e,t)}deletePeer(e){if(this.peerManager.hasPeer(e.remotePeerId)&&e.bitset){const t=e.bitset.allArray();for(let e in t){const i=Number(e),r=t[i];r&&r.forEach((e=>{this.bitCounts.decre(e,i)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,i,r){const{logger:s,config:n}=this;let a=1e3*(r-n.httpLoadTime);this.allowP2pLimit=n.httpLoadTime+1.5,s.info(`bufferedDuration ${1e3*r} remainLoadTime ${a} allowP2pLimit ${1e3*this.allowP2pLimit}`);const o=de(e,t),l=this.requestingMap.get(o);if(l){const n=l.segId;if(n&&n!==i)return s.warn(`syn segId ${n} not match ${i}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,i,r);if(!l.shouldWaitForRemain(a)){if(s.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const r=this.peerManager.getPeersOrderByWeight();let[n,o,h]=$t(r,e,t,i);return!!this.setTargetPeersFromGroup(l,n,o,h)||(l.hasReversePeer||l.hasPartialBuffer||a>1e3*(this.allowP2pLimit+1))&&this.httpRangeSupported}return s.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t,i,r)}_searchAvailablePeers(e,t,i,r){if(r<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const s=this.peerManager.getPeersOrderByWeight(),[n,a]=Vt(s,e,t,i);return this.targetPeers={forwardPeer:n,reversePeer:a},[n,a].some((e=>!!e))}reportTraffic(e,t,i){const{fetcher:r}=this.engine;r&&(e>0&&r.reportFlow(e),t>0&&r.reportDCTraffic(t,i))}notifyAllPeers(e,t,i,r,s=Kt.COMPLETE){if(!i)return void this.logger.error("segId is required");if(this.downloadOnly)return;const{live:n}=this.config;if(this.bitset.has(e,t,s))return;const a=((e,t,i)=>`${e}-${t}-${i}`)(e,t,s);let o;s!==Kt.PARTIAL_REVERSE&&(o=s===Kt.COMPLETE);const l=this.requestingMap.get(de(e,t));for(let h of this.getPeers())l&&l.hasPeer(h)||h.notifySet.has(a)||h.bitset.hasCompleteOr(e,t,s)||h.uploading||(h.sendMsgHave(e,i,{level:t,reverse:s===Kt.PARTIAL_REVERSE,complete:o,size:r}),h.notifySet.add(a),n&&T(h.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:i}=this;if(!this.hasPeers)return;const r=t.live;if(this.fragLoading)return void e.info("loading urgently, skip prefetch");const{currentLevel:s}=i;if(0===this.bitCounts.size(s))return;if(!r&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;let n=this.peerManager.getPeersOrderByWeight();if(0===n.length)return;let a=0,{prefetchNum:o,endSN:l,startSN:h}=t;if(!r){const t=this.requestingMap.size,i=this.requestingMap.activePeers;if(i>=o)return void e.warn(`requestingMap size ${t} activePeers ${i}`);o-=i}if(this.getBufferedDuration()<this.allowP2pLimit){if(!r)return;o=1}let u=0,d=this.loadingSN+1;if(this.prefetchOnly&&(d+=2),!r)if(this.loadingSN>=l&&!this.bufMgr.overflowed)d=h;else{const e=Math.min(...n.filter((e=>e.endSN>=d)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;d<e&&(d=e)}for(;a<o&&u<this.maxPrefetchCount&&(r||!(d>l))&&!(r&&d>this.loadingSN+2);){if(this.bitset.has(d,s)){d++;continue}const t=de(d,s),i=this.requestingMap.get(t);if(this.bitCounts.has(d,s)){if(i){for(let e of n)if(e.bitset.has(d,s)){const{state:t,segId:r,size:n}=e.bitset.getObj(d,s);if(this._trySetPeerForSyn(i,e,r,d,s,n,t))break}}else{let i=[null,null];if(r)i=Vt(n,d,s,void 0,!0);else for(let e of n)if(e.bitset.has(d,s)){const t=e.bitset.getState(d,s);let r;r=t===Kt.COMPLETE?0===p(0,1):t===Kt.PARTIAL_REVERSE,i[r?1:0]=e;break}if(i.some((e=>!!e))){const r=new ui(this.coordinator,this.logger,d,s,void 0,this.httpRangeSupported);this._setupSynthesizer(r),this.requestingMap.set(t,r),i.forEach(((t,i)=>{if(t&&a<o){const n=1===i,o=t.bitset.getSize(d,s);r.setPeer(t,n,o)&&(a++,t.requestDataBySN(d,!1,{level:s,reverse:n}),e.info(`request prefetch ${d} level ${s} from peer ${t.remotePeerId} downloadNum ${t.downloadNum} reverse ${n}`))}}))}}n=this.peerManager.getPeersOrderByWeight()}if(u++,d++,0===n.length)break}this.loadedPeerNum=a}onBufferManagerLost(e,t,i,r){this.currLostSN=e,i&&(this.nextLostSN=i),this.bitset.delete(e,r),this.bitCounts.delete(e,r)}onBufferManagerSegAdded(e){const{sn:t,segId:i,level:r,size:s}=e;this.notifyAllPeers(t,r,i,s),this.updateLoaded(t,r,i)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[i,r]of this.requestingMap.internalMap){const s=i.split("-"),n=Number(s[1]),a=Number(s[0]);r.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),r.deletePeer(t),this.bitCounts.decre(n,a),t.bitset.delete(n,a))}}updateLoaded(e,t,i){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,i,Kt.COMPLETE),this.bitCounts.delete(e,t),this.requestingMap.delete(de(e,t)),this.config.live&&this.checkPeers())}broadcastPlaylist(e,t){if(!this.config.live)return;const i=function(e){const t=e.split("\n");let i=0,r=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){i=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&r++;return i+r-1}(t);if(!this.isMobileNet)for(let r of this.getPeers())r.sendMsgPlaylist(e,t,i);this.playlistInfo.set(e,{seq:i,data:t})}async getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t,data:i}=this.playlistInfo.get(e),r=()=>{for(let i of this.getPeers()){const r=i.getLatestPlaylist(e,t);if(r)return this.playlistInfo.set(e,r),this.gotPlaylist=!0,r}return null};let s=r();return!s&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await v(240),this.gotPlaylist=!1,s=r()),s}getBufferedDuration(){const{config:e}=this;let{media:t,currentSrc:i}=this.engine;if(!t||t.src!==i&&0===t.currentTime){if(this.logger.info("try get video element"),t=ae(this.config.mediaElem,i),!t)return 4;this.engine.media=t}let r=function(e){let t=0,i=e.currentTime,r=e.buffered;for(let e=r.length-1;e>=0;e--)if(i>=r.start(e)&&i<=r.end(e)){t=r.end(e)-i;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return r}destroy(){super.destroy(),this.requestingMap.clear(),this.segmentBuilderMap.clear(),this.engine.removeAllListeners(t.MEDIA_REBUFFER)}clearCache(){"SegmentStore"===this.bufMgr.name?this.engine.emit(t.BM_FATAL_ERROR):this.bufMgr.clear(),this.bitset.clear()}async _handleSynOutput(e,t,i,r,s,n){if(this.logger.info(`syn output ${e} http ${t} p2p ${i} time ${r}`),!this.config.validateSegment(e,new Uint8Array(s)))return!1;if(n){const t=await w(s);if(t&&t!==n)return this.logger.warn(`${e} computedHash ${t} != hash ${n}`),!1}return!0}_handleSynError(e,t,i,r){const{logger:s,config:n}=this;s.warn(`SYN_ERROR ${t}-${i} code ${r}`),r!==Zt&&e.hasPartialBuffer&&i>this.loadingSN?s.warn(`syn abort ${i} with partial buffer`):this.requestingMap.delete(de(i,t)),n.live&&this.checkPeers()}_notifySynthesizer(e,t,i,r,s,n,a=!0){const o=this.requestingMap.get(de(i,r));o&&this._trySetPeerForSyn(o,e,t,i,r,s,n,a)}_trySetPeerForSyn(e,t,i,r,s,n,a,o=!1){const{logger:l}=this,h=e.segId;if(i&&h&&i!==h)return l.warn(`notifySynthesizer segId ${i} not match ${h}`),!1;if(e.isFull)return!0;if(e.isAlmostDeadline)return!0;if(e.isEmpty){if(e.hasForwardBuffer&&c()){if(e.setReversePeer(t,n))return u(!0,o),!0}else if(e.hasReverseBuffer&&d()&&e.setForwardPeer(t,n))return u(!1,o),!0}else if(!e.hasForwardPeer&&d()){if(e.setForwardPeer(t,n))return u(!1,o),!0}else if(!e.hasReversePeer&&c()&&e.setReversePeer(t,n))return u(!0,o),!0;function u(e,n){n?t.requestDataById(i,r,!0,{level:s,reverse:e}):t.requestDataBySN(r,!1,{level:s,reverse:e})}function d(){return a===Kt.PARTIAL_FORWARD||a===Kt.COMPLETE}function c(){return a===Kt.PARTIAL_REVERSE||a===Kt.COMPLETE}return!1}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:i}=this.config;t||i||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,i={level:e};if(t&&!this.config.live){const{currentTime:e}=t;i.pos=Math.round(e)}return i}checkSynthesizer(e,t){const i=de(e,t),r=this.requestingMap.get(i);r&&(0===r.streamListeners?(this.logger.info(`destroy syn ${i} without listeners`),this.requestingMap.delete(i)):this.logger.info(`keep syn ${i} with listeners`))}setupSynForLoad(e,t,i,r,s){const{forwardPeer:n,reversePeer:a}=this.targetPeers,o=de(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(r):(l=new ui(this.coordinator,this.logger,e,t,i,this.httpRangeSupported,r),this._setupSynthesizer(l),this.requestingMap.set(o,l)),l.prefetchTimeout&&s<1e3*this.allowP2pLimit&&!n&&!a)return l.setTimeout(0);s>700&&(n&&l.setForwardPeer(n)&&n.requestDataById(i,e,!0,{level:t}),a&&l.setReversePeer(a)&&a.requestDataById(i,e,!0,{level:t,reverse:!0})),l.setTimeout(l.isEmpty?0:s,!0)}async disconnectLoadingPeer(e,t){let i=e;if(!i){const e=await this.bufMgr.getSegById(this.loadingSegId);e&&e.fromPeerId&&(i=e.fromPeerId)}let r=!1;return i&&(this.logger.warn(`disconnect loading peer ${i}`),i.split(":").forEach((e=>{if(t&&e===t)return;r=!0;const i=this.peerManager.getPeer(e);i&&i.close(!0)}))),r}}class fi{constructor(t,i,r,s){this.bufferList=[],this.streamListeners=[],this.finished=!1,this.packetSize=u,this.attachments=s%this.packetSize==0?s/this.packetSize:Math.floor(s/this.packetSize)+1,this.pieceMsg={event:e.DC_PIECE,attachments:this.attachments,seg_id:r,sn:t,level:i,size:s,reverse:!1},this.sink=(0,a.h)(0),this.source="HttpStream"}receiveBytes(e,t){e.byteLength&&(this.sink=a.h.concat([this.sink,e]),this.bufferList.push(e),t&&(this.finished=!0),this._notifyStreamListeners(e))}getCompleteBuffer(){return this.sink.buffer}destroy(){this.finished||this._notifyStreamListenersAbort()}addStreamListener(e,t,i){this.streamListeners.push({handler:i,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:i}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((r=>r.peerId!==e||(r.handler(t,i,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let i of this.streamListeners){const{handler:r}=i;r(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:i}=this.pieceMsg;for(let r of this.streamListeners){const{handler:s}=r;s(t,i,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const gi=/^age:\s*[\d.]+\s*$/im;function pi(e,t,i,r){if(!e)return!1;const s=r&&r.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}const vi=class{constructor(e){this.xhrSetup=e&&e.xhrSetup||null,this.stats=D(),this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.loader=null}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);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=s&&Number.isFinite(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.tfirst=i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,n="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){const s=n||t.response;if(null!=s){i.tload=i.loading.end=Math.max(self.performance.now(),i.loading.first);const n="arraybuffer"===t.responseType?s.byteLength:s.length;if(i.loaded=i.total=n,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(i,e,s,t),!this.callbacks)return;const o={url:t.responseURL,data:s,code:r};return void this.callbacks.onSuccess(o,i,e,t)}}const a=s.loadPolicy.errorRetry;pi(a,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(a):this.callbacks.onError({code:r,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(pi(e,this.stats.retry,!0))this.retry(e);else{const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=function(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}(e,i.retry),i.retry++,this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&gi.test(this.loader.getAllResponseHeaders())){const 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}};const mi=class extends ci{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=I(t.segmentBypass)?t.segmentBypass:()=>!1,!0===t.httpStreamEnabled?this.streamEnabled=ni():this.streamEnabled=!1}async handleGetMediaData(e,i){const{logger:r,engine:s,config:n}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return r.warn(`cannot get frag ${a}`),i.postMessage({action:t.SW_GET_MEDIA});s.currentLevelIndex=l.level;const{sn:h,level:u}=l,d=this.config.segmentId(String(u),h,a,o);if(s.segmentLoadCount++,this.segmentBypass(a,l.tagList))return r.info(`bypass frag ${a}`),i.postMessage({action:t.SW_GET_MEDIA});if(s.segmentLoadCount<n.startFromSegmentOffset)return this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout,!1);const c=d===this.loadingSegId;if(c&&(r.warn(`duplicate request ${d}`),this.prefetchOnly))return i.postMessage({action:t.SW_GET_MEDIA});this.loadingSN=h,s.bufMgr&&(s.bufMgr.loadingSN=h),this.loadingSegId=d;const f=await this.bufMgr.getSegById(d);if(f)return l.loaded=f.size,l.fromPeerId=f.fromPeerId,r.info(`bufMgr found seg sn ${h} segId ${d} size ${l.loaded}`),s.emit(t.FRAG_LOADED,{url:a,sn:h,level:u,segId:d,loaded:l.loaded,duration:l.duration,byP2p:!0,fromPeerId:f.fromPeerId}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:f.data}});if(this.fragLoading=!0,this.prefetchOnly)return r.info(`prefetchOnly, skip p2p load ${d}`),this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout);let g=this.getBufferedDuration();g>this.fragloadTimeout&&(g=this.fragloadTimeout),r.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const v=de(h,u);if(this.resolveMap.has(h)||c){let e=this.requestingMap.get(v);if(e||c){e&&this.httpRangeSupported&&(r.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let s=setTimeout((()=>{r.info(`notify seg ${h} timeout`),s=-1,i.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{s<0||e&&e.level===u&&(clearTimeout(s),r.info(`notify seg ${e.sn}`),i.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else r.warn(`${h} is requesting, fallback`),i.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,u,d,g)){await this._loadFragByP2p(l,i,h,d,a,u,o,p)||(r.warn(`p2p timeout switch to http load ${d}`),this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,i,r,s,n,a,o=!0){const{sn:l,level:u}=e,d=de(l,u),c=f(s,h,!0),g={},p=this.streamEnabled&&o?new ai(g):new vi(g);let v={url:c,responseType:"arraybuffer",...L(n)};const m={timeout:a,loadPolicy:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4}},E={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,i.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,i.postMessage({action:t.SW_GET_MEDIA})},onSuccess:async(n,a)=>{this.fragLoading=!1;const{data:o}=n;let h=a.loading.end-a.loading.start;if(this.logger.info(`HTTP loaded ${r} time ${h} speed ${o.byteLength/h}`),!await this.bufMgr.hasSegOfId(r)){const e=y(o).buffer,t=new X(l,r,e,"",u);await this.bufMgr.putSeg(t),this.reportTraffic(o.byteLength,0,0)}this.segmentBuilderMap.delete(d),e.segId=r,e.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:s,sn:l,level:u,segId:r,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:o}})}};if(this.streamEnabled&&o){let e;E.onBodyStart=t=>{!e&&t>0&&(this.notifyAllPeers(l,u,r,t,Kt.PARTIAL_FORWARD),e=new fi(l,u,r,t),this.segmentBuilderMap.has(d)||this.segmentBuilderMap.set(d,e))},E.onUpdate=(t,i,s)=>{if(s)return this.logger.warn(`loadFragByHttp ${r} aborted`),void this.segmentBuilderMap.delete(d);e&&e.receiveBytes(t,i)}}p.load(v,m,E)}async _loadFragByP2p(e,i,r,s,n,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${r} segId ${s} level ${a}`);const u=await this.load(r,s,a,n,o,l);if(u&&u.data){const{data:o,fromPeerId:l,size:d}=u;if(h.info(`p2p loaded segId ${s} level ${a} size ${o.byteLength}`),!await this.bufMgr.hasSegOfId(s)){const e=new X(r,s,o,l,a,u.ext);h.info(`bufMgr putSeg ${r} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:n,sn:r,level:a,segId:s,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:o,size:d}}),!0}h.warn(`P2P timeout load segId ${s}`);const d=await this.bufMgr.getSegById(s);return!!d&&(this.fragLoading=!1,h.info(`already loaded seg sn ${r} segId ${s}`),i.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:d.data}}),!0)}notifySWMessage(e,i,r){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(i,r);else this.logger.warn(`unknown action ${e}`)}_getFrag(e,t){return t&&(e=`${e}|${t}`),this.fragMap.get(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(){if(!this.engine)return;const{media:e,targetDuration:t}=this.engine;!this.config.live&&e&&t&&(this.currPlaySN=Math.ceil(e.currentTime/t))}load(e,t,i,r,s,n){const{logger:a,config:o}=this;let l={...L(s),proxied:!0,url:r,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,i,t,l,n);const h=new Promise((r=>{const s={resolve:r,sn:e,level:i,segId:t};this.resolveMap.set(e,s)}));return this.targetPeers={},h}isCritical(){return this.resolveMap.has(this.loadingSN)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,i)=>{const{config:r,logger:s}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:u,time:d,http:c,p2p:f}=i,g=this.resolveMap.has(a);g&&(this.fragLoading=!1);const p=await this._handleSynOutput(n,c,f,d,o,h.hash),v=e.getFromPeerId();if(p)if(this.bitset.has(a,l)||this.reportTraffic(c,f,u),g){s.info(`receive criticalSeg seg_id ${n}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:f>0?v:void 0,ext:h})}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t));else{if(s.error(`segment ${n} validate failed`),g){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(de(a,l)),this.disconnectLoadingPeer(v)}})).on(t.SYN_ERROR,((t,i)=>{const{sn:r,level:s}=t;if(this.resolveMap.has(r)){const e=this.resolveMap.get(r);this.resolveMap.delete(r),e.resolve()}this._handleSynError(e,s,r,i)}))}_handleDCHave(e,t,i,r,s,n){this._notifySynthesizer(e,r,t,i,s,n,this.resolveMap.has(t)),this.config.live&&W((()=>{this.checkPeers()}))}},yi="2.13.0";class Ei extends It{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},i=null){super(e,i),this.swSupported=self.isSecureContext,this.levels=[],this.bypassLevels=[],this.currentLevelIndex=0,this.currentSrc="",this.swVersion="",this.media=ae(this.config.mediaElem),this.workerKeepAliveInterval=null,this.fragMap=new Map,this.engineName=Ei.name,Ei.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),i&&(i.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),i.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:r,signalId:s,browserInfo:n}=this.setup();if(this.onLevelLoaded=e=>{const{config:i}=this,a=e.live;i.live=a,this.segmentLoadCount=0,this.targetDuration=e.averagetargetduration,this.browserInfo={...n,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${r(this.currentSrc)}|${s}[${ee.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsSwP2pEngine"),o.info(`engine version: ${se.version} hls-proxy version: ${this.swVersion}`),o.info(`channel ${this.channel}`),a||(i.startSN=e.startSN,i.endSN=e.endSN,o.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(t.LEVEL_LOADED,this.onLevelLoaded)},0===this.config.httpLoadTime&&(this.config.live?this.on(t.LEVEL_LOADED,(e=>{const{fragments:t,averagetargetduration:i,startSN:r}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,i,r)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,i)=>{this.multiBitrate=e.length>1,this.currentSrc=i,this.off(t.MANIFEST_PARSED,this.onManifestParsed)},this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{this.curTsUri=e;const{config:t}=this;!this.rangeTested&&t.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,t.logger&&t.logger.info(JSON.stringify({engine:this.engineName,...this.browserInfo}))),this.segmentLoadCount>=t.startFromSegmentOffset&&this.resumeTracker()},this.on(t.FRAG_LOADED,this.onFragLoaded),this.swSupported){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:i,data:r}=e.data;if(!i)return;if(i===t.SW_DEBUG){const{level:e,text:t}=r;return void(this.logger&&this.logger[e](`hls-proxy ${this.swVersion}: ${t}`))}const s=e.ports[0];if(s){if(this.logger&&this.logger.info(`engine onmessage action ${i}`),s.postMessage({action:i,pong:!0}),!this.p2pEnabled||!r)return s.postMessage({action:i});if(i===t.SW_GET_PLAYLIST)this.handleGetPlaylist(r,s);else{if(!this.scheduler)return s.postMessage({action:i});this.scheduler.notifySWMessage(i,r,s)}}else this.logger&&this.logger.error(`sender not found in action ${i}`)}}this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}watchRebuffering(e){this.offEventRebuffer=function(e,t){let i=null;const r=()=>{i||(i=setTimeout((()=>{t()}),2500))},s=()=>{null!=i&&(clearTimeout(i),i=null)};return e.addEventListener("waiting",r),e.addEventListener("playing",s),()=>{e.removeEventListener("waiting",r),e.removeEventListener("playing",s)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,i,r=!1){const{config:s,logger:n}=this,{url:a,redirectedUrl:o,text:l,ver:u}=e;return this.swVersion=u,-1===function(e,t){for(var i=e.split("."),r=t.split("."),s=0;s<Math.max(i.length,r.length);s++){var n=parseInt(i[s]||0),a=parseInt(r[s]||0);if(n<a)return-1;if(n>a)return 1}return 0}(u,yi)?(console.warn(`hls-proxy.js version should >= ${yi}`),i.postMessage({action:t.SW_GET_PLAYLIST})):this.bypassLevels.indexOf(b(a))>=0?(console.warn("bypass audio track"),n&&n.warn("bypass audio track"),i.postMessage({action:t.SW_GET_PLAYLIST})):(i.postMessage({action:t.SW_GET_PLAYLIST,data:{active:!0,debug:n&&n.isDebugLevel,text:l,redirectedUrl:o}}),this._parsePlaylist(l,b(a),o,r),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!s.live&&t()){const i=new URL(e.scope);this.pathname=i.pathname+h;const r=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;n&&(n.error(t),n.report(t,"SWKeepAlive",this.peerId,"2.16.3"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,i)=>{fetch(`${e}/keepalive/`).then((e=>{if(e.ok)return e.text();throw new Error("keepalive failed")})).then((e=>{if(""!==e.trim())throw new Error("not valid keepalive response");t()})).catch((e=>{i(e)}))}))).catch((e=>{r(e)})):r("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,i,r,s=!1){const n=i;r&&(i=r);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let r=0;const o=Gt.parseLevelPlaylist(e,i);this.levels.length>0?(r=this.levels.indexOf(b(o.url)),-1===r?(this.restartP2p(),this.currentSrc=n,r=0):this.currentLevelIndex=r):(""!==this.currentSrc&&n!==this.currentSrc&&this.restartP2p(),this.currentSrc=n,this.levels=[b(i)]),this.emit(t.LEVEL_LOADED,o),a.live&&S(this.fragMap,200),o.fragments.forEach((e=>{e.level=r;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const i=e.byteRange;2===i.length&&(t=`${t}|bytes=${i[0]}-${i[1]-1}`),this.fragMap.set(t,e)})),!s&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(b(i),e)}else{const r=Gt.parseMasterPlaylist(e,i);""!==this.currentSrc&&this.restartP2p(),r.length>0&&(r.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=r.map((e=>b(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{Gt.parseMasterPlaylistMedia(e,i,t).forEach((e=>{e.url&&this.bypassLevels.push(b(e.url))}))}))),this.emit(t.MANIFEST_PARSED,r,n)}this._setupSegmentId()}async handleGetPlaylist(e,i){const{config:r,logger:s,scheduler:n}=this,{url:a}=e,o=b(a);if(n&&n.playlistInfo.has(o)){const t=await n.getPlaylistFromPeer(o);if(t&&t.data){const{data:r,seq:n}=t;return s&&s.info(`got playlist from peer seq ${n}`),void this.handlePlaylist({text:r,...e},i,!0)}}try{const{text:r,redirectedUrl:n}=await this._loadPlaylistByHttp(a);if(!function(e){return 0===e.indexOf("#EXTM3U")}(r))return s&&s.warn(`not m3u8: ${r}`),i.postMessage({action:t.SW_GET_PLAYLIST});this.handlePlaylist({text:r,redirectedUrl:n,...e},i)}catch(e){i.postMessage({action:t.SW_GET_PLAYLIST})}}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let e="sw is not supported";return E||(e="https is required when using ServiceWorker",console.warn(e)),Promise.reject(e)}return this.media=ae(t.mediaElem),this.media||e&&e.warn("no video element found"),Ri.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,i)=>{const{serviceWorker:r}=navigator;r||i(e),r.getRegistration().then((r=>{r?r.unregister().then(t).catch(i):i(e)}))}))}async _init(e,t){const{logger:i,config:r}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.mediaTimer=setInterval((()=>{const e=()=>this.hlsjs&&this.hlsjs.media;if(this.media){const t=e();t&&this.media!==t&&(this.media=t),clearInterval(this.mediaTimer),this.rubufferTimer=setTimeout((()=>{this.watchRebuffering(this.media)}),15e3)}else this.media=e()||ae(r.mediaElem)}),3e3);let s=new mi(this,r);s.fragMap=this.fragMap;try{await super._init(e,s,t)}catch(e){return void(i&&i.error(e))}s.server=this.fetcher,this.scheduler=s}restartP2p(){this.logger&&this.logger.warn("restart P2P"),this.disableP2P(),this.enableP2P(),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.on(t.FRAG_LOADED,this.onFragLoaded)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this)}disableP2P(){this.logger&&this.logger.warn("disable P2P"),clearInterval(this.mediaTimer),clearTimeout(this.rubufferTimer),this.offEventRebuffer&&this.offEventRebuffer(),this.p2pEnabled&&(this.config.p2pEnabled=this.p2pEnabled=!1,this.tracker&&this.tracker instanceof At&&(this.tracker.stopP2P(),this.tracker=null,this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.trackerTried=!1)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(t.MANIFEST_PARSED),this.removeAllListeners(t.LEVEL_LOADED),this.removeAllListeners(t.FRAG_LOADED),clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null}destroy(){this.swSupported&&(navigator.serviceWorker.onmessage=void 0),super.destroy()}async _loadPlaylistByHttp(e){const t=f(e,h,!0),i=await fetch(t);return{text:await i.text(),redirectedUrl:i.redirected?i.url:void 0}}}const Si=Ei;function Ti(e,t,i="main"){return"main"!==i}function _i(e,t,i){let r,s,n;const a=performance.now();n=a,s=i?n-i.getMeanTimeToLoaded(t):a-200,r=s-100,e.trequest=r,e.tfirst=s,e.tload=n,e.loading={first:r,start:s,end:n},e.loaded=t,e.total=t}const Li=class extends ci{constructor(e,t){super(e,t),this.isHlsjs=!0,this.waitingPeers=0,this.waitingSeg={},this.requestedSet=new Set}updatePlaySN(e){this.currPlaySN=e}load(e,t,i){const{logger:r,config:s}=this;this.context=e;const{rangeStart:n,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:u,level:d}=l;this.callbacks=i,this.criticalSeg={sn:u,level:d,segId:h};let c=e.defaultTimeout-1e3*s.httpLoadTime;const f={rangeStart:Number(n),rangeEnd:Number(a),url:o,httpLoadTime:1e3*s.httpLoadTime,xhrSetup:s.xhrSetup,segId:h,headers:Object.keys(e.headers||{}).length>0?e.headers:void 0};this.setupSynForLoad(u,d,h,f,c),this.targetPeers={}}isCritical(){return!(!this.criticalSeg||this.criticalSeg.segId!==this.loadingSegId)}addPeer(e){super.addPeer(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler")}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,i)=>{const{config:r,logger:s}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:u,time:d,http:c,p2p:f}=i,g=this.criticalSeg&&this.criticalSeg.segId===n,p=await this._handleSynOutput(n,c,f,d,o,h.hash),v=e.getFromPeerId();if(p)if(this.bitset.has(a,l)||this.reportTraffic(c,f,u),g&&this.callbacks){s.info(`receive criticalSeg seg_id ${n}`),this.criticalSeg=null;const{frag:e}=this.context;f>0&&(e.fromPeerId=v,e.loadByP2P=!0),this.callbacks.onSuccess({data:o,url:this.context.url},{},{...this.context,ext:h}),this.callbacks=void 0}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t));else s.error(`segment ${n} validate failed`),g&&this.callbacks.onTimeout({},this.context,null),this.requestingMap.delete(de(a,l)),this.disconnectLoadingPeer(v)})).on(t.SYN_ERROR,((t,i)=>{const{sn:r,level:s}=t;this.criticalSeg&&this.criticalSeg.sn===r&&(this.criticalSeg=null,this.callbacks.onTimeout({},this.context,null)),this._handleSynError(e,s,r,i)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:i,segId:r})=>{this.criticalSeg&&this.criticalSeg.segId===r&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:i},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:i,level:r})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,i&&this.checkSynthesizer(e,r)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:i,level:r})=>{this.fragLoading=!1,i||this.checkSynthesizer(e,r)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,i,r,s,n){this._notifySynthesizer(e,r,t,i,s,n,this.criticalSeg&&this.criticalSeg.segId===r),this.config.live&&W((()=>{this.checkPeers()}))}};class bi extends It{static get name(){return"HlsjsP2pEngine"}constructor(e,t={}){if(super(t,e),!e)throw new TypeError("hlsjs instance is null");"serviceWorker"in navigator&&this._setupSW(),this.config.xhrSetup=e.config.xhrSetup,this.engineName=bi.name,this._onFragLoading=this._onFragLoading.bind(this),this._onFragLoaded=this._onFragLoaded.bind(this),this._onFragChanged=this._onFragChanged.bind(this),this._onHlsError=this._onHlsError.bind(this),this._onLevelUpdated=this._onLevelUpdated.bind(this);const{channelIdMaker:i,signalId:r,browserInfo:s}=this.setup(),n=(t,a)=>{if(!a)return;const{config:o}=this,l=a.details,h=l.live;this._startEngine(this.hlsjs.url,h,s,i,r,l),e.off(this.HLSEvents.LEVEL_LOADED,n)};this._updateHlsEventsHandlers(),e.on(this.HLSEvents.LEVEL_LOADED,n);const a=(e,t)=>{if(!t)return;const{config:i}=this,{fragments:r,averagetargetduration:s,startSN:n}=t.details;i.httpLoadTime=this.determineHttpLoadTime(r,s,n)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,i)=>{this._setupSegmentId();const r=i.levels.length;this.multiBitrate=r>1,e.off(this.HLSEvents.MANIFEST_PARSED,o)};e.on(this.HLSEvents.MANIFEST_PARSED,o),e.on(this.HLSEvents.DESTROYING,(()=>{e.off(this.HLSEvents.LEVEL_LOADED,a),this.destroy()}))}_startEngine(e,t,i,r,s,n={}){const{config:a}=this;a.live=t,this.browserInfo={...i,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${r(e)}|${s}[${ee.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsjsP2pEngine"),this.logger=o,o.info(`channel ${this.channel}`),t||(a.startSN=n.startSN,a.endSN=n.endSN,o.info(`startSN ${n.startSN} endSN ${n.endSN}`)),this._init(this.channel,this.browserInfo)}async _init(e,t){const{logger:i,config:r}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const s=new Li(this,r);try{await super._init(e,s,t)}catch(e){return void i.error(e)}this.hlsjs.config.fLoader=function(e,t,i,r){const s=r.httpStreamEnabled&&ni();return class extends(n()){constructor(n){super(),this.logger=i,this.isHlsV0=r.isHlsV0,this.bufMgr=e.bufMgr,this.httpLoader=s||this.isHlsV0?new ai(n):new vi(n),this.originalLoader=n.loader,this.p2pEnabled=r.p2pEnabled,this.isLive=r.live,this.scheduler=e,this.fetcher=t,this.segmentId=r.segmentId,this.blockTypes=r.p2pBlackList,this.stats=this.httpLoader.stats||D(),this.segmentBypass=I(r.segmentBypass)?r.segmentBypass:()=>!1,this.prefetchOnly=r.prefetchOnly,this.startFromSegmentOffset=r.startFromSegmentOffset}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,i){const{logger:r,scheduler:s}=this,{url:n,frag:a}=e;this.isHlsV0||(a.stats=this.stats);const{level:o,sn:l,type:h,tagList:u}=a;let d=a.segId;if(!d){let t;e.rangeEnd&&(t="bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),d=a.segId=this.segmentId(String(o),l,n,t)}const c=()=>(a.loadByHTTP=!0,new this.originalLoader(t).load(e,t,i));if(!n||!Number.isInteger(l)||Ti(0,this.blockTypes,h)||this.segmentBypass(n,u))return r.info(`HTTP load blockType ${n}`),c();if(this.fetcher.increMediaRequests(),this.isLive&&s.requestedSet.has(d))return r.warn(`HTTP load duplicated ${n}`),c();if(s.engine.segmentLoadCount<this.startFromSegmentOffset)return c();t.maxRetry=2;const f=s.getBufferedDuration(),g=await this.bufMgr.getSegById(d);if(this.p2pEnabled&&g){r.info(`bufMgr found seg sn ${l} segId ${d} level ${o} size ${g.size}`);let t=y(g.data).buffer,n={url:e.url,data:t};return _i(this.stats,g.size,s.coordinator),a.loaded=g.size,a.loadByP2P=!0,a.fromPeerId=g.fromPeerId,void W((()=>{!this.isHlsV0&&i.onProgress&&i.onProgress(this.stats,e,n.data),i.onSuccess(n,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&s.hasAndSetTargetPeer(l,o,d,f)?this.loadFragByP2p(e,t,i,d,f):(r.info(`fragLoader load ${d} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,i,d))}loadFragByHttp(e,t,i,r){const{logger:n,scheduler:a}=this,{segmentBuilderMap:o}=a,l=e.frag,{sn:h,level:u}=l,d=de(h,u);if(s){let e;i.onUpdate=(t,i,s)=>{if(s)return n.warn(`loadFragByHttp ${r} aborted`),void o.delete(d);e&&e.receiveBytes(t,i)},i.onBodyStart=t=>{!e&&t>0&&(e=new fi(h,u,r,t),o.has(d)||o.set(d,e),a.notifyAllPeers(h,u,r,t,Kt.PARTIAL_FORWARD))}}const c=i.onSuccess;i.onSuccess=async(e,t,i)=>{a.coordinator.addLoaderHttpSpeed(t.tload-t.tfirst,t.loaded);const{data:s}=e;let f=t.tload-t.trequest;if(n.info(`HTTP loaded ${r} time ${f} speed ${t.total/f}`),l.loaded=t.total,!await this.bufMgr.hasSegOfId(r)){const e=y(s).buffer,t=new X(h,r,e,this.fetcher.peerId,u);await this.bufMgr.putSeg(t)}o.delete(d),this.fetcher.reportFlow(t.total),c(e,t,i)},e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,i)}loadFragByP2p(t,i,r,s,n){const{logger:a}=this,o=t.frag;let l;l=i.loadPolicy?i.loadPolicy.maxTimeToFirstByteMs:i.timeout,(!l||l>1e3*n)&&(l=1e3*n),t.defaultTimeout=l,this.scheduler.load(t,i,r);const h=r.onSuccess,u=r.onTimeout;r.onTimeout=(e,t)=>{a.warn(`P2P timeout switched to HTTP load ${o.relurl} at ${o.sn}`),r.onSuccess=h,this.loadFragByHttp(t,i,r,s),r.onTimeout=u},r.onSuccess=async(t,i,n)=>{const{data:l}=t;if(_i(i=this.stats,l.byteLength,e.coordinator),!await this.bufMgr.hasSegOfId(s)){const e=y(l).buffer,t=new X(o.sn,s,e,o.fromPeerId||this.fetcher.peerId,o.level,n.ext);await this.bufMgr.putSeg(t)}o.loadByP2P||this.fetcher.reportFlow(i.total),o.loaded=i.loaded,a.info(`${o.loadByP2P?"P2P":"HTTP"} loaded segment id ${s}`),!this.isHlsV0&&r.onProgress&&r.onProgress(i,n,l),h(t,i,n)}}}}(s,this.fetcher,i,r),r.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,i){return class extends(n()){constructor(r){super(),this.logger=t,this.xhrLoader=new r.loader(r),this.p2pEnabled=i.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||D()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,i){const{logger:r}=this,{url:s}=e,n=b(s),a=i.onSuccess;if(i.onSuccess=(e,t,i)=>{this.scheduler&&!i.loadedByPeer&&this.scheduler.broadcastPlaylist(n,e.data),a(e,t,i)},this.scheduler&&this.scheduler.playlistInfo.has(n)){const t=await this.scheduler.getPlaylistFromPeer(n);if(t&&t.data){const{data:n,seq:a}=t;r.info(`got playlist from peer seq ${a}`),_i(this.stats,n.length);let o={url:s,data:n};return e.loadedByPeer=!0,void W((()=>{i.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,i)}}}(s,i,r))}_onFragLoading(e,i){const r=i.frag;let{sn:s,level:n,segId:a}=r;if(!Ti(r.url,this.config.p2pBlackList,r.type)&&Number.isInteger(s)){if(this.logger&&this.logger.info("loading frag "+s),this.bufMgr&&(this.bufMgr.loadingSN=s),!a){let e;r._byteRange&&(e="bytes="+r._byteRange[0]+"-"+r._byteRange[1]);let t=r.url;this._setupSegmentId(),a=r.segId=this.config.segmentId(String(n),r.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:s,segId:a,byHttp:r.loadByHTTP,level:n})}}_onLevelUpdated(e,t){const{details:i}=t,{hlsjs:r,config:s}=this,{targetduration:n,live:a,fragments:o}=i,l=o.length;if(a&&r&&"main"===o[0].type&&!(l<=4)&&(s.isHlsV0||!r.userConfig.liveSyncDuration&&!r.userConfig.liveSyncDurationCount)){const e=l<=9?l-1:l-2;r.config.liveSyncDurationCount!==e&&(r.config.liveSyncDurationCount=e)}}_onFragLoaded(e,i){if(this.segmentLoadCount++,!this.p2pEnabled)return;const{frag:r}=i;this.curTsUri=r.url;const{sn:s,segId:n,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:u,url:d}=r,{config:c,logger:f}=this;this.tracker&&this.tracker.scheduler&&(T(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(n)),Ti(r.url,c.p2pBlackList,r.type)||(this.bufMgr&&this.bufMgr.loadingSN>=0&&this.emit(t.FRAG_LOADED,{url:d,sn:s,level:l,segId:n,loaded:a,duration:o,byP2p:!!u,fromPeerId:h}),!this.rangeTested&&c.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,f&&f.info(JSON.stringify({engine:this.engineName,hlsjs:this.hlsjsVersion,...this.browserInfo})))),this.segmentLoadCount>=c.startFromSegmentOffset&&this.resumeTracker()}_onFragChanged(e,i){const{frag:r}=i;if(!Ti(r.url,this.config.p2pBlackList,r.type)){this.logger&&this.logger.info("frag changed: "+r.sn);const{sn:e,duration:i}=r;this.emit(t.FRAG_CHANGED,{sn:e,duration:i})}}get currentLevel(){const{currentLevel:e}=this.hlsjs;return e>=0?e:0}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}_updateHlsEventsHandlers(e=!1){const t=this.hlsjs;if(!t)return;const i=e?"off":"on";t[i](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[i](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[i](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[i](this.HLSEvents.ERROR,this._onHlsError),t[i](this.HLSEvents.LEVEL_UPDATED,this._onLevelUpdated)}destroy(){this._updateHlsEventsHandlers(!0),super.destroy()}_setupSW(){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:t}=e.data,i=e.ports[0];if(i)return i.postMessage({action:t,pong:!0}),i.postMessage({action:t,data:{bypass:!0}})}}}const Ai=bi;class Ii{static get Events(){return t}static get TrackerZone(){return se.TrackerZone}static isSupported(){return se.isSupported()&&(ne()||Si.isServiceWorkerSupported())}static isServiceWorkerSupported(){return Si.isServiceWorkerSupported()}static isMSESupported(){return ne()}static getBrowser(){return J().getBrowser()}static get ServiceWorkerEngine(){return Si}static get HlsjsEngine(){return Ai}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return Ii.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:i}={}){const{serviceWorker:r}=navigator;return!r||i?Promise.resolve():r.getRegistration().then((i=>i||Promise.race([r.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,i)=>{const r=e.installing||e.waiting||e.active,s=()=>"activated"===r.state&&(r.removeEventListener("statechange",s),t(e),!0);s()||r.addEventListener("statechange",s)}))}(e))).catch((()=>{Promise.resolve()})),v(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const i=()=>{this._realEngine=new Ai(t,e)},r=()=>{this._realEngine=new Si(e,t)};"1"!==c("_sw")?e.proxyFirst&&t?Si.isServiceWorkerSupported()?r():i():!e.proxyOnly&&ne()&&t?i():r():r()}get realEngine(){return this._realEngine}get engineName(){return this._realEngine.constructor.name}once(e,t){return this._realEngine.once(e,t)}on(e,t){return this._realEngine.on(e,t)}off(e,t){return this._realEngine.off(e,t)}removeListener(e,t){return this._realEngine.removeListener(e,t)}removeAllListeners(e){return this._realEngine.removeAllListeners(e)}set p2pEnabled(e){this._realEngine.p2pEnabled=e}get p2pEnabled(){return this._realEngine.p2pEnabled}enableP2P(){this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}async registerServiceWorker(){return I(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return I(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return se.version}}Ii.version=se.version,Ii.protocolVersion=ee.VERSION,"object"==typeof self&&(self.P2PEngineHls=Ii);const Ri=Ii;var Pi=i(251),ki=i.n(Pi);const Di={maxBufferLength:12},wi={maxBufferLength:40};class Ci extends(ki()){static get P2PEvents(){return Ri.Events}static get P2pEngine(){return Ri}constructor(e={}){let t=e.p2pConfig||{};const i=!1===t.live?wi:Di;let r=JSON.parse(JSON.stringify(i));r.maxBufferSize=0,r.enableWorker=!1;for(let t in e)"p2pConfig"!==t&&(r[t]=e[t]);super(r),this._restartEvent=()=>{this.restartP2P()},Ri.isSupported()&&(this._p2pEngine=new Ri({...t,hlsjsInstance:this}),this._p2pEngine.on(Ri.Events.RESTART_P2P,this._restartEvent)),this.on(ki().Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(Ri.Events.RESTART_P2P,this._restartEvent),this._p2pEngine.hlsjs=null,this._p2pEngine=null)}))}get p2pEngine(){return this._p2pEngine}enableP2P(){this._p2pEngine&&(this._p2pEngine=this._p2pEngine.enableP2P())}disableP2P(){this._p2pEngine&&this._p2pEngine.disableP2P()}restartP2P(){this._p2pEngine&&(this._p2pEngine.disableP2P(),setTimeout((()=>{this.enableP2P()}),2e3),this._p2pEngine.removeListener(Ri.Events.RESTART_P2P,this._restartEvent))}}Ci.engineVersion=Ri.version,Ci.protocolVersion=Ri.protocolVersion,Ci.WEBRTC_SUPPORT=Ri.isSupported();const Mi=Ci})(),r=r.default})()));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(this,(()=>(()=>{var e={415:e=>{"use strict";var t,i="object"==typeof Reflect?Reflect:null,r=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function n(){n.init.call(this)}e.exports=n,e.exports.once=function(e,t){return new Promise((function(i,r){function s(i){e.removeListener(t,n),r(i)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&p(e,"error",t,i)}(e,s,{once:!0})}))},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function h(e,t,i,r){var s,n,a,h;if(o(i),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),n=e._events),a=n[t]),void 0===a)a=n[t]=i,++e._eventsCount;else if("function"==typeof a?a=n[t]=r?[i,a]:[a,i]:r?a.unshift(i):a.push(i),(s=l(e))>0&&a.length>s&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,h=u,console&&console.warn&&console.warn(h)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=u.bind(r);return s.listener=i,r.wrapFn=s,s}function c(e,t,i){var r=e._events;if(void 0===r)return[];var s=r[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):g(s,s.length)}function f(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function g(e,t){for(var i=new Array(t),r=0;r<t;++r)i[r]=e[r];return i}function p(e,t,i,r){if("function"==typeof e.on)r.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(n){r.once&&e.removeEventListener(t,s),i(n)}))}}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),n.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var s="error"===e,n=this._events;if(void 0!==n)s=s&&void 0===n.error;else if(!s)return!1;if(s){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var l=n[e];if(void 0===l)return!1;if("function"==typeof l)r(l,this,t);else{var h=l.length,u=g(l,h);for(i=0;i<h;++i)r(u[i],this,t)}return!0},n.prototype.addListener=function(e,t){return h(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return h(this,e,t,!0)},n.prototype.once=function(e,t){return o(t),this.on(e,d(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,d(this,e,t)),this},n.prototype.removeListener=function(e,t){var i,r,s,n,a;if(o(t),void 0===(r=this._events))return this;if(void 0===(i=r[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,n=i.length-1;n>=0;n--)if(i[n]===t||i[n].listener===t){a=i[n].listener,s=n;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(r[e]=i[0]),void 0!==r.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,i,r;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,n=Object.keys(i);for(r=0;r<n.length;++r)"removeListener"!==(s=n[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},n.prototype.listeners=function(e){return c(this,e,!0)},n.prototype.rawListeners=function(e){return c(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return i.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(d)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()},251:e=>{!function t(i){var r;r=function(){"use strict";function e(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,c(r.key),r)}}function r(t,i,r){return i&&e(t.prototype,i),r&&e(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function s(e,t,i){return(t=c(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},n.apply(null,arguments)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function o(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,d(e,t)}function l(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(l=function(){return!!e})()}function h(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function u(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?h(Object(i),!0).forEach((function(t){s(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):h(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function c(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function f(e){var t="function"==typeof Map?new Map:void 0;return f=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return function(e,t,i){if(l())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var s=new(e.bind.apply(e,r));return i&&d(s,i.prototype),s}(e,arguments,a(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),d(i,e)},f(e)}var g,p,v={exports:{}},m=(g||(g=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,n||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,s,n,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,h,u=this._events[o],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,s),!0;case 5:return u.fn.call(u.context,t,r,s,n),!0;case 6:return u.fn.call(u.context,t,r,s,n,a),!0}for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var c,f=u.length;for(h=0;h<f;h++)switch(u[h].once&&this.removeListener(e,u[h].fn,void 0,!0),d){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,t);break;case 3:u[h].fn.call(u[h].context,t,r);break;case 4:u[h].fn.call(u[h].context,t,r,s);break;default:if(!l)for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u[h].fn.apply(u[h].context,l)}}return!0},o.prototype.on=function(e,t,i){return n(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return n(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,r,s){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||s&&!o.once||r&&o.context!==r||a(this,n);else{for(var l=0,h=[],u=o.length;l<u;l++)(o[l].fn!==t||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(v)),v.exports),y=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(m),E={exports:{}},S=(p||(p=1,function(e,t){var i,r,s,n,a;i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return i.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(d)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(E)),E.exports),T=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},_=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=L},L=Number.MAX_SAFE_INTEGER||9007199254740991,b=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),A=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),I=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({}),R="manifest",P="level",k="audioTrack",D="subtitleTrack",w="main",C="audio",M="subtitle",O=function(){function e(e,t,i){void 0===t&&(t=0),void 0===i&&(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}var t=e.prototype;return t.sample=function(e,t){var i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),x=function(){function e(e,t,i,r){void 0===r&&(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 O(e),this.fast_=new O(t),this.defaultTTFB_=r,this.ttfb_=new O(e)}var t=e.prototype;return t.update=function(e,t){var i=this.slow_,r=this.fast_,s=this.ttfb_;i.halfLife!==e&&(this.slow_=new O(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new O(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new O(e,s.getEstimate(),s.getTotalWeight()))},t.sample=function(e,t){var i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)},t.sampleTTFB=function(e){var t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},r(e,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),F=function(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="["+e+"]:";this.trace=N,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)},N=function(){},B={trace:N,debug:N,log:N,warn:N,info:N,error:N};function U(){return n({},B)}function G(e,t,i){return t[e]?t[e].bind(t):function(e,t){var i=self.console[e];return i?i.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):N}(e,i)}var H=U();function K(e,t,i){var r=U();if("object"==typeof console&&!0===e||"object"==typeof e){var s=["debug","log","info","warn","error"];s.forEach((function(t){r[t]=G(t,e,i)}));try{r.log('Debug logs enabled for "'+t+'" in hls.js version 1.6.12')}catch(e){return U()}s.forEach((function(t){H[t]=G(t,e)}))}else n(H,r);return r}var V=H;function $(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function W(e,t){var i=Object.keys(e),r=Object.keys(t),s=i.length,n=r.length;return!s||!n||s===n&&!i.some((function(e){return-1===r.indexOf(e)}))}function q(e,t){if(void 0===t&&(t=!1),"undefined"!=typeof TextDecoder){var i=new TextDecoder("utf-8").decode(e);if(t){var r=i.indexOf("\0");return-1!==r?i.substring(0,r):i}return i.replace(/\0/g,"")}for(var s,n,a,o=e.length,l="",h=0;h<o;){if(0===(s=e[h++])&&t)return l;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(s);break;case 12:case 13:n=e[h++],l+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=e[h++],a=e[h++],l+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&a)}}return l}function j(e){for(var t="",i=0;i<e.length;i++){var r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t}function Y(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var z=function(){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}},X="audio",Q="video",J="audiovideo",Z=function(){function e(e){var t;this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,(t=re(this,"stats"))&&(t.enumerable=!0,Object.defineProperty(this,"stats",t))}var t=e.prototype;return t.setByteRange=function(e,t){var i,r=e.split("@",2);i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]},t.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[X]=null,e[Q]=null,e[J]=null},r(e,[{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){var e;return null===this._streams&&(this._streams=((e={})[X]=null,e[Q]=null,e[J]=null,e)),this._streams},set:function(e){this._streams=e}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new z),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=S.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}])}();function ee(e){return"initSegment"!==e.sn}var te=function(e){function t(t,i){var r;return(r=e.call(this,i)||this)._decryptdata=null,r._programDateTime=null,r._ref=null,r._bitrate=void 0,r.rawProgramDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.playlistOffset=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=t,r}o(t,e);var i=t.prototype;return i.addStart=function(e){this.setStart(this.start+e)},i.setStart=function(e){this.start=e,this._ref&&(this._ref.start=e)},i.setDuration=function(e){this.duration=e,this._ref&&(this._ref.duration=e)},i.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},i.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},i.setElementaryStreamInfo=function(e,t,i,r,s,n){void 0===n&&(n=!1);var a=this.elementaryStreams,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:n}},r(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],i=this.byteRange[1];if(T(t)&&T(i))return i-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{var t=Object.keys(this.levelkeys);if(1===t.length){var i=this._decryptdata=this.levelkeys[t[0]]||null;if(i)return i.getDecryptData(this.sn)}}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=T(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,i=Object.keys(this.levelkeys),r=i.length;if(r>1||1===r&&null!=(t=this.levelkeys[i[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){T(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return ee(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(Z),ie=function(e){function t(t,i,r,s,n){var a;(a=e.call(this,r)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.duration=t.decimalFloatingPoint("DURATION"),a.gap=t.bool("GAP"),a.independent=t.bool("INDEPENDENT"),a.relurl=t.enumeratedString("URI"),a.fragment=i,a.index=s;var o=t.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,n),n&&(a.fragOffset=n.fragOffset+n.duration),a}return o(t,e),r(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}])}(Z);function re(e,t){var i=Object.getPrototypeOf(e);if(i)return Object.getOwnPropertyDescriptor(i,t)||re(i,t)}var se=Math.pow(2,32)-1,ne=[].push,ae={video:1,audio:2,id3:3,text:4};function oe(e){return String.fromCharCode.apply(null,e)}function le(e,t){var i=e[t]<<8|e[t+1];return i<0?65536+i:i}function he(e,t){var i=de(e,t);return i<0?4294967296+i:i}function ue(e,t){var i=he(e,t);return(i*=Math.pow(2,32))+he(e,t+4)}function de(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ce(e,t){var i=[];if(!t.length)return i;for(var r=e.byteLength,s=0;s<r;){var n=he(e,s),a=n>1?s+n:r;if(oe(e.subarray(s+4,s+8))===t[0])if(1===t.length)i.push(e.subarray(s+8,a));else{var o=ce(e.subarray(s+8,a),t.slice(1));o.length&&ne.apply(i,o)}s=a}return i}function fe(e){var t=[],i=e[0],r=8,s=he(e,r);r+=4;var n=0,a=0;0===i?(n=he(e,r),a=he(e,r+4),r+=8):(n=ue(e,r),a=ue(e,r+8),r+=16),r+=2;var o=e.length+a,l=le(e,r);r+=2;for(var h=0;h<l;h++){var u=r,d=he(e,u);u+=4;var c=2147483647&d;if(1==(2147483648&d)>>>31)return V.warn("SIDX has hierarchical references (not supported)"),null;var f=he(e,u);u+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+c-1}}),o+=c,r=u+=4}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:t}}function ge(e){for(var t=[],i=ce(e,["moov","trak"]),r=0;r<i.length;r++){var s=i[r],n=ce(s,["tkhd"])[0];if(n){var a=n[0],o=he(n,0===a?12:20),l=ce(s,["mdia","mdhd"])[0];if(l){var h=he(l,0===(a=l[0])?12:20),d=ce(s,["mdia","hdlr"])[0];if(d){var c=oe(d.subarray(8,12)),f={soun:X,vide:Q}[c],g=pe(ce(s,["mdia","minf","stbl","stsd"])[0]);f?(t[o]={timescale:h,type:f,stsd:g},t[f]=u({timescale:h,id:o},g)):t[o]={timescale:h,type:c,stsd:g}}}}}return ce(e,["moov","mvex","trex"]).forEach((function(e){var i=he(e,4),r=t[i];r&&(r.default={duration:he(e,12),flags:he(e,20)})})),t}function pe(e){var t,i=e.subarray(8),r=i.subarray(86),s=oe(i.subarray(4,8)),n=s,a="enca"===s||"encv"===s;if(a){var o=ce(i,[s])[0];ce(o.subarray("enca"===s?28:78),["sinf"]).forEach((function(e){var t=ce(e,["schm"])[0];if(t){var i=oe(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=ce(e,["frma"])[0];r&&(n=oe(r))}}}))}var l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":var h=ce(r,["avcC"])[0];h&&h.length>3&&(n+="."+ye(h[1])+ye(h[2])+ye(h[3]),t=ve("avc1"===l?"dva1":"dvav",r));break;case"mp4a":var u=ce(i,[s])[0],d=ce(u.subarray(28),["esds"])[0];if(d&&d.length>7){var c=4;if(3!==d[c++])break;c=me(d,c),c+=2;var f=d[c++];if(128&f&&(c+=2),64&f&&(c+=d[c++]),4!==d[c++])break;c=me(d,c);var g=d[c++];if(64!==g)break;if(n+="."+ye(g),c+=12,5!==d[c++])break;c=me(d,c);var p=d[c++],v=(248&p)>>3;31===v&&(v+=1+((7&p)<<3)+((224&d[c])>>5)),n+="."+v}break;case"hvc1":case"hev1":var m=ce(r,["hvcC"])[0];if(m&&m.length>12){var y=m[1],E=["","A","B","C"][y>>6],S=31&y,T=he(m,2),_=(32&y)>>5?"H":"L",L=m[12],b=m.subarray(6,12);n+="."+E+S,n+="."+function(e){for(var t=0,i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}(T).toString(16).toUpperCase(),n+="."+_+L;for(var A="",I=b.length;I--;){var R=b[I];(R||A)&&(A="."+R.toString(16).toUpperCase()+A)}n+=A}t=ve("hev1"==l?"dvhe":"dvh1",r);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ve(n,r)||n;break;case"vp09":var P=ce(r,["vpcC"])[0];if(P&&P.length>6){var k=P[4],D=P[5],w=P[6]>>4&15;n+="."+Ee(k)+"."+Ee(D)+"."+Ee(w)}break;case"av01":var C=ce(r,["av1C"])[0];if(C&&C.length>2){var M=C[1]>>>5,O=31&C[1],x=C[2]>>>7?"H":"M",F=(64&C[2])>>6,N=(32&C[2])>>5,B=2===M&&F?N?12:10:F?10:8,U=(16&C[2])>>4,G=(8&C[2])>>3,H=(4&C[2])>>2,K=3&C[2];n+="."+M+"."+Ee(O)+x+"."+Ee(B)+"."+U+"."+G+H+K+"."+Ee(1)+"."+Ee(1)+"."+Ee(1)+".0",t=ve("dav1",r)}}return{codec:n,encrypted:a,supplemental:t}}function ve(e,t){var i=ce(t,["dvvC"]),r=i.length?i[0]:ce(t,["dvcC"])[0];if(r){var s=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return e+"."+Ee(s)+"."+Ee(n)}}function me(e,t){for(var i=t+5;128&e[t++]&&t<i;);return t}function ye(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ee(e){return(e<10?"0":"")+e}function Se(e){var t=ce(e,["schm"])[0];if(t){var i=oe(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return ce(e,["schi","tenc"])[0]}return null}function Te(e,t){var i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function _e(e,t){var i=[],r=t.samples,s=t.timescale,n=t.id,a=!1;return ce(r,["moof"]).map((function(o){var l=o.byteOffset-8;ce(o,["traf"]).map((function(o){var h=ce(o,["tfdt"]).map((function(e){var t=e[0],i=he(e,4);return 1===t&&(i*=Math.pow(2,32),i+=he(e,8)),i/s}))[0];return void 0!==h&&(e=h),ce(o,["tfhd"]).map((function(h){var u=he(h,4),d=16777215&he(h,0),c=0,f=!!(16&d),g=0,p=!!(32&d),v=8;u===n&&(!!(1&d)&&(v+=8),!!(2&d)&&(v+=4),!!(8&d)&&(c=he(h,v),v+=4),f&&(g=he(h,v),v+=4),p&&(v+=4),"video"===t.type&&(a=Le(t.codec)),ce(o,["trun"]).map((function(n){var o=n[0],h=16777215&he(n,0),u=!!(1&h),d=0,f=!!(4&h),p=!!(256&h),v=0,m=!!(512&h),y=0,E=!!(1024&h),S=!!(2048&h),T=0,_=he(n,4),L=8;u&&(d=he(n,L),L+=4),f&&(L+=4);for(var b=d+l,A=0;A<_;A++){if(p?(v=he(n,L),L+=4):v=c,m?(y=he(n,L),L+=4):y=g,E&&(L+=4),S&&(T=0===o?he(n,L):de(n,L),L+=4),t.type===Q)for(var I=0;I<y;){var R=he(r,b);be(a,r[b+=4])&&Ae(r.subarray(b,b+R),a?2:1,e+T/s,i),b+=R,I+=R+4}e+=v/s}})))}))}))})),i}function Le(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function be(e,t){if(e){var i=t>>1&63;return 39===i||40===i}return 6==(31&t)}function Ae(e,t,i,r){var s=Ie(e),n=0;n+=t;for(var a=0,o=0,l=0;n<s.length;){a=0;do{if(n>=s.length)break;a+=l=s[n++]}while(255===l);o=0;do{if(n>=s.length)break;o+=l=s[n++]}while(255===l);var h=s.length-n,u=n;if(o<h)n+=o;else if(o>h){V.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===s[u++]){var d=le(s,u);if(u+=2,49===d){var c=he(s,u);if(u+=4,1195456820===c){var f=s[u++];if(3===f){var g=s[u++],p=64&g,v=p?2+3*(31&g):0,m=new Uint8Array(v);if(p){m[0]=g;for(var y=1;y<v;y++)m[y]=s[u++]}r.push({type:f,payloadType:a,pts:i,bytes:m})}}}}}else if(5===a&&o>16){for(var E=[],S=0;S<16;S++){var T=s[u++].toString(16);E.push(1==T.length?"0"+T:T),3!==S&&5!==S&&7!==S&&9!==S||E.push("-")}for(var _=o-16,L=new Uint8Array(_),b=0;b<_;b++)L[b]=s[u++];r.push({payloadType:a,pts:i,uuid:E.join(""),userData:q(L),userDataBytes:L})}}}function Ie(e){for(var t=e.byteLength,i=[],r=1;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;var s=t-i.length,n=new Uint8Array(s),a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=e[a];return n}function Re(e){var t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};var s=e.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:t};var n=e.buffer,a=j(new Uint8Array(n,i+12,16)),o=null,l=0;if(0===s)l=28;else{var h=e.getUint32(28);if(!h||r<32+16*h)return{offset:i,size:t};o=[];for(var u=0;u<h;u++)o.push(new Uint8Array(n,i+32+16*u,16));l=32+16*h}if(!l)return{offset:i,size:t};var d=e.getUint32(l);return t-32<d?{offset:i,size:t}:{version:s,systemId:a,kids:o,data:new Uint8Array(n,i+l+4,d),offset:i,size:t}}var Pe=function(){return/\(Windows.+Firefox\//i.test(navigator.userAgent)},ke={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,dav1:.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 De(e,t){var i=ke[t];return!!i&&!!i[e.slice(0,4)]}function we(e,t,i){return void 0===i&&(i=!0),!e.split(",").some((function(e){return!Ce(e,t,i)}))}function Ce(e,t,i){var r;void 0===i&&(i=!0);var s=$(i);return null!=(r=null==s?void 0:s.isTypeSupported(Me(e,t)))&&r}function Me(e,t){return t+"/mp4;codecs="+e}function Oe(e){if(e){var t=e.substring(0,4);return ke.video[t]}return 2}function xe(e){var t=Pe();return e.split(",").reduce((function(e,i){var r=t&&Le(i)?9:ke.video[i];return r?(2*r+e)/(e?3:2):(ke.audio[i]+e)/(e?2:1)}),0)}var Fe={},Ne=/flac|opus|mp4a\.40\.34/i;function Be(e,t){return void 0===t&&(t=!0),e.replace(Ne,(function(e){return function(e,t){if(void 0===t&&(t=!0),Fe[e])return Fe[e];for(var i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],r=0;r<i.length;r++){var s;if(Ce(i[r],"audio",t))return Fe[e]=i[r],i[r];if("mp3"===i[r]&&null!=(s=$(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)}))}function Ue(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(Ge(e,"audio")||Ge(e,"video")))return e;if(t){var i=t.split(",");if(i.length>1){if(e)for(var r=i.length;r--;)if(i[r].substring(0,4)===e.substring(0,4))return i[r];return i[0]}}return t||e}function Ge(e,t){return De(e,t)&&Ce(e,t)}function He(e){if(e.startsWith("av01.")){for(var t=e.split("."),i=["0","111","01","01","01","0"],r=t.length;r>4&&r<10;r++)t[r]=i[r-4];return t.join(".")}return e}function Ke(e){var t=$(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ve(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var $e={supported:!1,smooth:!1,powerEfficient:!1},We={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function qe(e,t){return{supported:!1,configurations:t,decodingInfoResults:[$e],error:e}}function je(e,t,i,r){void 0===r&&(r={});var s=e.videoCodec;if(!s&&!e.audioCodec||!i)return Promise.resolve(We);for(var n=[],a=function(e){var t,i=null==(t=e.videoCodec)?void 0:t.split(","),r=ze(e),s=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map((function(e){var t={contentType:Me(He(e),"video"),width:s,height:n,bitrate:r,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t})):[]}(e),o=a.length,l=function(e,t,i){var r,s=null==(r=e.audioCodec)?void 0:r.split(","),n=ze(e);return s&&e.audioGroups?e.audioGroups.reduce((function(e,r){var a,o=r?null==(a=t.groups[r])?void 0:a.tracks:null;return o?o.reduce((function(e,t){if(t.groupId===r){var a=parseFloat(t.channels||"");s.forEach((function(t){var r={contentType:Me(t,"audio"),bitrate:i?Ye(t,n):n};a&&(r.channels=""+a),e.push(r)}))}return e}),e):e}),[]):[]}(e,t,o>0),h=l.length,u=o||1*h||1;u--;){var d={type:"media-source"};if(o&&(d.video=a[u%o]),h){d.audio=l[u%h];var c=d.audio.bitrate;d.video&&c&&(d.video.bitrate-=c)}n.push(d)}if(s){var f=navigator.userAgent;if(s.split(",").some((function(e){return Le(e)}))&&Pe())return Promise.resolve(qe(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: ("+f+")"),n))}return Promise.all(n.map((function(e){var t,s,n,a,o=(s="",n=(t=e).audio,(a=t.video)&&(s+=Ve(a.contentType)+"_r"+a.height+"x"+a.width+"f"+Math.ceil(a.framerate)+(a.transferFunction||"sd")+"_"+Math.ceil(a.bitrate/1e5)),n&&(s+=(a?"_":"")+Ve(n.contentType)+"_c"+n.channels),s);return r[o]||(r[o]=i.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:n,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:n,decodingInfoResults:[],error:e}}))}function Ye(e,t){if(t<=1)return 1;var i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}function ze(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}var Xe=["NONE","TYPE-0","TYPE-1",null],Qe=["SDR","PQ","HLG"];function Je(e){var t=e.canSkipUntil,i=e.canSkipDateRanges,r=e.age;return t&&r<t/2?i?"v2":"YES":""}var Ze=function(){function e(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}return e.prototype.addDirectives=function(e){var t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href},e}(),et=function(){function e(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((function(e){return!!e})).map((function(e){return e.substring(0,4)})).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;var i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=","+i.substring(0,4))}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}var t=e.prototype;return t.hasAudioGroup=function(e){return tt(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return tt(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(t)&&i.push(t)}else if("text"===e){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(t)&&r.push(t)}},t.addFallback=function(){},r(e,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}}])}();function tt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}var it=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(i,r){if(e&&(r=e(i,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}}(t))};function rt(e,t){V.log('[abr] start candidates with "'+e+'" ignored because '+t)}function st(e){return e.reduce((function(e,t){var i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);var 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 nt(e){if(!e)return e;var t=e;return{lang:t.lang,assocLang:t.assocLang,characteristics:t.characteristics,channels:t.channels,audioCodec:t.audioCodec}}function at(e,t,i){if("attrs"in e){var r=t.indexOf(e);if(-1!==r)return r}for(var s=0;s<t.length;s++)if(ot(e,t[s],i))return s;return-1}function ot(e,t,i){var r,s,n=e.groupId,a=e.name,o=e.lang,l=e.assocLang,h=e.default,u=e.forced;return(void 0===n||t.groupId===n)&&(void 0===a||t.name===a)&&(void 0===o||(r=o,void 0===(s=t.lang)&&(s="--"),r.length===s.length?r===s:r.startsWith(s)||s.startsWith(r)))&&(void 0===o||t.assocLang===l)&&(void 0===h||t.default===h)&&(void 0===u||t.forced===u)&&(!("characteristics"in e)||function(e,t){void 0===t&&(t="");var i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some((function(e){return-1===r.indexOf(e)}))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function lt(e,t){var i=e.audioCodec,r=e.channels;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function ht(e,t,i){for(var r=t;r>-1;r--)if(i(e[r]))return r;for(var s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function ut(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}var dt=function(e){function t(t){var i;return(i=e.call(this,"abr",t.logger)||this).hls=void 0,i.lastLevelLoadSec=0,i.lastLoadedFragLevel=-1,i.firstSelection=-1,i._nextAutoLevel=-1,i.nextAutoLevelKey="",i.audioTracksByGroup=null,i.codecTiers=null,i.timer=-1,i.fragCurrent=null,i.partCurrent=null,i.bitrateTestDelay=0,i.rebufferNotice=-1,i.supportedCache={},i.bwEstimator=void 0,i._abandonRulesCheck=function(e){var t,r=i,s=r.fragCurrent,n=r.partCurrent,a=r.hls,o=a.autoLevelEnabled,l=a.media;if(s&&l){var h=performance.now(),u=n?n.stats:s.stats,d=n?n.duration:s.duration,c=h-u.loading.start,f=a.minAutoLevel,g=s.level,p=i._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f)return i.clearTimer(),void(i._nextAutoLevel=-1);if(o){var v=p>-1&&p!==g,m=!!e||v;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=a.mainForwardBufferInfo;if(m||null!==y){var E=i.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(!(c<=Math.max(E,d/(2*S)*1e3))){var _=y?y.len/S:0,L=u.loading.first?u.loading.first-u.loading.start:-1,b=u.loaded&&L>-1,A=i.getBwEstimate(),R=a.levels,P=R[g],k=Math.max(u.loaded,Math.round(d*(s.bitrate||P.averageBitrate)/8)),D=b?c-L:c;D<1&&b&&(D=Math.min(c,8*u.loaded/A));var w=b?1e3*u.loaded/D:0,C=E/1e3,M=w?(k-u.loaded)/w:8*k/A+C;if(!(M<=_)){var O,x=w?8*w:A,F=!0===(null==(t=(null==e?void 0:e.details)||i.hls.latestLevelDetails)?void 0:t.live),N=i.hls.config.abrBandWidthUpFactor,B=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){var U=R[O].maxBitrate,G=!R[O].details||F;if((B=i.getTimeToLoadFrag(C,x,d*U,G))<Math.min(_,d+C))break}if(!(B>=M||B>10*d)){b?i.bwEstimator.sample(c-Math.min(E,L),u.loaded):i.bwEstimator.sampleTTFB(c);var H=R[O].maxBitrate;i.getBwEstimate()*N>H&&i.resetEstimator(H);var K=i.findBestLevel(H,f,O,0,_,1,1);K>-1&&(O=K),i.warn("Fragment "+s.sn+(n?" part "+n.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+s.duration.toFixed(3)+"\n Time to underbuffer: "+_.toFixed(3)+" s\n Estimated load time for current fragment: "+M.toFixed(3)+" s\n Estimated load time for down switch fragment: "+B.toFixed(3)+" s\n TTFB estimate: "+(0|L)+" ms\n Current BW estimate: "+(T(A)?0|A:"Unknown")+" bps\n New BW estimate: "+(0|i.getBwEstimate())+" bps\n Switching to level "+O+" @ "+(0|H)+" bps"),a.nextLoadLevel=a.nextAutoLevel=O,i.clearTimer();var V=function(){if(i.clearTimer(),i.fragCurrent===s&&i.hls.loadLevel===O&&O>0){var e=i.getStarvationDelay();if(i.warn("Aborting inflight request "+(O>0?"and switching down":"")+"\n Fragment duration: "+s.duration.toFixed(3)+" s\n Time to underbuffer: "+e.toFixed(3)+" s"),s.abortRequests(),i.fragCurrent=i.partCurrent=null,O>f){var t=i.findBestLevel(i.hls.levels[f].bitrate,f,O,0,e,1,1);-1===t&&(t=f),i.hls.nextLoadLevel=i.hls.nextAutoLevel=t,i.resetEstimator(i.hls.levels[t].bitrate)}}};v||M>2*B?V():i.timer=self.setInterval(V,1e3*B),a.trigger(I.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:u})}}}}}}}},i.hls=t,i.bwEstimator=i.initEstimator(),i.registerListeners(),i}o(t,e);var i=t.prototype;return i.resetEstimator=function(e){e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},i.initEstimator=function(){var e=this.hls.config;return new x(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},i.registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(I.ERROR,this.onError,this))},i.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null},i.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},i.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},i.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},i.onFragLoading=function(e,t){var i,r=t.frag;this.ignoreFragment(r)||(r.bitrateTest||(this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},i.onLevelSwitching=function(e,t){this.clearTimer()},i.onError=function(e,t){if(!t.fatal)switch(t.details){case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case A.FRAG_LOAD_TIMEOUT:var i=t.frag,r=this.fragCurrent,s=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var n=performance.now(),a=s?s.stats:i.stats,o=n-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){var h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}}},i.getTimeToLoadFrag=function(e,t,i,r){return e+i/t+(r?e+this.lastLevelLoadSec:0)},i.onLevelLoaded=function(e,t){var i=this.hls.config,r=t.stats.loading,s=r.end-r.first;T(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},i.onFragLoaded=function(e,t){var i=t.frag,r=t.part,s=r?r.stats:i.stats;if(i.type===w&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var n=r?r.duration:i.duration,a=this.hls.levels[i.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(i.bitrateTest){var h={stats:s,frag:i,part:r,id:i.type};this.onFragBuffered(I.FRAG_BUFFERED,h),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(!s.aborted&&!this.ignoreFragment(i)){var n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},i.ignoreFragment=function(e){return e.type!==w||"initSegment"===e.sn},i.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},i.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},i.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,i=this.hls;if(i.levels.length<=1)return i.loadLevel;var r=i.maxAutoLevel,s=i.config,n=i.minAutoLevel,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=s.abrBandWidthFactor,u=s.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,n,r,l,0,h,u);if(d>=0)return this.rebufferNotice=-1,d}var c=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-f,this.info("bitrate test took "+Math.round(1e3*f)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*c)+" ms"),h=u=1)}var g=this.findBestLevel(o,n,r,l,c,h,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var p=i.levels[n],v=i.loadLevelObj;return v&&(null==p?void 0:p.bitrate)<v.bitrate?n:i.loadLevel},i.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i},i.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},i.findBestLevel=function(e,t,i,r,s,n,a){var o,l=this,h=r+s,u=this.lastLoadedFragLevel,d=-1===u?this.hls.firstLevel:u,c=this.fragCurrent,f=this.partCurrent,g=this.hls,p=g.levels,v=g.allAudioTracks,m=g.loadLevel,y=g.config;if(1===p.length)return 0;var E,S=p[d],_=!(null==(o=this.hls.latestLevelDetails)||!o.live),L=-1===m||-1===u,b="SDR",A=(null==S?void 0:S.frameRate)||0,I=y.audioPreference,R=y.videoPreference,P=this.audioTracksByGroup||(this.audioTracksByGroup=st(v)),k=-1;if(L){if(-1!==this.firstSelection)return this.firstSelection;var D=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce((function(e,i,r){if(!i.codecSet)return e;var s=i.audioGroups,n=e[i.codecSet];n||(e[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);var a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,s&&s.forEach((function(e){if(e){var i=t.groups[e];i&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((function(e){n.channels[e]=(n.channels[e]||0)+i.channels[e]})))}})),e}),{})}(p,P,t,i)),w=function(e,t,i,r,s){for(var n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=null==s?void 0:s.videoCodec,h=a&&2===parseInt(a),u=!1,d=!1,c=1/0,f=1/0,g=1/0,p=1/0,v=0,m=[],y=function(e,t){var i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){var s="SDR"!==(r=t.allowedVideoRanges||Qe.slice(0)).join("")&&!t.videoCodec;(i=void 0!==t.preferHDR?t.preferHDR:s&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}(t,s),E=y.preferHDR,S=y.allowedVideoRanges,_=function(){var t=e[n[L]];u||(u=t.channels[2]>0),c=Math.min(c,t.minHeight),f=Math.min(f,t.minFramerate),g=Math.min(g,t.minBitrate),S.filter((function(e){return t.videoRanges[e]>0})).length>0&&(d=!0)},L=n.length;L--;)_();c=T(c)?c:0,f=T(f)?f:0;var b=Math.max(1080,c),A=Math.max(30,f);g=T(g)?g:i,i=Math.max(g,i),d||(t=void 0);var I=n.length>1;return{codecSet:n.reduce((function(t,r){var s=e[r];if(r===t)return t;if(m=d?S.filter((function(e){return s.videoRanges[e]>0})):[],I){if(s.minBitrate>i)return rt(r,"min bitrate of "+s.minBitrate+" > current estimate of "+i),t;if(!s.hasDefaultAudio)return rt(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return rt(r,'audio codec preference "'+o+'" not found'),t;if(a&&!h){if(!s.channels[a])return rt(r,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(s.channels)+")"),t}else if((!o||h)&&u&&0===s.channels[2])return rt(r,"no renditions with stereo sound found"),t;if(s.minHeight>b)return rt(r,"min resolution of "+s.minHeight+" > maximum of "+b),t;if(s.minFramerate>A)return rt(r,"min framerate of "+s.minFramerate+" > maximum of "+A),t;if(!m.some((function(e){return s.videoRanges[e]>0})))return rt(r,"no variants with VIDEO-RANGE of "+it(m)+" found"),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return rt(r,'video codec preference "'+l+'" not found'),t;if(s.maxScore<v)return rt(r,"max score of "+s.maxScore+" < selected max of "+v),t}return t&&(xe(r)>=xe(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,v=s.maxScore,r)}),void 0),videoRanges:m,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}(D,b,e,I,R),C=w.codecSet,M=w.videoRanges,O=w.minFramerate,x=w.minBitrate,F=w.minIndex,N=w.preferHDR;k=F,E=C,b=N?M[M.length-1]:M[0],A=O,e=Math.max(e,x),this.log("picked start tier "+it(w))}else E=null==S?void 0:S.codecSet,b=null==S?void 0:S.videoRange;for(var B,U=f?f.duration:c?c.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,H=[],K=function(){var t,o=p[V],c=V>d;if(!o)return 0;if(y.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&function(e,t,i,r,s,n){var a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,u=h?parseInt(h):l?1/0:2,d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((function(e,i){if(i){var r=t.groups[i];if(!r)throw new Error("Audio track group "+i+" not found");Object.keys(r.channels).forEach((function(t){e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some((function(e){return Le(e)}))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!d&&T(u)&&Object.keys(d).some((function(e){return parseInt(e)>u}))}(o,P,b,A,e,I)?(o.supportedPromise=je(o,P,g,l.supportedCache),o.supportedPromise.then((function(e){if(l.hls){o.supportedResult=e;var t=l.hls.levels,i=t.indexOf(o);e.error?l.warn('MediaCapabilities decodingInfo error: "'+e.error+'" for level '+i+" "+it(e)):e.supported?e.decodingInfoResults.some((function(e){return!1===e.smooth||!1===e.powerEfficient}))&&l.log("MediaCapabilities decodingInfo for level "+i+" not smooth or powerEfficient: "+it(e)):(l.warn("Unsupported MediaCapabilities decodingInfo result for level "+i+" "+it(e)),i>-1&&t.length>1&&(l.log("Removing unsupported level "+i),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}})).catch((function(e){l.warn("Error handling MediaCapabilities decodingInfo: "+e)}))):o.supportedResult=We}if((E&&o.codecSet!==E||b&&o.videoRange!==b||c&&A>o.frameRate||!c&&A>0&&A<o.frameRate||null!=(t=o.supportedResult)&&null!=(t=t.decodingInfoResults)&&t.some((function(e){return!1===e.smooth})))&&(!L||V!==k))return H.push(V),0;var v,S=o.details,R=(f?null==S?void 0:S.partTarget:null==S?void 0:S.averagetargetduration)||U;v=c?a*e:n*e;var D=U&&r>=2*U&&0===s?o.averageBitrate:o.maxBitrate,w=l.getTimeToLoadFrag(G,v,D*R,void 0===S);if(v>=D&&(V===u||0===o.loadError&&0===o.fragmentError)&&(w<=G||!T(w)||_&&!l.bitrateTestDelay||w<h)){var C=l.forcedAutoLevel;return V===m||-1!==C&&C===m||(H.length&&l.trace("Skipped level(s) "+H.join(",")+" of "+i+' max with CODECS and VIDEO-RANGE:"'+p[H[0]].codecs+'" '+p[H[0]].videoRange+'; not compatible with "'+E+'" '+b),l.info("switch candidate:"+d+"->"+V+" adjustedbw("+Math.round(v)+")-bitrate="+Math.round(v-D)+" ttfb:"+G.toFixed(1)+" avgDuration:"+R.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+w.toFixed(1)+" firstSelection:"+L+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+m)),L&&(l.firstSelection=V),{v:V}}},V=i;V>=t;V--)if(0!==(B=K())&&B)return B.v;return-1},i.deriveNextAutoLevel=function(e){var t=this.hls,i=t.maxAutoLevel,r=t.minAutoLevel;return Math.min(Math.max(e,r),i)},r(t,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,i=e.minAutoLevel,r=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(r,i,t,0,s,1,1);if(n>-1)return n;var a=this.hls.firstLevel,o=Math.min(Math.max(a,i),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+a+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var s=this.hls.levels;if(s.length>Math.max(e,r)&&s[e].loadError<=s[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(F),ct=function(e,t){for(var i=0,r=e.length-1,s=null,n=null;i<=r;){var a=t(n=e[s=(i+r)/2|0]);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function ft(e,t,i,r,s){void 0===i&&(i=0),void 0===r&&(r=0),void 0===s&&(s=.005);var n=null;if(e){n=t[1+e.sn-t[0].sn]||null;var a=e.endDTS-i;a>0&&a<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===gt(i,r,n)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var r=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),i);return e.start<=r}return!1}(n,e,Math.min(s,r))))return n;var o=ct(t,gt.bind(null,i,r));return!o||o===e&&n?n:o}function gt(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=0),i.start<=e&&i.start+i.duration>e)return 0;var r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function pt(e,t,i){var r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}function vt(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){var r,s=e.fragments,n=e.fragmentHint;return n&&(s=s.concat(n)),ct(s,(function(e){return e.cc<t?1:e.cc>t?-1:(r=e,e.end<=i?1:e.start>i?-1:0)})),r||null}return null}function mt(e){switch(e.details){case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_TIMEOUT:case A.LEVEL_LOAD_TIMEOUT:case A.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function yt(e){return e.details.startsWith("key")}function Et(e){return yt(e)&&!!e.frag&&!e.frag.decryptdata}function St(e,t){var i=mt(t);return e.default[(i?"timeout":"error")+"Retry"]}function Tt(e,t){var i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function _t(e){return u(u({},e),{errorRetry:null,timeoutRetry:null})}function Lt(e,t,i,r){if(!e)return!1;var s=null==r?void 0:r.code,n=t<e.maxNumRetry&&(function(e){return bt(e)||!!e&&(e<400||e>499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}function bt(e){return 0===e&&!1===navigator.onLine}var At=function(e){function t(t){var i;return(i=e.call(this,"error-controller",t.logger)||this).hls=void 0,i.playlistError=0,i.hls=t,i.registerListeners(),i}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(I.ERROR,this.onError,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.ERROR,this.onError,this),e.off(I.ERROR,this.onErrorOut,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this))},i.destroy=function(){this.unregisterListeners(),this.hls=null},i.startLoad=function(e){},i.stopLoad=function(){this.playlistError=0},i.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===w?e.level:this.getVariantIndex()},i.getVariantIndex=function(){var e,t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i},i.variantHasKey=function(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;var r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter((function(e){return r.indexOf(e.groupId)>=0})).some((function(e){var i;return null==(i=e.details)?void 0:i.hasKey(t)}))}return!1},i.onManifestLoading=function(){this.playlistError=0},i.onLevelUpdated=function(){this.playlistError=0},i.onError=function(e,t){var i;if(!t.fatal){var r=this.hls,s=t.context;switch(t.details){case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case A.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=It());case A.FRAG_GAP:case A.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=2);case A.LEVEL_EMPTY_ERROR:case A.LEVEL_PARSING_ERROR:var n,a=t.parent===w?t.level:r.loadLevel;return void(t.details===A.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,a)));case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level)));case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.SUBTITLE_LOAD_ERROR:case A.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){var o=r.loadLevelObj;if(o&&(s.type===k&&o.hasAudioGroup(s.groupId)||s.type===D&&o.hasSubtitleGroup(s.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:2,flags:2});case A.KEY_SYSTEM_SESSION_UPDATE_FAILED:case A.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case A.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:2,flags:4});case A.BUFFER_ADD_CODEC_ERROR:case A.REMUX_ALLOC_ERROR:case A.BUFFER_APPEND_ERROR:var l;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(l=t.level)?l:r.loadLevel)));case A.INTERNAL_EXCEPTION:case A.BUFFER_APPENDING_ERROR:case A.BUFFER_FULL_ERROR:case A.LEVEL_SWITCH_ERROR:case A.BUFFER_STALLED_ERROR:case A.BUFFER_SEEK_OVER_HOLE:case A.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=It())}t.type===b.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=It())}},i.getPlaylistRetryOrSwitchAction=function(e,t){var i=St(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Lt(i,r,mt(e),e.response))return{action:5,flags:0,retryConfig:i,retryCount:r};var s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s},i.getFragRetryOrSwitchAction=function(e){var t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],s=t.config,n=s.fragLoadPolicy,a=s.keyLoadPolicy,o=St(yt(e)?a:n,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(r&&(e.details!==A.FRAG_GAP&&r.fragmentError++,!Et(e)&&Lt(o,l,mt(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(e,i);return o&&(h.retryConfig=o,h.retryCount=l),h},i.getLevelSwitchAction=function(e,t){var i=this.hls;null==t&&(t=i.loadLevel);var r=this.hls.levels[t];if(r){var s,n,a=e.details;r.loadError++,a===A.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,h=i.loadLevel,u=i.minAutoLevel,d=i.maxAutoLevel;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);for(var c,f=null==(s=e.frag)?void 0:s.type,g=(f===C&&a===A.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(a===A.BUFFER_ADD_CODEC_ERROR||a===A.BUFFER_APPEND_ERROR))&&l.some((function(e){var t=e.audioCodec;return r.audioCodec!==t})),p="video"===e.sourceBufferName&&(a===A.BUFFER_ADD_CODEC_ERROR||a===A.BUFFER_APPEND_ERROR)&&l.some((function(e){var t=e.codecSet,i=e.audioCodec;return r.codecSet!==t&&r.audioCodec===i})),v=null!=(n=e.context)?n:{},m=v.type,y=v.groupId,E=function(){var t=(S+h)%l.length;if(t!==h&&t>=u&&t<=d&&0===l[t].loadError){var i,s,n=l[t];if(a===A.FRAG_GAP&&f===w&&e.frag){var c=l[t].details;if(c){var v=ft(e.frag,c.fragments,e.frag.start);if(null!=v&&v.gap)return 0}}else{if(m===k&&n.hasAudioGroup(y)||m===D&&n.hasSubtitleGroup(y))return 0;if(f===C&&null!=(i=r.audioGroups)&&i.some((function(e){return n.hasAudioGroup(e)}))||f===M&&null!=(s=r.subtitleGroups)&&s.some((function(e){return n.hasSubtitleGroup(e)}))||g&&r.audioCodec===n.audioCodec||p&&r.codecSet===n.codecSet||!g&&r.codecSet!==n.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(c=E())||1!==c););if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}},i.onErrorOut=function(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===A.FRAG_GAP?/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()):t.fatal=!0}t.fatal&&this.hls.stopLoad()},i.sendAlternateToPenaltyBox=function(e){var t=this.hls,i=e.errorAction;if(i){var r=i.flags,s=i.nextAutoLevel;switch(r){case 0:this.switchLevel(e,s);break;case 2:var n=this.getVariantLevelIndex(e.frag),a=t.levels[n],o=null==a?void 0:a.attrs["HDCP-LEVEL"];if(i.hdcpLevel=o,"NONE"===o)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(o){t.maxHdcpLevel=Xe[Xe.indexOf(o)-1],i.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower');break}case 4:var l=e.decryptdata;if(l){for(var h=this.hls.levels,u=h.length,d=u;d--;){var c,f;this.variantHasKey(h[d],l)&&(this.log("Banned key found in level "+d+" ("+h[d].bitrate+'bps) or audio group "'+(null==(c=h[d].audioGroups)?void 0:c.join(","))+'" ('+(null==(f=e.frag)?void 0:f.type)+" fragment) "+j(l.keyId||[])),h[d].fragmentError++,h[d].loadError++,this.log("Removing level "+d+" with key error ("+e.error+")"),this.hls.removeLevel(d))}var g=e.frag;if(this.hls.levels.length<u)i.resolved=!0;else if(g&&g.type!==w){var p=g.decryptdata;p&&!l.matches(p)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(e,s)}},i.switchLevel=function(e,t){if(void 0!==t&&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,e.details===A.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var i=Ve(e.mimeType),r=this.hls.levels,s=r.length;s--;)r[s][e.sourceBufferName+"Codec"]===i&&(this.log("Removing level "+s+" for "+e.details+' ("'+i+'" not supported)'),this.hls.removeLevel(s))},t}(F);function It(e){var t={action:0,flags:0};return e&&(t.resolved=!0),t}var Rt="NOT_LOADED",Pt="APPENDING",kt="PARTIAL",Dt="OK",wt=function(){function e(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()}var t=e.prototype;return t._registerListeners=function(){var e=this.hls;e&&(e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this))},t._unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this))},t.destroy=function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){var i=this.activePartLists[t];if(i)for(var r=i.length;r--;){var s=i[r];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){return this.getFragAtPos(e,t,!0)},t.getFragAtPos=function(e,t,i){for(var r=this.fragments,s=Object.keys(r),n=s.length;n--;){var a=r[s[n]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){var o=a.body;if(o.start<=e&&e<=o.end)return o}}return null},t.detectEvictedFragments=function(e,t,i,r,s){var n=this;this.timeRanges&&(this.timeRanges[e]=t);var a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(r){var o=n.fragments[r];if(o&&!(a>=o.body.sn))if(o.buffered||o.loaded&&!s){var l=o.range[e];l&&(0!==l.time.length?l.time.some((function(e){var i=!n.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&n.removeFragment(o.body),i})):n.removeFragment(o.body))}else o.body.type===i&&n.removeFragment(o.body)}))},t.detectPartialFragments=function(e){var t=this,i=this.timeRanges;if(i&&"initSegment"!==e.frag.sn){var r=e.frag,s=Mt(r),n=this.fragments[s];if(!(!n||n.buffered&&r.gap)){var a=!r.relurl;Object.keys(i).forEach((function(s){var o=r.elementaryStreams[s];if(o){var l=i[s],h=a||!0===o.partial;n.range[s]=t.getBufferedTimes(r,e.part,h,l)}})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=r.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ct(n)||this.removeParts(r.sn-1,r.type)):this.removeFragment(n.body)}}},t.removeParts=function(e,t){var i=this.activePartLists[t];i&&(this.activePartLists[t]=Ot(i,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var i=Mt(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)},t.getBufferedTimes=function(e,t,i,r){for(var s={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n,h=0;h<r.length;h++){var u=r.start(h)-this.bufferPadding,d=r.end(h)+this.bufferPadding;if(l>=u&&o<=d){s.time.push({startPTS:Math.max(n,r.start(h)),endPTS:Math.min(a,r.end(h))});break}if(n<d&&a>u){var c=Math.max(n,r.start(h)),f=Math.min(a,r.end(h));f>c&&(s.partial=!0,s.time.push({startPTS:c,endPTS:f}))}else if(a<=u)break}return s},t.getPartialFragment=function(e){var t,i,r,s=null,n=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&Ct(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),n<=t&&(s=h.body,n=t)))})),s},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Ct(t))},t.getState=function(e){var t=Mt(e),i=this.fragments[t];return i?i.buffered?Ct(i)?kt:Dt:Pt:Rt},t.isTimeBuffered=function(e,t,i){for(var r,s,n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var i=t.frag,r=t.part?null:t,s=Mt(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var i=t.frag,r=t.part,s=t.timeRanges,n=t.type;if("initSegment"!==i.sn){var a=i.type;if(r){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=s;var l=s[n];this.detectEvictedFragments(n,l,a,r)}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Mt(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,i=Object.keys(t);if(!e)return i.length>0;for(var r=i.length;r--;){var s=t[i[r]];if((null==s?void 0:s.body.type)===e)return!0}return!1},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.removeFragmentsInRange=function(e,t,i,r,s){var n=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=n.fragments[a];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||s)&&n.removeFragment(l)}}))},t.removeFragment=function(e){var t=Mt(e);e.clearElementaryStreamInfo();var i=this.activePartLists[e.type];if(i){var r=e.sn;this.activePartLists[e.type]=Ot(i,(function(e){return e.fragment.sn!==r}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function Ct(e){var t,i,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(r=e.range.audiovideo)&&r.partial)}function Mt(e){return e.type+"_"+e.level+"_"+e.sn}function Ot(e,t){return e.filter((function(e){var i=t(e);return i||e.clearElementaryStreamInfo(),i}))}var xt=function(){function e(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}return e.prototype.decrypt=function(e,t){switch(this.aesMode){case 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},e}(),Ft=function(){function e(){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()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),i=new Uint32Array(4),r=0;r<4;r++)i[r]=t.getUint32(4*r);return i},t.initTable=function(){var e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],u=o[2],d=o[3],c=new Uint32Array(256),f=0,g=0,p=0;for(p=0;p<256;p++)c[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^255&v^99,e[f]=v,t[v]=f;var m=c[f],y=c[m],E=c[y],S=257*c[v]^16843008*v;r[f]=S<<24|S>>>8,s[f]=S<<16|S>>>16,n[f]=S<<8|S>>>24,a[f]=S,S=16843009*E^65537*y^257*m^16843008*f,l[v]=S<<24|S>>>8,h[v]=S<<16|S>>>16,u[v]=S<<8|S>>>24,d[v]=S,f?(f=m^c[c[c[E^m]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;r<t.length&&i;)i=t[r]===this.key[r],r++;if(!i){this.key=t;var s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);var n,a,o,l,h=this.ksRows=4*(s+6+1),u=this.keySchedule=new Uint32Array(h),d=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,p=g[0],v=g[1],m=g[2],y=g[3];for(n=0;n<h;n++)n<s?o=u[n]=t[n]:(l=o,n%s==0?(l=c[(l=l<<8|l>>>24)>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l],l^=f[n/s|0]<<24):s>6&&n%s==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),u[n]=o=(u[n-s]^l)>>>0);for(a=0;a<h;a++)n=h-a,l=3&a?u[n]:u[n-4],d[a]=a<4||n<=4?l:p[c[l>>>24]]^v[c[l>>>16&255]]^m[c[l>>>8&255]]^y[c[255&l]],d[a]=d[a]>>>0}},t.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},t.decrypt=function(e,t,i){for(var r,s,n,a,o,l,h,u,d,c,f,g,p,v,m=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,S=this.invSubMix,T=S[0],_=S[1],L=S[2],b=S[3],A=this.uint8ArrayToUint32Array_(i),I=A[0],R=A[1],P=A[2],k=A[3],D=new Int32Array(e),w=new Int32Array(D.length),C=this.networkToHostOrderSwap;t<D.length;){for(d=C(D[t]),c=C(D[t+1]),f=C(D[t+2]),g=C(D[t+3]),o=d^y[0],l=g^y[1],h=f^y[2],u=c^y[3],p=4,v=1;v<m;v++)r=T[o>>>24]^_[l>>16&255]^L[h>>8&255]^b[255&u]^y[p],s=T[l>>>24]^_[h>>16&255]^L[u>>8&255]^b[255&o]^y[p+1],n=T[h>>>24]^_[u>>16&255]^L[o>>8&255]^b[255&l]^y[p+2],a=T[u>>>24]^_[o>>16&255]^L[l>>8&255]^b[255&h]^y[p+3],o=r,l=s,h=n,u=a,p+=4;r=E[o>>>24]<<24^E[l>>16&255]<<16^E[h>>8&255]<<8^E[255&u]^y[p],s=E[l>>>24]<<24^E[h>>16&255]<<16^E[u>>8&255]<<8^E[255&o]^y[p+1],n=E[h>>>24]<<24^E[u>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[p+2],a=E[u>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&h]^y[p+3],w[t]=C(r^I),w[t+1]=C(a^R),w[t+2]=C(n^P),w[t+3]=C(s^k),I=d,R=c,P=f,k=g,t+=4}return w.buffer},e}(),Nt=function(){function e(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}return e.prototype.expandKey=function(){var e=function(e){switch(e){case 0:return"AES-CBC";case 1:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode "+e)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])},e}(),Bt=function(){function e(e,t){var i=(void 0===t?{}:t).removePKCS7Padding,r=void 0===i||i;if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=r,r)try{var s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}var t=e.prototype;return t.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},t.isSync=function(){return this.useSoftware},t.flush=function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var i,r,s,n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(s=(r=(i=n).byteLength)&&new DataView(i.buffer).getUint8(r-1))?i.slice(0,r-s):i:n},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,i,r){var s=this;return this.useSoftware?new Promise((function(n,a){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);s.softwareDecrypt(o,t,i,r);var l=s.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)},t.softwareDecrypt=function(e,t,i,r){var s=this.currentIV,n=this.currentResult,a=this.remainderData;if(0!==r||16!==t.byteLength)return V.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Te(a,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;s&&(i=s);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ft),l.expandKey(t);var h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null},t.webCryptoDecrypt=function(e,t,i,r){var s=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Nt(this.subtle,t,r)}return this.fastAesKey.expandKey().then((function(t){return s.subtle?(s.logOnce("WebCrypto AES decrypt"),new xt(s.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(n){return V.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+n.name+": "+n.message),s.onWebCryptoError(e,t,i,r)}))},t.onWebCryptoError=function(e,t,i,r){var s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);var n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")},t.getValidChunk=function(e){var t=e,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t},t.logOnce=function(e){this.logEnabled&&(V.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),Ut=Math.pow(2,17),Gt=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t){var i=this,r=e.url;if(!r)return Promise.reject(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,n=s.fLoader,a=s.loader;return new Promise((function(o,l){if(i.loader&&i.loader.destroy(),e.gap){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void l(Kt(e));e.gap=!1}var h=i.loader=n?new n(s):new a(s),d=Ht(e);e.loader=h;var c=_t(s.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Ut};e.stats=h.stats;var g={onSuccess:function(t,r,s,n){i.resetLoader(e,h);var a=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:n})},onError:function(t,s,n,a){i.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:u({url:r,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:n,stats:a}))},onAbort:function(t,r,s){i.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:function(t,r,s){i.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:s,stats:t}))}};t&&(g.onProgress=function(i,r,s,n){return t({frag:e,part:null,payload:s,networkDetails:n})}),h.load(d,f,g)}))},t.loadPart=function(e,t,i){var r=this;this.abort();var s=this.config,n=s.fLoader,a=s.loader;return new Promise((function(o,l){if(r.loader&&r.loader.destroy(),e.gap||t.gap)l(Kt(e,t));else{var h=r.loader=n?new n(s):new a(s),d=Ht(e,t);e.loader=h;var c=_t(s.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ut};t.stats=h.stats,h.load(d,f,{onSuccess:function(s,n,a,l){r.resetLoader(e,h),r.updateStatsFromPart(e,t);var u={frag:e,part:t,payload:s.data,networkDetails:l};i(u),o(u)},onError:function(i,s,n,a){r.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:u({url:d.url,data:void 0},i),error:new Error("HTTP Error "+i.code+" "+i.text),networkDetails:n,stats:a}))},onAbort:function(i,s,n){e.stats.aborted=t.stats.aborted,r.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:n,stats:i}))},onTimeout:function(i,s,n){r.resetLoader(e,h),l(new Vt({type:b.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:i}))}})}}))},t.updateStatsFromPart=function(e,t){var i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){var n=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/s),n),o=(n-a)*Math.round(i.loaded/a);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,h=r.loading;l.start?l.first+=h.first-h.start:(l.start=h.start,l.first=h.first),l.end=h.end},t.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function Ht(e,t){void 0===t&&(t=null);var i,r=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(T(n)&&T(a)){var o,l=n,h=a;if("initSegment"===e.sn&&("AES-128"===(i=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===i)){var u=a-n;u%16&&(h=a+(16-u%16)),0!==n&&(s.resetIV=!0,l=n-16)}s.rangeStart=l,s.rangeEnd=h}return s}function Kt(e,t){var i=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),r={type:b.MEDIA_ERROR,details:A.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Vt(r)}var Vt=function(e){function t(t){var i;return(i=e.call(this,t.error.message)||this).data=void 0,i.data=t,i}return o(t,e),t}(f(Error)),$t=function(e){function t(t,i){var r;return(r=e.call(this,t,i)||this)._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(r),r}o(t,e);var i=t.prototype;return i.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},i.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},i.onHandlerDestroyed=function(){},i.hasInterval=function(){return!!this._tickInterval},i.hasNextTick=function(){return!!this._tickTimer},i.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},i.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},i.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},i.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},i.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},i.doTick=function(){},t}(F),Wt=function(e,t,i,r,s,n){void 0===r&&(r=0),void 0===s&&(s=-1),void 0===n&&(n=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=n},qt={length:0,start:function(){return 0},end:function(){return 0}},jt=function(){function e(){}return e.isBuffered=function(t,i){if(t)for(var r=e.getBuffered(t),s=r.length;s--;)if(i>=r.start(s)&&i<=r.end(s))return!0;return!1},e.bufferedRanges=function(t){if(t){var i=e.getBuffered(t);return e.timeRangesToArray(i)}return[]},e.timeRangesToArray=function(e){for(var t=[],i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t},e.bufferInfo=function(t,i,r){if(t){var s=e.bufferedRanges(t);if(s.length)return e.bufferedInfo(s,i,r)}return{len:0,start:i,end:i,bufferedIndex:-1}},e.bufferedInfo=function(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var r=-1,s=[];if(i)for(var n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(r=n);var a=s.length;if(a){var o=s[a-1].end;e[n].start-o<i?e[n].end>o&&(s[a-1].end=e[n].end):s.push(e[n])}else s.push(e[n])}else s=e;for(var l,h=0,u=t,d=t,c=0;c<s.length;c++){var f=s[c].start,g=s[c].end;if(-1===r&&t>=f&&t<=g&&(r=c),t+i>=f&&t<g)u=f,h=(d=g)-t;else if(t+i<f){l=f;break}}return{len:h,start:u||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:r}},e.getBuffered=function(e){try{return e.buffered||qt}catch(e){return V.log("failed to get media.buffered",e),qt}},e}(),Yt=/\{\$([a-zA-Z0-9-_]+)\}/g;function zt(e){return Yt.test(e)}function Xt(e,t){if(null!==e.variableList||e.hasVariableRefs){var i=e.variableList;return t.replace(Yt,(function(t){var r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+r+'"')),t):s}))}return t}function Qt(e,t,i){var r,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{var a=new self.URL(i).searchParams;if(!a.has(r))throw new Error('"'+r+'" does not match any query parameter in URI: "'+i+'"');s=a.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+t.message))}}else r=t.NAME,s=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+r+'"')):n[r]=s||""}function Jt(e,t,i){var r=t.IMPORT;if(i&&r in i){var s=e.variableList;s||(e.variableList=s={}),s[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+r+'"'))}var Zt=/^(\d+)x(\d+)$/,ei=/(.+?)=(".*?"|.*?)(?:,|$)/g,ti=function(){function e(t,i){"string"==typeof t&&(t=e.parseAttrList(t,i)),n(this,t)}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var i=new Uint8Array(t.length/2),r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(2*r,2*r+2),16);return i}return null},t.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var i=this[e];return i?parseFloat(i):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((function(e,t){return e[t.toLowerCase()]=!0,e}),t)},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=Zt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var i,r={};for(ei.lastIndex=0;null!==(i=ei.exec(e));){var s=i[1].trim(),n=i[2],a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1,o=!1;if(a)n=n.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=Xt(t,n);else if(!o&&!a)switch(s){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":V.warn(e+": attribute "+s+" is missing quotes")}r[s]=n}return r},r(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function ii(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var ri=r((function(e,t,i){var r;if(void 0===i&&(i=0),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:i,t){var s=t.attr;for(var a in s)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==s[a]){V.warn('DATERANGE tag attribute: "'+a+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=a;break}e=n(new ti({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){var o=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);T(o.getTime())&&(this._endDate=o)}}),[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(V.warn('Expected tagAnchor Fragment with PDT set for DateRange "'+this.id+'": '+e),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(T(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&T(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}]),si=function(){function e(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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}var t=e.prototype;return t.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var 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||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1},t.hasKey=function(e){return this.encryptedFragments.some((function(t){var i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)}))},r(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&T(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function ni(e,t){return e.length===t.length&&!e.some((function(e,i){return e!==t[i]}))}function ai(e,t){return!e&&!t||!(!e||!t)&&ni(e,t)}function oi(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function li(e){switch(e){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw new Error("invalid full segment method "+e)}}function hi(e){return Uint8Array.from(atob(e),(function(e){return e.charCodeAt(0)}))}function ui(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}function di(e){var t=function(e,t,i){var r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}var ci="undefined"!=typeof self?self:void 0,fi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},gi="org.w3.clearkey",pi="com.apple.streamingkeydelivery",vi="com.microsoft.playready",mi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function yi(e){switch(e){case pi:return fi.FAIRPLAY;case vi:return fi.PLAYREADY;case mi:return fi.WIDEVINE;case gi:return fi.CLEARKEY}}function Ei(e){switch(e){case fi.FAIRPLAY:return pi;case fi.PLAYREADY:return vi;case fi.WIDEVINE:return mi;case fi.CLEARKEY:return gi}}function Si(e){var t=e.drmSystems,i=e.widevineLicenseUrl,r=t?[fi.FAIRPLAY,fi.WIDEVINE,fi.PLAYREADY,fi.CLEARKEY].filter((function(e){return!!t[e]})):[];return!r[fi.WIDEVINE]&&i&&r.push(fi.WIDEVINE),r}var Ti,_i=null!=ci&&null!=(Ti=ci.navigator)&&Ti.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null,Li={},bi=function(){function e(e,t,i,r,s,n){void 0===r&&(r=[1]),void 0===s&&(s=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!oi(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(Y(n)))}e.clearKeyUriToKeyIdMap=function(){Li={}},e.setKeyIdForUri=function(e,t){Li[e]=t};var t=e.prototype;return t.matches=function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ni(e.keyFormatVersions,this.keyFormatVersions)&&ai(e.iv,this.iv)&&ai(e.keyId,this.keyId)},t.isSupported=function(){if(this.method){if(oi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case pi:case mi:case vi:case gi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},t.getDecryptData=function(t){if(!this.encrypted||!this.uri)return null;if(oi(this.method)){var i=this.iv;return i||("number"!=typeof t&&(V.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0),i=function(e){for(var t=new Uint8Array(16),i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.pssh&&this.keyId)return this;var r=function(e){var t,i,r=e.split(":"),s=null;if("data"===r[0]&&2===r.length){var n=r[1].split(";"),a=n[n.length-1].split(",");if(2===a.length){var o="base64"===a[0],l=a[1];o?(n.splice(-1,1),s=hi(l)):(t=ui(l).subarray(0,16),(i=new Uint8Array(16)).set(t,16-t.length),s=i)}}return s}(this.uri);if(r)switch(this.keyFormat){case mi:if(this.pssh=r,!this.keyId){var s=function(e){var t=[];if(e instanceof ArrayBuffer)for(var i=e.byteLength,r=0;r+32<i;){var s=Re(new DataView(e,r));t.push(s),r+=s.size}return t}(r.buffer);if(s.length){var n,a=s[0];this.keyId=null!=(n=a.kids)&&n.length?a.kids[0]:null}}if(!this.keyId){var o=r.length-22;this.keyId=r.subarray(o,o+16)}break;case vi:var l=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");var r,s;r=new Uint8Array,s=new Uint8Array;var n=new Uint8Array(4);return i.byteLength>0&&new DataView(n.buffer).setUint32(0,i.byteLength,!1),function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var s=i.length,n=8,a=s;a--;)n+=i[a].byteLength;var o=new Uint8Array(n);for(o[0]=n>>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=255&n,o.set(e,4),a=0,n=8;a<s;a++)o.set(i[a],n),n+=i[a].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,s,r,n,i)}(l,0,r),this.keyId=function(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),s=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){var n=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(n){var a=hi(n).subarray(0,16);return di(a),a}}return null}(r);break;default:var h=r.subarray(0,16);if(16!==h.length){var u=new Uint8Array(16);u.set(h,16-h.length),h=u}this.keyId=h}if(!this.keyId||16!==this.keyId.byteLength){var d=Li[this.uri];if(!d){var c=Object.keys(Li).length%Number.MAX_SAFE_INTEGER;d=new Uint8Array(16),new DataView(d.buffer,12,4).setUint32(0,c),e.setKeyIdForUri(this.uri,d)}this.keyId=d}return this},e}(),Ai=/#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,Ii=/#EXT-X-MEDIA:(.*)/g,Ri=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ki=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|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("|")),Di=function(){function e(){}return e.findGroup=function(e,t){for(var i=0;i<e.length;i++){var r=e[i];if(r.id===t)return r}},e.resolve=function(e,t){return S.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.isMediaPlaylist=function(e){return Ri.test(e)},e.parseMasterPlaylist=function(t,i){var r,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:zt(t)},n=[];if(Ai.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;for(;null!=(r=Ai.exec(t));)if(r[1]){var a,o=new ti(r[1],s),l=Xt(s,r[2]),h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,i)},u=o.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),xi(o.CODECS,h);var d=o["SUPPLEMENTAL-CODECS"];d&&(h.supplemental={},xi(d,h.supplemental)),null!=(a=h.unknownCodecs)&&a.length||n.push(h),s.levels.push(h)}else if(r[3]){var c=r[3],f=r[4];switch(c){case"SESSION-DATA":var g=new ti(f,s),p=g["DATA-ID"];p&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[p]=g);break;case"SESSION-KEY":var v=Mi(f,i,s);v.encrypted&&v.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(v)):V.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+f+'"');break;case"DEFINE":Qt(s,new ti(f,s),i);break;case"CONTENT-STEERING":var m=new ti(f,s);s.contentSteering={uri:e.resolve(m["SERVER-URI"],i),pathwayId:m["PATHWAY-ID"]||"."};break;case"START":s.startTimeOffset=Oi(f)}}var y=n.length>0&&n.length<s.levels.length;return s.levels=y?n:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s},e.parseMasterPlaylistMedia=function(t,i,r){var s,n={},a=r.levels,o={AUDIO:a.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),SUBTITLES:a.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),"CLOSED-CAPTIONS":[]},l=0;for(Ii.lastIndex=0;null!==(s=Ii.exec(t));){var h=new ti(s[1],r),u=h.TYPE;if(u){var d=o[u],c=n[u]||[];n[u]=c;var f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],p=h.CHANNELS,v=h.CHARACTERISTICS,m=h["INSTREAM-ID"],y={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:u,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?e.resolve(h.URI,i):""};if(g&&(y.assocLang=g),p&&(y.channels=p),v&&(y.characteristics=v),m&&(y.instreamId=m),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Fi(y,E,"audioCodec"),Fi(y,E,"textCodec")}c.push(y)}}return n},e.parseLevelPlaylist=function(e,t,i,r,s,a){var o,l,h,u,d,c={url:t},f=new si(t),g=f.fragments,p=[],v=null,m=0,y=0,E=0,S=0,_=0,L=null,b=new te(r,c),A=-1,I=!1,R=null;if(Pi.lastIndex=0,f.m3u8=e,f.hasVariableRefs=zt(e),"#EXTM3U"!==(null==(o=Pi.exec(e))?void 0:o[0]))return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;null!==(l=Pi.exec(e));){I&&(I=!1,(b=new te(r,c)).playlistOffset=E,b.setStart(E),b.sn=m,b.cc=S,_&&(b.bitrate=_),b.level=i,v&&(b.initSegment=v,v.rawProgramDateTime&&(b.rawProgramDateTime=v.rawProgramDateTime,v.rawProgramDateTime=null),R&&(b.setByteRange(R),R=null)));var P=l[1];if(P){b.duration=parseFloat(P);var k=(" "+l[2]).slice(1);b.title=k||null,b.tagList.push(k?["INF",P,k]:["INF",P])}else if(l[3]){if(T(b.duration)){b.playlistOffset=E,b.setStart(E),u&&Ui(b,u,f),b.sn=m,b.level=i,b.cc=S,g.push(b);var D=(" "+l[3]).slice(1);b.relurl=Xt(f,D),Ni(b,L,p),L=b,E+=b.duration,m++,y=0,I=!0}}else{if(!(l=l[0].match(ki))){V.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);var w=(" "+l[h]).slice(1),C=(" "+l[h+1]).slice(1),M=l[h+2]?(" "+l[h+2]).slice(1):null;switch(w){case"BYTERANGE":L?b.setByteRange(C,L):b.setByteRange(C);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=C,b.tagList.push(["PROGRAM-DATE-TIME",C]),-1===A&&(A=g.length);break;case"PLAYLIST-TYPE":f.type&&Gi(f,w,l),f.type=C.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?Gi(f,w,l):g.length>0&&Hi(f,w,l),m=f.startSN=parseInt(C);break;case"SKIP":f.skippedSegments&&Gi(f,w,l);var O=new ti(C,f),x=O.decimalInteger("SKIPPED-SEGMENTS");if(T(x)){f.skippedSegments+=x;for(var F=x;F--;)g.push(null);m+=x}var N=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");N&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(N.split("\t")));break;case"TARGETDURATION":0!==f.targetduration&&Gi(f,w,l),f.targetduration=Math.max(parseInt(C),1);break;case"VERSION":null!==f.version&&Gi(f,w,l),f.version=parseInt(C);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":f.live||Gi(f,w,l),f.live=!1;break;case"#":(C||M)&&b.tagList.push(M?[C,M]:[C]);break;case"DISCONTINUITY":S++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([w]);break;case"BITRATE":b.tagList.push([w,C]),_=1e3*parseInt(C),T(_)?b.bitrate=_:_=0;break;case"DATERANGE":var B=new ti(C,f),U=new ri(B,f.dateRanges[B.ID],f.dateRangeTagCount);f.dateRangeTagCount++,U.isValid||f.skippedSegments?f.dateRanges[U.id]=U:V.warn('Ignoring invalid DATERANGE tag: "'+C+'"'),b.tagList.push(["EXT-X-DATERANGE",C]);break;case"DEFINE":var G=new ti(C,f);"IMPORT"in G?Jt(f,G,a):Qt(f,G,t);break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?Gi(f,w,l):g.length>0&&Hi(f,w,l),f.startCC=S=parseInt(C);break;case"KEY":var H=Mi(C,t,f);if(H.isSupported()){if("NONE"===H.method){u=void 0;break}u||(u={});var K=u[H.keyFormat];null!=K&&K.matches(H)||(K&&(u=n({},u)),u[H.keyFormat]=H)}else V.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'+C+'"');break;case"START":f.startTimeOffset=Oi(C);break;case"MAP":var $=new ti(C,f);if(b.duration){var W=new te(r,c);Bi(W,$,i,u),v=W,b.initSegment=v,v.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=v.rawProgramDateTime)}else{var q=b.byteRangeEndOffset;if(q){var j=b.byteRangeStartOffset;R=q-j+"@"+j}else R=null;Bi(b,$,i,u),v=b,I=!0}v.cc=S;break;case"SERVER-CONTROL":d&&Gi(f,w,l),d=new ti(C),f.canBlockReload=d.bool("CAN-BLOCK-RELOAD"),f.canSkipUntil=d.optionalFloat("CAN-SKIP-UNTIL",0),f.canSkipDateRanges=f.canSkipUntil>0&&d.bool("CAN-SKIP-DATERANGES"),f.partHoldBack=d.optionalFloat("PART-HOLD-BACK",0),f.holdBack=d.optionalFloat("HOLD-BACK",0);break;case"PART-INF":f.partTarget&&Gi(f,w,l);var Y=new ti(C);f.partTarget=Y.decimalFloatingPoint("PART-TARGET");break;case"PART":var z=f.partList;z||(z=f.partList=[]);var X=y>0?z[z.length-1]:void 0,Q=y++,J=new ti(C,f),Z=new ie(J,b,c,Q,X);z.push(Z),b.duration+=Z.duration;break;case"PRELOAD-HINT":var ee=new ti(C,f);f.preloadHint=ee;break;case"RENDITION-REPORT":var re=new ti(C,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(re);break;default:V.warn("line parsed but not handled: "+l)}}}L&&!L.relurl?(g.pop(),E-=L.duration,f.partList&&(f.fragmentHint=L)):f.partList&&(Ni(b,L,p),b.cc=S,f.fragmentHint=b,u&&Ui(b,u,f)),f.targetduration||(f.playlistParsingError=new Error("Missing Target Duration"));var se=g.length,ne=g[0],ae=g[se-1];if((E+=f.skippedSegments*f.targetduration)>0&&se&&ae){f.averagetargetduration=E/se;var oe=ae.sn;f.endSN="initSegment"!==oe?oe:0,f.live||(ae.endList=!0),A>0&&(function(e,t){for(var i=e[t],r=t;r--;){var s=e[r];if(!s)return;s.programDateTime=i.programDateTime-1e3*s.duration,i=s}}(g,A),ne&&p.unshift(ne))}return f.fragmentHint&&(E+=f.fragmentHint.duration),f.totalduration=E,p.length&&f.dateRangeTagCount&&ne&&wi(p,f),f.endCC=S,f},e}();function wi(e,t){var i=e.length;if(!i){if(!t.hasProgramDateTime)return;var r=t.fragments[t.fragments.length-1];e.push(r),i++}for(var s=e[i-1],n=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges),o=a.length;o--;){var l=t.dateRanges[a[o]],h=l.startDate.getTime();l.tagAnchor=s.ref;for(var u=i;u--;){var d;if((null==(d=e[u])?void 0:d.sn)<t.startSN)break;var c=Ci(t,h,e,u,n);if(-1!==c){l.tagAnchor=t.fragments[c].ref;break}}}}function Ci(e,t,i,r,s){var n=i[r];if(n){var a,o=n.programDateTime;if((t>=o||0===r)&&t<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||s)-n.start)){var l=i[r].sn-e.startSN;if(l<0)return-1;var h=e.fragments;if(h.length>i.length)for(var u=(i[r+1]||h[h.length-1]).sn-e.startSN;u>l;u--){var d=h[u].programDateTime;if(t>=d&&t<d+1e3*h[u].duration)return u}return l}}return-1}function Mi(e,t,i){var r,s,n=new ti(e,i),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,u=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&V.error("Invalid IV: "+n.IV);var d=o?Di.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new bi(a,d,u,c,l,n.KEYID)}function Oi(e){var t=new ti(e).decimalFloatingPoint("TIME-OFFSET");return T(t)?t:null}function xi(e,t){var i=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var r=i.filter((function(t){return De(t,e)}));r.length&&(t[e+"Codec"]=r.map((function(e){return e.split("/")[0]})).join(","),i=i.filter((function(e){return-1===r.indexOf(e)})))})),t.unknownCodecs=i}function Fi(e,t,i){var r=t[i];r&&(e[i]=r)}function Ni(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Bi(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function Ui(e,t,i){e.levelkeys=t;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||r.push(e)}function Gi(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must not appear more than once ("+i[0]+")")}function Hi(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must appear before the first Media Segment ("+i[0]+")")}function Ki(e,t){var i=t.startPTS;if(T(i)){var r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&r.setDuration(s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Vi(e,t,i,r,s,n,a){r-i<=0&&(a.warn("Fragment should have a positive duration",t),r=i+t.duration,n=s+t.duration);var o=i,l=r,h=t.startPTS,u=t.endPTS;if(T(h)){var d=Math.abs(h-i);e&&d>e.totalduration?a.warn("media timestamps and playlist times differ by "+d+"s for level "+t.level+" "+e.url):T(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,o=Math.max(i,h),i=Math.min(i,h),s=void 0!==t.startDTS?Math.min(s,t.startDTS):s,l=Math.min(r,u),r=Math.max(r,u),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}var c=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=s,t.endPTS=r,t.minEndPTS=l,t.endDTS=n;var f,g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;var p=g-e.startSN,v=e.fragments;for(v[p]=t,f=p;f>0;f--)Ki(v[f],v[f-1]);for(f=p;f<v.length-1;f++)Ki(v[f],v[f+1]);return e.fragmentHint&&Ki(v[v.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function $i(e,t,i){if(e!==t){for(var r,s=null,a=e.fragments,o=a.length-1;o>=0;o--){var l=a[o].initSegment;if(l){s=l;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){for(var r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=s;h<=n;h++){var u=l[a+h],d=o[h];if(r&&!d&&u&&(d=t.fragments[h]=u),u&&d){i(u,d,h,o);var c=u.relurl,f=d.relurl;if(c&&Zi(c,f))return void(t.playlistParsingError=Wi("media sequence mismatch "+d.sn+":",e,t,0,d));if(u.cc!==d.cc)return void(t.playlistParsingError=Wi("discontinuity sequence mismatch ("+u.cc+"!="+d.cc+")",e,t,0,d))}}}(e,t,(function(e,i,n,a){if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){for(var o=e.cc-i.cc,l=n;l<a.length;l++)a[l].cc+=o;t.endCC=a[a.length-1].cc}T(e.startPTS)&&T(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(r=i),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,s=e.initSegment)}));var h=t.fragments,u=t.fragmentHint?h.concat(t.fragmentHint):h;if(s&&u.forEach((function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=s)?void 0:t.relurl)||(e.initSegment=s)})),t.skippedSegments){if(t.deltaUpdateFailed=h.some((function(e){return!e})),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var d=t.skippedSegments;d--;)h.shift();t.startSN=h[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){var r=t.dateRanges,s=t.recentlyRemovedDateranges,a=n({},e);s&&s.forEach((function(e){delete a[e]}));var o=Object.keys(a).length;return o?(Object.keys(r).forEach((function(e){var t=a[e],s=new ri(r[e].attr,t);s.isValid?(a[e]=s,t||(s.tagOrder+=o)):i.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+it(r[e].attr)+'"')})),a):r}(e.dateRanges,t,i));var c=e.fragments.filter((function(e){return e.rawProgramDateTime}));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var f=1;f<u.length;f++)null===u[f].programDateTime&&Ni(u[f],u[f-1],c);wi(c,t)}t.endCC=h[h.length-1].cc}if(!t.startCC){var g,p=zi(e,t.startSN-1);t.startCC=null!=(g=null==p?void 0:p.cc)?g:h[0].cc}!function(e,t,i){if(e&&t)for(var r=0,s=0,n=e.length;s<=n;s++){var a=e[s],o=t[s+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):r--}}(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),r?Vi(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,i):qi(e,t),h.length&&(t.totalduration=t.edge-h[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var v=t.advancedDateTime;if(t.advanced&&v){var m=t.edge;t.driftStart||(t.driftStartTime=v,t.driftStart=m),t.driftEndTime=v,t.driftEnd=m}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Wi(e,t,i,r,s){return new Error(e+" "+s.url+"\nPlaylist starting @"+t.startSN+"\n"+t.m3u8+"\n\nPlaylist starting @"+i.startSN+"\n"+i.m3u8)}function qi(e,t,i){void 0===i&&(i=!0);var r=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,n=r>=0,a=0;if(n&&r<s.length)a=s[r].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}ji(t,a)}function ji(e,t){if(t){for(var i=e.fragments,r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Yi(e,t){void 0===t&&(t=1/0);var i=1e3*e.targetduration;if(e.updated){var r=e.fragments;if(r.length&&4*i>t){var s=1e3*r[r.length-1].duration;s<i&&(i=s)}}else i/=2;return Math.round(i)}function zi(e,t,i){if(!e)return null;var r=e.fragments[t-e.startSN];return r||((r=e.fragmentHint)&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null)}function Xi(e,t,i){return e?Qi(e.partList,t,i):null}function Qi(e,t,i){if(e)for(var r=e.length;r--;){var s=e[r];if(s.index===i&&s.fragment.sn===t)return s}return null}function Ji(e){e.forEach((function(e,t){var i;null==(i=e.details)||i.fragments.forEach((function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function Zi(e,t){return!(e===t||!t)&&er(e)!==er(t)}function er(e){return e.replace(/\?[^?]*$/,"")}function tr(e,t){for(var i=0,r=e.length;i<r;i++){var s;if((null==(s=e[i])?void 0:s.cc)===t)return e[i]}return null}function ir(e,t){var i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function rr(e,t){for(var i=t.fragments,r=0,s=i.length;r<s;r++)ir(i[r],e);t.fragmentHint&&ir(t.fragmentHint,e),t.alignedSliding=!0}function sr(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var i=Math.min(t.endCC,e.endCC),r=tr(t.fragments,i),s=tr(e.fragments,i);r&&s&&(V.log("Aligning playlist at start of dicontinuity sequence "+i),rr(r.start-s.start,e))}}function nr(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i=e.fragments,r=t.fragments;if(i.length&&r.length){var s,n,a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(s=tr(r,a),n=tr(i,a)),s&&n||(n=tr(i,(s=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.length/2)]);var o=s.programDateTime,l=n.programDateTime;o&&l&&rr((l-o)/1e3-(n.start-s.start),e)}}}function ar(e,t,i){or(e,t,i),e.addEventListener(t,i)}function or(e,t,i){e.removeEventListener(t,i)}var lr={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},hr=function(e){function t(t,i,r,s,n){var a;return(a=e.call(this,s,t.logger)||this).hls=void 0,a.fragPrevious=null,a.fragCurrent=null,a.fragmentTracker=void 0,a.transmuxer=null,a._state=lr.STOPPED,a.playlistType=void 0,a.media=null,a.mediaBuffer=null,a.config=void 0,a.bitrateTest=!1,a.lastCurrentTime=0,a.nextLoadPosition=0,a.startPosition=0,a.startTimeOffset=null,a.retryDate=0,a.levels=null,a.fragmentLoader=void 0,a.keyLoader=void 0,a.levelLastLoaded=null,a.startFragRequested=!1,a.decrypter=void 0,a.initPTS=[],a.buffering=!0,a.loadingParts=!1,a.loopSn=void 0,a.onMediaSeeking=function(){var e=a,t=e.config,i=e.fragCurrent,r=e.media,s=e.mediaBuffer,n=e.state,o=r?r.currentTime:0,l=jt.bufferInfo(s||r,o,t.maxBufferHole),h=!l.len;if(a.log("Media seeking to "+(T(o)?o.toFixed(3):o)+", state: "+n+", "+(h?"out of":"in")+" buffer"),a.state===lr.ENDED)a.resetLoadingState();else if(i){var u=t.maxFragLookUpTolerance,d=i.start-u,c=i.start+i.duration+u;if(h||c<l.start||d>l.end){var f=o>c;(o<d||f)&&(f&&i.loader&&(a.log("Cancelling fragment load for seek (sn: "+i.sn+")"),i.abortRequests(),a.resetLoadingState()),a.fragPrevious=null)}}if(r&&(a.fragmentTracker.removeFragmentsInRange(o,1/0,a.playlistType,!0),o>a.lastCurrentTime&&(a.lastCurrentTime=o),!a.loadingParts)){var g=Math.max(l.end,o),p=a.shouldLoadParts(a.getLevelDetails(),g);p&&(a.log("LL-Part loading ON after seeking to "+o.toFixed(2)+" with buffer @"+g.toFixed(2)),a.loadingParts=p)}a.hls.hasEnoughToStart||(a.log("Setting "+(h?"startPosition":"nextLoadPosition")+" to "+o+" for seek without enough to start"),a.nextLoadPosition=o,h&&(a.startPosition=o)),h&&a.state===lr.IDLE&&a.tickImmediate()},a.onMediaEnded=function(){a.log("setting startPosition to 0 because media ended"),a.startPosition=a.lastCurrentTime=0},a.playlistType=n,a.hls=t,a.fragmentLoader=new Gt(t.config),a.keyLoader=r,a.fragmentTracker=i,a.config=t.config,a.decrypter=new Bt(t.config),a}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.ERROR,this.onError,this)},i.doTick=function(){this.onTickEnd()},i.onTickEnd=function(){},i.startLoad=function(e){},i.stopLoad=function(){if(this.state!==lr.STOPPED){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=lr.STOPPED}},i.pauseBuffering=function(){this.buffering=!1},i.resumeBuffering=function(){this.buffering=!0},i._streamEnded=function(e,t){if(t.live||!this.media)return!1;var i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;var s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=jt.bufferedInfo(s,e.start,0));var n=e.nextStart;if(n&&n>r&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var a=t.partList;if(null!=a&&a.length){var o=a[a.length-1];return jt.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)},i.getLevelDetails=function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details},i.onMediaAttached=function(e,t){var i=this.media=this.mediaBuffer=t.media;ar(i,"seeking",this.onMediaSeeking),ar(i,"ended",this.onMediaEnded);var r=this.config;this.levels&&r.autoStartLoad&&this.state===lr.STOPPED&&this.startLoad(r.startPosition)},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),or(r,"seeking",this.onMediaSeeking),or(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},i.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},i.onError=function(e,t){},i.onManifestLoaded=function(e,t){this.startTimeOffset=t.startTimeOffset},i.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),e.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},i.onHandlerDestroyed=function(){this.state=lr.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,e.prototype.onHandlerDestroyed.call(this)},i.loadFragment=function(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)},i._loadFragForPlayback=function(e,t,i){var r=this;this._doFragLoad(e,t,i,(function(e){var t=e.frag;if(r.fragContextChanged(t))return r.warn(t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+r.fragInfo(t,!1,e.part)+") was dropped during download."),void r.fragmentTracker.removeFragment(t);t.stats.chunkCount++,r._handleFragmentLoadProgress(e)})).then((function(e){if(e){var t=r.state,i=e.frag;r.fragContextChanged(i)?(t===lr.FRAG_LOADING||!r.fragCurrent&&t===lr.PARSING)&&(r.fragmentTracker.removeFragment(i),r.state=lr.IDLE):("payload"in e&&(r.log("Loaded "+i.type+" sn: "+i.sn+" of "+r.playlistLabel()+" "+i.level),r.hls.trigger(I.FRAG_LOADED,e)),r._handleFragmentLoadComplete(e))}})).catch((function(t){r.state!==lr.STOPPED&&r.state!==lr.ERROR&&(r.warn("Frag error: "+((null==t?void 0:t.message)||t)),r.resetFragmentLoading(e))}))},i.clearTrackerIfNeeded=function(e){var t,i=this.fragmentTracker;if(i.getState(e)===Pt){var r=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,r),n=Math.max(e.duration,s?s.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?e.sn-a.sn:0)||this.reduceMaxBufferLength(n,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===kt&&i.removeFragment(e))},i.checkLiveUpdate=function(e){if(e.updated&&!e.live){var 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)},i.waitForLive=function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)},i.flushMainBuffer=function(e,t,i){if(void 0===i&&(i=null),e-t){var r={startOffset:e,endOffset:t,type:i};this.hls.trigger(I.BUFFER_FLUSHING,r)}},i._loadInitSegment=function(e,t){var i=this;this._doFragLoad(e,t).then((function(e){var t=null==e?void 0:e.frag;if(!t||i.fragContextChanged(t)||!i.levels)throw new Error("init load aborted");return e})).then((function(e){var t=i.hls,r=e.frag,s=e.payload,n=r.decryptdata;if(s&&s.byteLength>0&&null!=n&&n.key&&n.iv&&oi(n.method)){var a=self.performance.now();return i.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,li(n.method)).catch((function(e){throw t.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e})).then((function(s){var n=self.performance.now();return t.trigger(I.FRAG_DECRYPTED,{frag:r,payload:s,stats:{tstart:a,tdecrypt:n}}),e.payload=s,i.completeInitSegmentLoad(e)}))}return i.completeInitSegmentLoad(e)})).catch((function(t){i.state!==lr.STOPPED&&i.state!==lr.ERROR&&(i.warn(t),i.resetFragmentLoading(e))}))},i.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==lr.STOPPED&&(this.state=lr.IDLE),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()},i.unhandledEncryptionError=function(e,t){var i,r,s=e.tracks;if(s&&!t.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var n=this.media,a=new Error("Encrypted track with no key in "+this.fragInfo(t)+" (media "+(n?"attached mediaKeys: "+n.mediaKeys:"detached")+")");return this.warn(a.message),!(!n||n.mediaKeys||(this.hls.trigger(I.ERROR,{type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,frag:t}),this.resetTransmuxer(),0))}return!1},i.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},i.fragBufferedComplete=function(e,t){var i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+" > buffer:"+(i?function(e){for(var t="",i=e.length,r=0;r<i;r++)t+="["+e.start(r).toFixed(3)+"-"+e.end(r).toFixed(3)+"]";return t}(jt.getBuffered(i)):"(detached)")+")"),ee(e)){var r;if(e.type!==M){var s=e.elementaryStreams;if(!Object.keys(s).some((function(e){return!!s[e]})))return void(this.state=lr.IDLE)}var n=null==(r=this.levels)?void 0:r[e.level];null!=n&&n.fragmentError&&(this.log("Resetting level fragment error count of "+n.fragmentError+" on frag buffered"),n.fragmentError=0)}this.state=lr.IDLE},i._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var i=e.frag,r=e.part,s=e.partsLoaded,n=!s||0===s.length||s.some((function(e){return!e})),a=new Wt(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}},i._handleFragmentLoadProgress=function(e){},i._doFragLoad=function(e,t,i,r){var s,n=this;void 0===i&&(i=null),this.fragCurrent=e;var a=t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var o=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key)e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");else if(this.log("Loading key for "+e.sn+" of ["+a.startSN+"-"+a.endSN+"], "+this.playlistLabel()+" "+e.level),this.state=lr.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(I.KEY_LOADED,e),n.state===lr.KEY_LOADING&&(n.state=lr.IDLE),e})),this.hls.trigger(I.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);var l,h=this.fragPrevious;if(ee(e)&&(!h||e.sn!==h.sn)){var u=this.shouldLoadParts(t.details,e.end);u!==this.loadingParts&&(this.log("LL-Part loading "+(u?"ON":"OFF")+" loading sn "+(null==h?void 0:h.sn)+"->"+e.sn),this.loadingParts=u)}if(i=Math.max(e.start,i||0),this.loadingParts&&ee(e)){var d=a.partList;if(d&&r){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);var c=this.getNextPart(d,e,i);if(c>-1){var f,g=d[c];return e=this.fragCurrent=g.fragment,this.log("Loading "+e.type+" sn: "+e.sn+" part: "+g.index+" ("+c+"/"+(d.length-1)+") of "+this.fragInfo(e,!1,g)+") cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(i.toFixed(3))),this.nextLoadPosition=g.start+g.duration,this.state=lr.FRAG_LOADING,f=o?o.then((function(i){return!i||n.fragContextChanged(i.frag)?null:n.doFragPartsLoad(e,g,t,r)})).catch((function(e){return n.handleFragLoadError(e)})):this.doFragPartsLoad(e,g,t,r).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(I.FRAG_LOADING,{frag:e,part:g,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!e.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}if(ee(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+i.toFixed(2)+" Check buffer at sn: "+e.sn+" loaded parts: "+(null==(l=a.partList)?void 0:l.filter((function(e){return e.loaded})).map((function(e){return"["+e.start+"-"+e.end+"]"})))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log("Loading "+e.type+" sn: "+e.sn+" of "+this.fragInfo(e,!1)+") cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(i.toFixed(3))),T(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=lr.FRAG_LOADING;var p,v=this.config.progressive;return p=v&&o?o.then((function(t){return!t||n.fragContextChanged(t.frag)?null:n.fragmentLoader.load(e,r)})).catch((function(e){return n.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,v?r:void 0),o]).then((function(e){var t=e[0];return!v&&r&&r(t),t})).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(I.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):p},i.doFragPartsLoad=function(e,t,i,r){var s=this;return new Promise((function(n,a){var o,l=[],h=null==(o=i.details)?void 0:o.partList,u=function(t){s.fragmentLoader.loadPart(e,t,r).then((function(r){l[t.index]=r;var a=r.part;s.hls.trigger(I.FRAG_LOADED,r);var o=Xi(i.details,e.sn,t.index+1)||Qi(h,e.sn,t.index+1);if(!o)return n({frag:e,part:a,partsLoaded:l});u(o)})).catch(a)};u(t)}))},i.handleFragLoadError=function(e){if("data"in e){var t=e.data;t.frag&&t.details===A.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===b.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(I.ERROR,t)}else this.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},i._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===lr.PARSING){var i=t.frag,r=t.part,s=t.level,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n);var a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+i.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(i,r,s,e.partial)}else this.fragCurrent||this.state===lr.STOPPED||this.state===lr.ERROR||(this.state=lr.IDLE)},i.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i,r,s=e.partList[0];if(s.fragment.type===M)return!1;if(t>=s.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}return!1},i.getCurrentContext=function(e){var t=this.levels,i=this.fragCurrent,r=e.level,s=e.sn,n=e.part;if(null==t||!t[r])return this.warn("Levels object was unset while buffering fragment "+s+" of "+this.playlistLabel()+" "+r+". The current chunk will not be buffered."),null;var a=t[r],o=a.details,l=n>-1?Xi(o,s,n):null,h=l?l.fragment:zi(o,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null},i.bufferFragmentData=function(e,t,i,r,s){if(this.state===lr.PARSING){var n=e.data1,a=e.data2,o=n;if(a&&(o=Te(n,a)),o.length){var l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:i,chunkMeta:r,offset:h,parent:t.type,data:o};if(this.hls.trigger(I.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}}},i.flushBufferGap=function(e){var t=this.media;if(t)if(jt.isBuffered(t,t.currentTime)){var i=t.currentTime,r=jt.bufferInfo(t,i,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,r.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}else this.flushMainBuffer(0,e.start)},i.getFwdBufferInfo=function(e,t){var i,r=this.getLoadPosition();if(!T(r))return null;var s=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,s)},i.getFwdBufferInfoAtPos=function(e,t,i,r){var s=jt.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){var n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(s.nextStart<=n.end||n.gap)){var a=Math.max(Math.min(s.nextStart,n.end)-t,r);return jt.bufferInfo(e,t,a)}}return s},i.getMaxBufferLength=function(e){var t,i=this.config;return t=e?Math.max(8*i.maxBufferSize/e,i.maxBufferLength):i.maxBufferLength,Math.min(t,i.maxMaxBufferLength)},i.reduceMaxBufferLength=function(e,t){var i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn("Reduce max buffer length to "+s+"s"),!0)},i.getAppendedFrag=function(e,t){void 0===t&&(t=w);var i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i},i.getNextFragment=function(e,t){var i=t.fragments,r=i.length;if(!r)return null;var s=this.config,n=i[0].start,a=s.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=s.initialLiveManifestSize;if(r<l)return this.warn("Not enough fragments to start playback (have: "+r+", need: "+l+")"),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var h;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);var u=this.hls.startPosition,d=this.hls.liveSyncPosition,c=o?(-1!==u&&u>=n?u:d)||o.start:e;this.log("Setting startPosition to "+c+" to match start frag at live edge. mainStart: "+u+" liveSyncPosition: "+d+" frag.start: "+(null==(h=o)?void 0:h.start)),this.startPosition=this.nextLoadPosition=c}}else e<=n&&(o=i[0]);if(!o){var f=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,f,t)}var g=this.filterReplacedPrimary(o,t);if(!g&&o){var p=o.sn-t.startSN;g=this.filterReplacedPrimary(i[p+1]||null,t)}return this.mapToInitFragWhenRequired(g)},i.isLoopLoading=function(e,t){var i=this.fragmentTracker.getState(e);return(i===Dt||i===kt&&!!e.gap)&&this.nextLoadPosition>t},i.getNextFragmentLoopLoading=function(e,t,i,r,s){var n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t))&&!n.gap&&i.nextStart){var a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==a&&i.len+a.len>=s){var o=n.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+r+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,n},i.filterReplacedPrimary=function(e,t){if(!e)return e;if(ur(this.config)&&e.type!==M){var i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){var s=r.event;if(s){if(s.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}var n=null==i?void 0:i.playerQueue;if(n)for(var a=n.length;a--;){var o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e},i.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment},i.getNextPart=function(e,t,i){for(var r=-1,s=!1,n=!0,a=0,o=e.length;a<o;a++){var l=e[a];if(n=n&&!l.independent,r>-1&&i<l.start)break;var h=l.loaded;h?r=-1:(s||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn("Need buffer at "+i+" but next unloaded part starts at "+l.start),r=a),s=h}return r},i.loadedEndOfParts=function(e,t){for(var i,r=e.length;r--;){if(!(i=e[r]).loaded)return!1;if(t>i.start)return!0}return!1},i.getInitialLiveFragment=function(e){var t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+i.programDateTime),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!T(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var r=0;r<e.length;++r){var s=e[r];if(pt(t,i,s))return s}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){var n=t[s-e.startSN];i.cc===n.cc&&(r=n,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=vt(e,i.cc,i.end))&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn)}}else{var a=this.hls.liveSyncPosition;null!==a&&(r=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r},i.getFragmentAtPosition=function(e,t,i){var r,s,n=this.config,a=this.fragPrevious,o=i.fragments,l=i.endSN,h=i.fragmentHint,u=n.maxFragLookUpTolerance,d=i.partList,c=!!(this.loadingParts&&null!=d&&d.length&&h);if(c&&!this.bitrateTest&&d[d.length-1].fragment.sn===h.sn&&(o=o.concat(h),l=h.sn),r=e<t?ft(a,o,e,e<this.lastCurrentTime||e>t-u||null!=(s=this.media)&&s.paused||!this.startFragRequested?0:u):o[o.length-1]){var f=r.sn-i.startSN,g=this.fragmentTracker.getState(r);if((g===Dt||g===kt&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!c||d[0].fragment.sn>r.sn||!i.live)&&r.level===a.level){var p=o[f+1];r=r.sn<l&&this.fragmentTracker.getState(p)!==Dt?p:null}}return r},i.alignPlaylists=function(e,t,i){var r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;var s=e.fragmentStart,n=!t,a=e.alignedSliding&&T(s);if(n||!a&&!s){!function(e,t){e&&(sr(t,e),t.alignedSliding||nr(t,e),t.alignedSliding||t.skippedSegments||qi(e,t,!1))}(i,e);var o=e.fragmentStart;return this.log("Live playlist sliding: "+o.toFixed(2)+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" fragments: "+r),o}return s},i.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},i.setStartPosition=function(e,t){var i=this.startPosition;i<t&&(i=-1);var r=this.timelineOffset;if(-1===i){var s=null!==this.startTimeOffset,n=s?this.startTimeOffset:e.startTimeOffset;null!==n&&T(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log("Setting startPosition to "+i+" for start time offset "+n+" found in "+(s?"multivariant":"media")+" playlist"),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge "+i),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r},i.getLoadPosition=function(){var e,t=this.media,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i},i.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&ee(e)&&e.stats.aborted&&(this.log("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},i.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===lr.FRAG_LOADING_WAITING_RETRY)||(this.state=lr.IDLE)},i.onFragmentOrKeyLoadError=function(e,t){var i;if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var s=t.frag;if(s&&s.type===e&&this.levels)if(this.fragContextChanged(s)){var n;this.warn("Frag load error must match current frag to retry "+s.url+" > "+(null==(n=this.fragCurrent)?void 0:n.url))}else{var a=t.details===A.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);var o=t.errorAction;if(o){var l=o.action,h=o.flags,u=o.retryCount,d=void 0===u?0:u,c=o.retryConfig,f=!!c,g=f&&5===l,p=f&&!o.resolved&&1===h,v=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!g&&p&&ee(s)&&!s.endList&&v&&!Et(t))this.resetFragmentErrors(e),this.treatAsGap(s),o.resolved=!0;else if((g||p)&&d<c.maxNumRetry){var m,y=bt(null==(m=t.response)?void 0:m.code),E=Tt(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=lr.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,y)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment "+s.sn+" of "+e+" "+s.level+" errored with "+t.details+", retrying loading "+(d+1)+"/"+c.maxNumRetry+" in "+E+"ms")}else if(c){if(this.resetFragmentErrors(e),!(d<c.maxNumRetry))return void this.warn(t.details+" reached or exceeded max retry ("+d+")");a||3===l||(o.resolved=!0)}else this.state=2===l?lr.WAITING_LEVEL:lr.ERROR;this.tickImmediate()}else this.state=lr.ERROR}},i.checkRetryDate=function(){var e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!bt(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=lr.IDLE)},i.reduceLengthAndFlushBuffer=function(e){if(this.state===lr.PARSING||this.state===lr.PARSED){var t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);var n=!s;return n&&this.warn("Buffer full error while media.currentTime ("+this.getLoadPosition()+") is not buffered, flush "+i+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1},i.resetFragmentErrors=function(e){e===C&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==lr.STOPPED&&(this.state=lr.IDLE)},i.afterBufferFlushed=function(e,t,i){if(e){var r=jt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===lr.ENDED&&this.resetLoadingState()}},i.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==lr.STOPPED&&(this.state=lr.IDLE)},i.resetStartWhenNotLoaded=function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},i.resetWhenMissingContext=function(e){this.log("Loading context changed while buffering sn "+e.sn+" of "+this.playlistLabel()+" "+(-1===e.level?"<removed>":e.level)+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()},i.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},i.updateLevelTiming=function(e,t,i,r){var s=this,n=i.details;if(n){var a;if(!Object.keys(e.elementaryStreams).reduce((function(t,a){var o=e.elementaryStreams[a];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return s.warn("Could not parse fragment "+e.sn+" "+a+" duration reliably ("+l+")"),t||!1;var h=r?0:Vi(n,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,s);return s.hls.trigger(I.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(a=this.transmuxer)?void 0:a.error))){var o=new Error("Found no media in fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+" resetting transmuxer to fallback to playlist timing");if(this.warn(o.message),this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+i.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=lr.PARSED,this.log("Parsed "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+")"),this.hls.trigger(I.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")},i.playlistLabel=function(){return this.playlistType===w?"level":"track"},i.fragInfo=function(e,t,i){var r,s;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(i?"part":"frag")+":["+(null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN).toFixed(3)+"-"+(null!=(s=t&&!i?e.endPTS:(i||e).end)?s:NaN).toFixed(3)+"]"+(i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):"")},i.treatAsGap=function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)},i.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},i.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())},r(t,[{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"primaryPrefetch",get:function(){var e;return!(!ur(this.config)||!(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}($t);function ur(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var dr=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,i=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var i=new Uint8Array(t),r=0,s=0;s<e.length;s++){var n=e[s];i.set(n,r),r+=n.length}return i}(t,i),this.reset(),e):new Uint8Array(0)},t.reset=function(){this.chunks.length=0,this.dataLength=0},e}();function cr(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function fr(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function gr(e,t){var i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,(i|=(127&e[t+2])<<7)|127&e[t+3]}function pr(e,t){for(var i=t,r=0;fr(e,t);)r+=10,r+=gr(e,t+6),cr(e,t+10)&&(r+=10),t+=r;if(r>0)return e.subarray(i,i+r)}function vr(e,t){return 255===e[t]&&240==(246&e[t+1])}function mr(e,t){return 1&e[t+1]?7:9}function yr(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Er(e,t){return t+1<e.length&&vr(e,t)}function Sr(e,t){if(Er(e,t)){var i=mr(e,t);if(t+i>=e.length)return!1;var r=yr(e,t);if(r<=i)return!1;var s=t+r;return s===e.length||Er(e,s)}return!1}function Tr(e,t,i,r,s){if(!e.samplerate){var a=function(e,t,i,r){var s=t[i+2],n=s>>2&15;if(!(n>12)){var a=1+(s>>6&3),o=t[i+3]>>6&3|(1&s)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n],u=n;5!==a&&29!==a||(u-=3);var d=[a<<3|(14&u)>>1,(1&u)<<7|o<<3];return V.log("manifest codec:"+r+", parsed codec:"+l+", channels:"+o+", rate:"+h+" (ADTS object type:"+a+" sampling index:"+n+")"),{config:d,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:r}}var c=new Error("invalid ADTS sampling index:"+n);e.emit(I.ERROR,I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}(t,i,r,s);if(!a)return;n(e,a)}}function _r(e){return 9216e4/e}function Lr(e,t,i,r,s){var n,a=r+s*_r(e.samplerate),o=function(e,t){var i=mr(e,t);if(t+i<=e.length){var r=yr(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(o){var l=o.frameLength,h=o.headerLength,u=h+l,d=Math.max(0,i+u-t.length);d?(n=new Uint8Array(u-h)).set(t.subarray(i+h,t.length),0):n=t.subarray(i+h,i+u);var c={unit:n,pts:a};return d||e.samples.push(c),{sample:c,length:u,missing:d}}var f=t.length-i;return(n=new Uint8Array(f)).set(t.subarray(i,t.length),0),{sample:{unit:n,pts:a},length:f,missing:-1}}function br(e,t){return fr(e,t)&&gr(e,t+6)+10<=e.length-t}function Ar(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1/0),function(e,t,i,r){var s=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);var a,o=(a=e)&&a.buffer instanceof ArrayBuffer&&void 0!==a.byteLength&&void 0!==a.byteOffset?e.byteOffset:0,l=(o+e.byteLength)/n,h=(o+t)/n,u=Math.floor(Math.max(0,Math.min(h,l)));return new r(s,u,Math.floor(Math.min(u+Math.max(i,0),l))-u)}(e,t,i,Uint8Array)}function Ir(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=q(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,i=q(e.data.subarray(t),!0);t+=i.length+1;var r=q(e.data.subarray(t));return{key:e.type,info:i,data:r}}var s=q(e.data);return{key:e.type,info:"",data:s}}(e):"APIC"===e.type?function(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var i=e.data.subarray(1).indexOf(0);if(-1!==i){var r=q(Ar(e.data,1,i)),s=e.data[2+i],n=e.data.subarray(3+i).indexOf(0);if(-1!==n){var a,o=q(Ar(e.data,3+i,n));return a="--\x3e"===r?q(Ar(e.data,4+i+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+n)),t.mimeType=r,t.pictureType=s,t.description=o,t.data=a,t}}}else console.log("Ignore frame with unrecognized character encoding")}(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,i=q(e.data.subarray(t),!0);t+=i.length+1;var r=q(e.data.subarray(t));return{key:e.type,info:i,data:r}}var s=q(e.data.subarray(1));return{key:e.type,info:"",data:s}}}(e)}function Rr(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=gr(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}var Pr=10,kr=10;function Dr(e){for(var t=0,i=[];fr(e,t);){var r=gr(e,t+6);e[t+5]>>6&1&&(t+=Pr);for(var s=(t+=Pr)+r;t+kr<s;){var n=Rr(e.subarray(t)),a=Ir(n);a&&i.push(a),t+=n.size+Pr}cr(e,t)&&(t+=Pr)}return i}function wr(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Cr(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Mr(e){for(var t=Dr(e),i=0;i<t.length;i++){var r=t[i];if(wr(r))return Cr(r)}}var Or=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function xr(e,t){return void 0===e&&(e=""),void 0===t&&(t=9e4),{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var Fr=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,i){},t.demux=function(e,t){this.cachedData&&(e=Te(this.cachedData,e),this.cachedData=null);var i,r=pr(e,0),s=r?r.length:0,n=this._audioTrack,a=this._id3Track,o=r?Mr(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&T(o))&&(this.basePTS=Nr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Or.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){var h=this.appendFrame(n,e,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i=s+=h.length):s=l}else br(e,s)?(r=pr(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Or.audioId3,duration:Number.POSITIVE_INFINITY}),i=s+=r.length):s++;if(s===l&&i!==l){var u=e.slice(i);this.cachedData?this.cachedData=Te(this.cachedData,u):this.cachedData=u}}return{audioTrack:n,videoTrack:xr(),id3Track:a,textTrack:xr()}},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},t.flush=function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:xr(),id3Track:this._id3Track,textTrack:xr()}},t.destroy=function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},e}(),Nr=function(e,t,i){return T(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0)},Br=null,Ur=[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],Gr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Hr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Kr=[0,1,1,4];function Vr(e,t,i,r,s){if(!(i+24>t.length)){var n=$r(t,i);if(n&&i+n.frameLength<=t.length){var a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function $r(e,t){var i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){var a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Ur[14*(3===i?3-r:3===r?3:4)+s-1],h=Gr[3*(3===i?0:2===i?1:2)+n],u=3===o?1:2,d=Hr[i][r],c=Kr[r],f=8*d*c,g=Math.floor(d*l/h+a)*c;if(null===Br){var p=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Br=p?parseInt(p[1]):0}return!!Br&&Br<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:u,frameLength:g,samplesPerFrame:f}}}function Wr(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function qr(e,t){return t+1<e.length&&Wr(e,t)}function jr(e,t){if(t+1<e.length&&Wr(e,t)){var i=$r(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);var s=t+r;return s===e.length||qr(e,s)}return!1}var Yr=function(e){function t(t,i){var r;return(r=e.call(this)||this).observer=void 0,r.config=void 0,r.observer=t,r.config=i,r}o(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e,t){if(!e)return!1;var i=pr(e,0),r=(null==i?void 0:i.length)||0;if(jr(e,r))return!1;for(var s=e.length;r<s;r++)if(Sr(e,r))return t.log("ADTS sync word found !"),!0;return!1},i.canParse=function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&vr(e,t)&&yr(e,t)<=e.length-t}(e,t)},i.appendFrame=function(e,t,i){Tr(e,this.observer,t,i,e.manifestCodec);var r=Lr(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r},t}(Fr),zr=function(e,t){var i=0,r=5;t+=r;for(var s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);r>0;){a[0]=e[t];var o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],t+=1,r-=o}return i},Xr=function(e){function t(t){var i;return(i=e.call(this)||this).observer=void 0,i.observer=t,i}o(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},i.canParse=function(e,t){return t+64<e.length},i.appendFrame=function(e,t,i){var r=Qr(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}},t.probe=function(e){if(!e)return!1;var t=pr(e,0);if(!t)return!1;var i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Mr(t)&&zr(e,i)<16},t}(Fr);function Qr(e,t,i,r,s){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;var n=t[i+4]>>6;if(n>=3)return-1;var a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[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][3*o+n];if(i+l>t.length)return-1;var h=t[i+6]>>5,u=0;2===h?u+=2:(1&h&&1!==h&&(u+=2),4&h&&(u+=2));var d=(t[i+6]<<8|t[i+7])>>12-u&1,c=[2,1,2,3,3,4,4,5][h]+d,f=t[i+5]>>3,g=7&t[i+5],p=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|d<<2|o>>4,o<<4&224]),v=r+s*(1536/a*9e4),m=t.subarray(i,i+l);return e.config=p,e.channelCount=c,e.samplerate=a,e.samples.push({unit:m,pts:v}),l}var Jr=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,s){e.prototype.resetInitSegment.call(this,t,i,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=pr(e,0),i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Mr(t)&&zr(e,i)<=16)return!1;for(var r=e.length;i<r;i++)if(jr(e,i))return V.log("MPEG Audio sync word found !"),!0;return!1},i.canParse=function(e,t){return function(e,t){return Wr(e,t)&&4<=e.length-t}(e,t)},i.appendFrame=function(e,t,i){if(null!==this.basePTS)return Vr(e,t,i,this.basePTS,this.frameIndex)},t}(Fr),Zr=/\/emsg[-/]ID3/i,es=function(){function e(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}var t=e.prototype;return t.resetTimeStamp=function(){},t.resetInitSegment=function(e,t,i,r){var s=this.videoTrack=xr("video",1),n=this.audioTrack=xr("audio",1),a=this.txtTrack=xr("text",1);if(this.id3Track=xr("id3",1),this.timeOffset=0,null!=e&&e.byteLength){var o=ge(e);if(o.video){var l=o.video,h=l.id,u=l.timescale,d=l.codec,c=l.supplemental;s.id=h,s.timescale=a.timescale=u,s.codec=d,s.supplemental=c}if(o.audio){var f=o.audio,g=f.id,p=f.timescale,v=f.codec;n.id=g,n.timescale=p,n.codec=v}a.id=ae.text,s.sampleDuration=0,s.duration=n.duration=r}},t.resetContiguity=function(){this.remainderData=null},e.probe=function(e){return function(e){for(var t=e.byteLength,i=0;i<t;){var r=he(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var i=e,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Te(this.remainderData,e));var n=function(e){var t={valid:null,remainder:null},i=ce(e,["moof"]);if(i.length<2)return t.remainder=e,t;var r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=n.remainder,r.samples=n.valid||new Uint8Array}else r.samples=i;var a=this.extractID3Track(r,t);return s.samples=_e(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(t,this.timeOffset);return i.samples=_e(e,t),{videoTrack:t,audioTrack:xr(),id3Track:r,textTrack:xr()}},t.extractID3Track=function(e,t){var i=this,r=this.id3Track;if(e.samples.length){var s=ce(e.samples,["emsg"]);s&&s.forEach((function(e){var s=function(e){var t=e[0],i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==oe(e.subarray(h,h+1));)i+=oe(e.subarray(h,h+1)),h+=1;for(i+=oe(e.subarray(h,h+1)),h+=1;"\0"!==oe(e.subarray(h,h+1));)r+=oe(e.subarray(h,h+1)),h+=1;r+=oe(e.subarray(h,h+1)),h+=1,s=he(e,12),n=he(e,16),o=he(e,20),l=he(e,24),h=28}else if(1===t){s=he(e,h+=4);var u=he(e,h+=4),d=he(e,h+=4);for(h+=4,a=Math.pow(2,32)*u+d,_(a)||(a=Number.MAX_SAFE_INTEGER,V.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=he(e,h),l=he(e,h+=4),h+=4;"\0"!==oe(e.subarray(h,h+1));)i+=oe(e.subarray(h,h+1)),h+=1;for(i+=oe(e.subarray(h,h+1)),h+=1;"\0"!==oe(e.subarray(h,h+1));)r+=oe(e.subarray(h,h+1)),h+=1;r+=oe(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Zr.test(s.schemeIdUri)){var n=ts(s,t),a=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=s.payload;r.samples.push({data:o,len:o.byteLength,dts:n,pts:n,type:Or.emsg,duration:a})}else if(i.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=ts(s,t);r.samples.push({data:s.payload,len:s.payload.byteLength,dts:l,pts:l,type:Or.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return r},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0},e}();function ts(e,t){return T(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var is=function(){function e(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Bt(t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,0)},t.decryptAacSample=function(e,t,i){var r=this,s=e[t].unit;if(!(s.length<=16)){var n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then((function(n){var a=new Uint8Array(n);s.set(a,16),r.decrypter.isSync()||r.decryptAacSamples(e,t+1,i)})).catch(i)}},t.decryptAacSamples=function(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,i),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0,s=32;s<e.length-16;s+=160,r+=16)i.set(e.subarray(s,s+16),r);return i},t.getAvcDecryptedUnit=function(e,t){for(var i=new Uint8Array(t),r=0,s=32;s<e.length-16;s+=160,r+=16)e.set(i.subarray(r,r+16),s);return e},t.decryptAvcSample=function(e,t,i,r,s){var n=this,a=Ie(s.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then((function(o){s.data=n.getAvcDecryptedUnit(a,o),n.decrypter.isSync()||n.decryptAvcSamples(e,t,i+1,r)})).catch(r)},t.decryptAvcSamples=function(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)return void r();for(var s=e[t].units;!(i>=s.length);i++){var n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,r,n),this.decrypter.isSync())))return}}},e}(),rs=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}},t.getLastNalUnit=function(e){var t,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){var s=r.units;i=s[s.length-1]}return i},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var i=t.samples,r=i.length;if(!r)return void t.dropped++;var s=i[r-1];e.pts=s.pts,e.dts=s.dts}t.samples.push(e)}},t.parseNALu=function(e,t,i){var r,s,n=t.byteLength,a=e.naluState||0,o=a,l=[],h=0,u=-1,d=0;for(-1===a&&(u=0,d=this.getNALuType(t,0),a=0,h=1);h<n;)if(r=t[h++],a)if(1!==a)if(r)if(1===r){if(s=h-a-1,u>=0){var c={data:t.subarray(u,s),type:d};l.push(c)}else{var f=this.getLastNalUnit(e.samples);f&&(o&&h<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),s>0&&(f.data=Te(f.data,t.subarray(0,s)),f.state=0))}h<n?(u=h,d=this.getNALuType(t,h),a=0):a=-1}else a=0;else a=3;else a=r?0:2;else a=r?0:1;if(u>=0&&a>=0){var g={data:t.subarray(u,n),type:d,state:a};l.push(g)}if(0===l.length){var p=this.getLastNalUnit(e.samples);p&&(p.data=Te(p.data,t))}return e.naluState=a,l},e}(),ss=function(){function e(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}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&V.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i},t.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},e}(),ns=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var s,n=this,a=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,h;switch(r.type){case 1:var u=!1;s=!0;var d,c=r.data;if(l&&c.length>4){var f=n.readSliceType(c);2!==f&&4!==f&&7!==f&&9!==f||(u=!0)}u&&null!=(d=o)&&d.frame&&!o.key&&(n.pushAccessUnit(o,e),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=u;break;case 5:s=!0,null!=(a=o)&&a.frame&&!o.key&&(n.pushAccessUnit(o,e),o=n.VideoSample=null),o||(o=n.VideoSample=n.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:s=!0,Ae(r.data,1,i.pts,t.samples);break;case 7:var g,p;s=!0,l=!0;var v=r.data,m=n.readSPS(v);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(g=e.pixelRatio)?void 0:g[0])!==m.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[v];for(var y=v.subarray(1,4),E="avc1.",S=0;S<3;S++){var T=y[S].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:s=!0,e.pps=[r.data];break;case 9:s=!0,e.audFound=!0,null!=(h=o)&&h.frame&&(n.pushAccessUnit(o,e),o=null),o||(o=n.VideoSample=n.createVideoSample(!1,i.pts,i.dts));break;case 12:s=!0;break;default:s=!1}o&&s&&o.units.push(r)})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},i.getNALuType=function(e,t){return 31&e[t]},i.readSliceType=function(e){var t=new ss(e);return t.readUByte(),t.readUEG(),t.readUEG()},i.skipScalingList=function(e,t){for(var i=8,r=8,s=0;s<e;s++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r},i.readSPS=function(e){var t,i,r,s=new ss(e),n=0,a=0,o=0,l=0,h=s.readUByte.bind(s),u=s.readBits.bind(s),d=s.readUEG.bind(s),c=s.readBoolean.bind(s),f=s.skipBits.bind(s),g=s.skipEG.bind(s),p=s.skipUEG.bind(s),v=this.skipScalingList.bind(this);h();var m=h();if(u(5),f(3),h(),p(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),p(),p(),f(1),c())for(i=3!==y?8:12,r=0;r<i;r++)c()&&v(r<6?16:64,s)}p();var E=d();if(0===E)d();else if(1===E)for(f(1),g(),g(),t=d(),r=0;r<t;r++)g();p(),f(1);var S=d(),T=d(),_=u(1);0===_&&f(1),f(1),c()&&(n=d(),a=d(),o=d(),l=d());var L=[1,1];if(c()&&c())switch(h()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil(16*(S+1)-2*n-2*a),height:(2-_)*(T+1)*16-(_?2:4)*(o+l),pixelRatio:L}},t}(rs),as=function(e){function t(){for(var t,i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return(t=e.call.apply(e,[this].concat(r))||this).initVPS=null,t}o(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var s,a=this,o=this.parseNALu(e,i.data,r),l=this.VideoSample,h=!1;i.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.forEach((function(r){var o,u;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=a.VideoSample=a.createVideoSample(!1,i.pts,i.dts)),l.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:var d;s=!0,h&&null!=(d=l)&&d.frame&&!l.key&&(a.pushAccessUnit(l,e),l=a.VideoSample=null),l||(l=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:s=!0,null!=(o=l)&&o.frame&&!l.key&&(a.pushAccessUnit(l,e),l=a.VideoSample=null),l||(l=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 39:s=!0,Ae(r.data,2,i.pts,t.samples);break;case 32:s=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=n(e.params,a.readVPS(r.data)),a.initVPS=r.data),e.vps=[r.data];break;case 33:if(s=!0,h=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],r.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var c=a.readSPS(r.data);for(var f in e.width=c.width,e.height=c.height,e.pixelRatio=c.pixelRatio,e.codec=c.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),c.params)e.params[f]=c.params[f]}a.pushParameterSet(e.sps,r.data,e.vps),l||(l=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts)),l.key=!0;break;case 34:if(s=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];var g=a.readPPS(r.data);for(var p in g)e.params[p]=g[p]}a.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:s=!0,e.audFound=!0,null!=(u=l)&&u.frame&&(a.pushAccessUnit(l,e),l=null),l||(l=a.VideoSample=a.createVideoSample(!1,i.pts,i.dts));break;default:s=!1}l&&s&&l.units.push(r)})),r&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)},i.pushParameterSet=function(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)},i.getNALuType=function(e,t){return(126&e[t])>>>1},i.ebsp2rbsp=function(e){for(var t=new Uint8Array(e.byteLength),i=0,r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)},i.pushAccessUnit=function(t,i){e.prototype.pushAccessUnit.call(this,t,i),this.initVPS&&(this.initVPS=null)},i.readVPS=function(e){var t=new ss(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}},i.readSPS=function(e){var t=new ss(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var i=t.readBits(3);t.readBoolean();for(var r=t.readBits(2),s=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),m=[],y=[],E=0;E<i;E++)m.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(var S=i;S<8;S++)t.readBits(2);for(var T=0;T<i;T++)m[T]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[T]&&t.readUByte();t.readUEG();var _=t.readUEG();3==_&&t.skipBits(1);var L=t.readUEG(),b=t.readUEG(),A=t.readBoolean(),I=0,R=0,P=0,k=0;A&&(I+=t.readUEG(),R+=t.readUEG(),P+=t.readUEG(),k+=t.readUEG());for(var D=t.readUEG(),w=t.readUEG(),C=t.readUEG(),M=t.readBoolean()?0:i;M<=i;M++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(var O=0;O<4;O++)for(var x=0;x<(3===O?2:6);x++)if(t.readBoolean()){var F=Math.min(64,1<<4+(O<<1));O>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var B=t.readUEG(),U=0,G=0;G<B;G++){var H=!1;if(0!==G&&(H=t.readBoolean()),H){G===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var K=0,V=0;V<=U;V++){var $=t.readBoolean(),W=!1;$||(W=t.readBoolean()),($||W)&&K++}U=K}else{var q=t.readUEG(),j=t.readUEG();U=q+j;for(var Y=0;Y<q;Y++)t.readUEG(),t.readBoolean();for(var z=0;z<j;z++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var X=t.readUEG(),Q=0;Q<X;Q++){for(var J=0;J<C+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,ie=!0,re=1,se=0;if(t.readBoolean(),t.readBoolean(),t.readBoolean()){if(t.readBoolean()){var ne=t.readUByte();ne>0&&ne<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ne-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ne-1]):255===ne&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(re=t.readBits(32),se=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){var ae=t.readBoolean(),oe=t.readBoolean(),le=!1;(ae||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var he=0;he<=i;he++){var ue=!1;(ie=t.readBoolean())||t.readBoolean()?t.readEG():ue=t.readBoolean();var de=ue?1:t.readUEG()+1;if(ae)for(var ce=0;ce<de;ce++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var fe=0;fe<de;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var ge=L,pe=b;if(A){var ve=1,me=1;1===_?ve=me=2:2==_&&(ve=2),ge=L-ve*R-ve*I,pe=b-me*k-me*P}for(var ye=r?["A","B","C"][r]:"",Ee=a<<24|o<<16|l<<8|h,Se=0,Te=0;Te<32;Te++)Se=(Se|(Ee>>Te&1)<<31-Te)>>>0;var _e=Se.toString(16);return 1===n&&"2"===_e&&(_e="6"),{codecString:"hvc1."+ye+n+"."+_e+"."+(s?"H":"L")+v+".B0",params:{general_tier_flag:s,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[u,d,c,f,g,p],general_level_idc:v,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:w,min_spatial_segmentation_idc:Z,chroma_format_idc:_,frame_rate:{fixed:ie,fps:se/re}},width:ge,height:pe,pixelRatio:[ee,te]}},i.readPPS=function(e){var t=new ss(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var i=t.readBoolean(),r=t.readBoolean(),s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}},i.matchSPS=function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)},t}(rs),os=188,ls=function(){function e(e,t,i,r){this.logger=void 0,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._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.logger=r,this.videoParser=null}e.probe=function(t,i){var r=e.syncOffset(t);return r>0&&i.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},e.syncOffset=function(e){for(var t=e.length,i=Math.min(940,t-os)+1,r=0;r<i;){for(var s=!1,n=-1,a=0,o=r;o<t;o+=os){if(71!==e[o]||t-o!==os&&71!==e[o+os]){if(a)return-1;break}if(a++,-1===n&&0!==(n=o)&&(i=Math.min(n+18612,e.length-os)+1),s||(s=0===hs(e,o)),s&&a>1&&(0===n&&a>2||o+os>i))return n}r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:ae[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,i,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=e.createTrack("audio",s),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=r},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,i=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,i,r,s){var n;void 0===r&&(r=!1),void 0===s&&(s=!1),r||(this.sampleAes=null);var a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,u=a.pid,d=a.pesData,c=o.pid,f=l.pid,g=o.pesData,p=l.pesData,v=null,m=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=Te(this.remainderData,t)).length,this.remainderData=null),E<os&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var S=Math.max(0,e.syncOffset(t));(E-=(E-S)%os)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var T=0,_=S;_<E;_+=os)if(71===t[_]){var L=!!(64&t[_+1]),b=hs(t,_),A=void 0;if((48&t[_+3])>>4>1){if((A=_+5+t[_+4])===_+os)continue}else A=_+4;switch(b){case u:L&&(d&&(n=gs(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,h,n,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(A,_+os)),d.size+=_+os-A);break;case c:if(L){if(g&&(n=gs(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}g={data:[],size:0}}g&&(g.data.push(t.subarray(A,_+os)),g.size+=_+os-A);break;case f:L&&(p&&(n=gs(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(t.subarray(A,_+os)),p.size+=_+os-A);break;case 0:L&&(A+=t[A]+1),y=this._pmtId=us(t,A);break;case y:L&&(A+=t[A]+1);var I=ds(t,A,this.typeSupported,r,this.observer,this.logger);(u=I.videoPid)>0&&(a.pid=u,a.segmentCodec=I.segmentVideoCodec),(c=I.audioPid)>0&&(o.pid=c,o.segmentCodec=I.segmentAudioCodec),(f=I.id3Pid)>0&&(l.pid=f),null===v||m||(this.logger.warn("MPEG-TS PMT found at "+_+" after unknown PID '"+v+"'. Backtracking to sync byte @"+S+" to parse all TS packets."),v=null,_=S-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:v=b}}else T++;T>0&&cs(this.observer,new Error("Found "+T+" TS packet/s that do not start with 0x47"),void 0,this.logger),a.pesData=d,o.pesData=g,l.pesData=p;var R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(R),R},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,i=e.audioTrack,r=e.videoTrack,s=e.id3Track,n=e.textTrack,a=r.pesData,o=i.pesData,l=s.pesData;if(a&&(t=gs(a,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,n,t,!0),r.pesData=null)):r.pesData=a,o&&(t=gs(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(t=gs(l,this.logger))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=l},t.demuxSampleAes=function(e,t,i){var r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new is(this.observer,this.config,t);return this.decrypt(r,s)},t.readyVideoParser=function(e){null===this.videoParser&&("avc"===e?this.videoParser=new ns:"hevc"===e&&(this.videoParser=new as))},t.decrypt=function(e,t){return new Promise((function(i){var r=e.audioTrack,s=e.videoTrack;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(function(){s.samples?t.decryptAvcSamples(s.samples,0,0,(function(){i(e)})):i(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(function(){i(e)}))}))},t.destroy=function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0},t.parseAACPES=function(e,t){var i,r,s,n=0,a=this.aacOverFlow,o=t.data;if(a){this.aacOverFlow=null;var l=a.missing,h=a.sample.unit.byteLength;if(-1===l)o=Te(a.sample.unit,o);else{var u=h-l;a.sample.unit.set(o.subarray(0,l),u),e.samples.push(a.sample),n=a.missing}}for(i=n,r=o.length;i<r-1&&!Er(o,i);i++);if(i!==n){var d,c=i<r-1;if(d=c?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES",cs(this.observer,new Error(d),c,this.logger),!c)return}if(Tr(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)s=t.pts;else{if(!a)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=_r(e.samplerate);s=a.sample.pts+f}for(var g,p=0;i<r;){if(i+=(g=Lr(e,o,i,s,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;i<r-1&&!Er(o,i);i++);}},t.parseMPEGPES=function(e,t){var i=t.data,r=i.length,s=0,n=0,a=t.pts;if(void 0!==a)for(;n<r;)if(qr(i,n)){var o=Vr(e,i,n,a,s);if(!o)break;n+=o.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},t.parseAC3PES=function(e,t){var i=t.data,r=t.pts;if(void 0!==r)for(var s,n=i.length,a=0,o=0;o<n&&(s=Qr(e,i,o,r,a++))>0;)o+=s;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var i=n({},t,{type:this._videoTrack?Or.emsg:Or.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function hs(e,t){return((31&e[t+1])<<8)+e[t+2]}function us(e,t){return(31&e[t+10])<<8|e[t+11]}function ds(e,t,i,r,s,n){var a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){var l=hs(e,t),h=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){fs("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=l);break;case 21:-1===a.id3Pid&&(a.id3Pid=l);break;case 219:if(!r){fs("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){fs("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&h>0)for(var u=t+5,d=h;d>2;){106===e[u]&&(!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=l,a.segmentAudioCodec="ac3"));var c=e[u+1]+2;u+=c,d-=c}break;case 194:case 135:return cs(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=l,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=h+5}return a}function cs(e,t,i,r){r.warn("parsing error: "+t.message),e.emit(I.ERROR,I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function fs(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function gs(e,t){var i,r,s,n,a,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Te(l[0],l[1]),l.splice(1,1);if(1===((i=l[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>e.size-6)return null;var h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?n-(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2)>54e5&&(t.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var u=(s=i[8])+9;if(e.size<=u)return null;e.size-=u;for(var d=new Uint8Array(e.size),c=0,f=l.length;c<f;c++){var g=(i=l[c]).byteLength;if(u){if(u>g){u-=g;continue}i=i.subarray(u),g-=u,u=0}d.set(i,o),o+=g}return r&&(r-=s+3),{data:d,pts:n,dts:a,len:r}}return null}var ps=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}},e}(),vs=Math.pow(2,32)-1,ms=function(){function e(){}return e.init=function(){var t;for(t in e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var i=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:i,audio:r};var s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=n,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,a,l,a,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,s))},e.box=function(e){for(var t=8,i=arguments.length,r=new Array(i>1?i-1:0),s=1;s<i;s++)r[s-1]=arguments[s];for(var n=r.length,a=n;n--;)t+=r[n].byteLength;var o=new Uint8Array(t);for(o[0]=t>>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),n=0,t=8;n<a;n++)o.set(r[n],t),t+=r[n].byteLength;return o},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,i){i*=t;var r=Math.floor(i/(vs+1)),s=Math.floor(i%(vs+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,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,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,i,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,i))},e.moov=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(e.mvex(t)))},e.mvex=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trex(t[i]);return e.box.apply(null,[e.types.mvex].concat(r))},e.mvhd=function(t,i){i*=t;var r=Math.floor(i/(vs+1)),s=Math.floor(i%(vs+1)),n=new Uint8Array([1,0,0,0,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,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,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 e.box(e.types.mvhd,n)},e.sdtp=function(t){var i,r,s=t.samples||[],n=new Uint8Array(4+s.length);for(i=0;i<s.length;i++)r=s[i].flags,n[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,n)},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))},e.avc1=function(t){var i,r,s,n=[],a=[];for(i=0;i<t.sps.length;i++)s=(r=t.sps[i]).byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)s=(r=t.pps[i]).byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(r));var o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.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,255&l,h>>8&255,255&h,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,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,d>>24,d>>16&255,d>>8&255,255&d])))},e.esds=function(e){var t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2].concat(t,[6,1,2]))},e.audioStsd=function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){return e.box(e.types[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))},e.stsd=function(t){var i=t.segmentCodec;if("audio"===t.type){if("aac"===i)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===i&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===i&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===i)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===i&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+i+"/"+t.codec+")")},e.tkhd=function(t){var i=t.id,r=(t.duration||0)*(t.timescale||0),s=t.width||0,n=t.height||0,a=Math.floor(r/(vs+1)),o=Math.floor(r%(vs+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,s>>8&255,255&s,0,0,n>>8&255,255&n,0,0]))},e.traf=function(t,i){var r=e.sdtp(t),s=t.id,n=Math.floor(i/(vs+1)),a=Math.floor(i%(vs+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,r.length+16+20+8+16+8+8),r)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var i=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,i){var r,s,n,a,o,l,h=t.samples||[],u=h.length,d=12+16*u,c=new Uint8Array(d);for(i+=8+d,c.set(["video"===t.type?1:0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<u;r++)n=(s=h[r]).duration,a=s.size,o=s.flags,l=s.cts,c.set([n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*r);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var i=e.moov(t);return Te(e.FTYP,i)},e.hvc1=function(t){for(var i=t.params,r=[t.vps,t.sps,t.pps],s=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),r.length]),n=s.length,a=0;a<r.length;a+=1){n+=3;for(var o=0;o<r[a].length;o+=1)n+=2+r[a][o].length}var l=new Uint8Array(n);l.set(s,0),n=s.length;for(var h=r.length-1,u=0;u<r.length;u+=1){l.set(new Uint8Array([32+u|(u===h?128:0),0,r[u].length]),n),n+=3;for(var d=0;d<r[u].length;d+=1)l.set(new Uint8Array([r[u][d].length>>8,255&r[u][d].length]),n),n+=2,l.set(r[u][d],n),n+=r[u][d].length}var c=e.box(e.types.hvcC,l),f=t.width,g=t.height,p=t.pixelRatio[0],v=t.pixelRatio[1];return e.box(e.types.hvc1,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,f>>8&255,255&f,g>>8&255,255&g,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]),c,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,255&p,v>>24,v>>16&255,v>>8&255,255&v])))},e}();ms.types=void 0,ms.HDLR_TYPES=void 0,ms.STTS=void 0,ms.STSC=void 0,ms.STCO=void 0,ms.STSZ=void 0,ms.VMHD=void 0,ms.SMHD=void 0,ms.STSD=void 0,ms.FTYP=void 0,ms.DINF=void 0;function ys(e,t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);var s=e*t*i;return r?Math.round(s):s}function Es(e,t){return ys(e,1e3,1/9e4,t)}var Ss=null,Ts=null;function _s(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Ls=function(e){function t(t,i,r,s){var n;if((n=e.call(this,"mp4-remuxer",s)||this).observer=void 0,n.config=void 0,n.typeSupported=void 0,n.ISGenerated=!1,n._initPTS=null,n._initDTS=null,n.nextVideoTs=null,n.nextAudioTs=null,n.videoSampleDuration=null,n.isAudioContiguous=!1,n.isVideoContiguous=!1,n.videoTrackConfig=void 0,n.observer=t,n.config=i,n.typeSupported=r,n.ISGenerated=!1,null===Ss){var a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ss=a?parseInt(a[1]):0}if(null===Ts){var o=navigator.userAgent.match(/Safari\/(\d+)/i);Ts=o?parseInt(o[1]):0}return n}o(t,e);var i=t.prototype;return i.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},i.resetTimeStamp=function(e){this.log("initPTS & initDTS reset"),this._initPTS=this._initDTS=e},i.resetNextTimestamp=function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},i.resetInitSegment=function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},i.getVideoStartPts=function(e){var t=!1,i=e[0].pts,r=e.reduce((function(e,r){var s=r.pts,n=s-e;return n<-4294967296&&(t=!0,n=(s=bs(s,i))-e),n>0?e:s}),i);return t&&this.debug("PTS rollover detected"),r},i.remux=function(e,t,i,r,s,n,a,o){var l,h,u,d,c,f,g=s,p=s,v=e.pid>-1,m=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!v||E)&&(!m||S)||this.ISGenerated||a){if(this.ISGenerated){var T,_,L,b,A=this.videoTrackConfig;(A&&(t.width!==A.width||t.height!==A.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(_=A.pixelRatio)?void 0:_[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(b=A.pixelRatio)?void 0:b[1]))||!A&&S||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,s,n));var I,R=this.isVideoContiguous,P=-1;if(S&&(P=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!R&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,P>0){this.warn("Dropped "+P+" out of "+y+" video samples due to a missing keyframe");var k=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,I=p+=(t.samples[0].pts-k)/t.inputTimeScale}else-1===P&&(this.warn("No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&S){var D=this.getVideoStartPts(t.samples),w=(bs(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,w),p+=Math.max(0,-w)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,m||S||o===C?p:void 0),S){var M=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,p,R,M)}}else S&&(l=this.remuxVideo(t,p,R,0));l&&(l.firstKeyFrame=P,l.independent=-1!==P,l.firstKeyFramePTS=I)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=As(i,s,this._initPTS,this._initDTS)),r.samples.length&&(d=Is(r,s,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:c}},i.generateIS=function(e,t,i,r){var s,n,a,o=e.samples,l=t.samples,h=this.typeSupported,u={},d=this._initPTS,c=!d||r,f="audio/mp4",g=-1;if(c&&(s=n=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",e.codec=""):h.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}u.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&h.mpeg?new Uint8Array(0):ms.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(g=e.id,a=e.inputTimeScale,d&&a===d.timescale?c=!1:s=n=o[0].pts-Math.round(a*i))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:ms.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(g=t.id,a=t.inputTimeScale,d&&a===d.timescale)c=!1;else{var p=this.getVideoStartPts(l),v=Math.round(a*i);n=Math.min(n,bs(l[0].dts,p)-v),s=Math.min(s,p-v)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,c?(d&&this.warn("Timestamps at playlist time: "+(r?"":"~")+i+" "+s/a+" != initPTS: "+d.baseTime/d.timescale+" ("+d.baseTime+"/"+d.timescale+") trackId: "+d.trackId),this.log("Found initPTS at playlist time: "+i+" offset: "+s/a+" ("+s+"/"+a+") trackId: "+g),this._initPTS={baseTime:s,timescale:a,trackId:g},this._initDTS={baseTime:n,timescale:a,trackId:g}):s=a=void 0,{tracks:u,initPTS:s,timescale:a,trackId:g}},i.remuxVideo=function(e,t,i,r){var s,a,o=e.inputTimeScale,l=e.samples,h=[],u=l.length,d=this._initPTS,c=d.baseTime*o/d.timescale,f=this.nextVideoTs,g=8,p=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,y=!1;if(!i||null===f){var E=c+t*o,S=l[0].pts-bs(l[0].dts,l[0].pts);Ss&&null!==f&&Math.abs(E-S-(f+c))<15e3?i=!0:f=E-S-c}for(var T=f+c,_=0;_<u;_++){var L=l[_];L.pts=bs(L.pts,T),L.dts=bs(L.dts,T),L.dts<l[_>0?_-1:_].dts&&(y=!0)}y&&l.sort((function(e,t){var i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),s=l[0].dts;var R=l[l.length-1].dts-s,P=R?Math.round(R/(u-1)):p||e.inputTimeScale/30;if(i){var k=s-T,D=k>P,w=k<-1;if((D||w)&&(D?this.warn((e.segmentCodec||"").toUpperCase()+": "+Es(k,!0)+" ms ("+k+"dts) hole between fragments detected at "+t.toFixed(3)):this.warn((e.segmentCodec||"").toUpperCase()+": "+Es(-k,!0)+" ms ("+k+"dts) overlapping between fragments detected at "+t.toFixed(3)),!w||T>=l[0].pts||Ss)){s=T;var C=l[0].pts-k;if(D)l[0].dts=s,l[0].pts=C;else for(var M=!0,O=0;O<l.length&&!(l[O].dts>C&&M);O++){var x=l[O].pts;if(l[O].dts-=k,l[O].pts-=k,O<l.length-1){var F=l[O+1].pts;M=F<=l[O].pts==F<=x}}this.log("Video: Initial PTS/DTS adjusted: "+Es(C,!0)+"/"+Es(s,!0)+", delta: "+Es(k,!0)+" ms")}}for(var N=0,B=0,U=s=Math.max(0,s),G=0;G<u;G++){for(var H=l[G],K=H.units,V=K.length,$=0,W=0;W<V;W++)$+=K[W].data.length;B+=$,N+=V,H.length=$,H.dts<U?(H.dts=U,U+=P/4|0||1):U=H.dts,v=Math.min(H.pts,v),m=Math.max(H.pts,m)}a=l[u-1].dts;var q,j=B+4*N+8;try{q=new Uint8Array(j)}catch(e){return void this.observer.emit(I.ERROR,I.ERROR,{type:b.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:j,reason:"fail allocating video mdat "+j})}var Y=new DataView(q.buffer);Y.setUint32(0,j),q.set(ms.types.mdat,4);for(var z=!1,X=Number.POSITIVE_INFINITY,Q=Number.POSITIVE_INFINITY,J=Number.NEGATIVE_INFINITY,Z=Number.NEGATIVE_INFINITY,ee=0;ee<u;ee++){for(var te=l[ee],ie=te.units,re=0,se=0,ne=ie.length;se<ne;se++){var ae=ie[se],oe=ae.data,le=ae.data.byteLength;Y.setUint32(g,le),g+=4,q.set(oe,g),g+=le,re+=4+le}var he=void 0;if(ee<u-1)p=l[ee+1].dts-te.dts,he=l[ee+1].pts-te.pts;else{var ue=this.config,de=ee>0?te.dts-l[ee-1].dts:P;if(he=ee>0?te.pts-l[ee-1].pts:P,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var ce=Math.floor(ue.maxBufferHole*o),fe=(r?v+r*o:this.nextAudioTs+c)-te.pts;fe>ce?((p=fe-de)<0?p=de:z=!0,this.log("It is approximately "+fe/90+" ms to the next segment; using duration "+p/90+" ms for the last video frame.")):p=de}else p=de}var ge=Math.round(te.pts-te.dts);X=Math.min(X,p),J=Math.max(J,p),Q=Math.min(Q,he),Z=Math.max(Z,he),h.push(_s(te.key,p,re,ge))}if(h.length)if(Ss){if(Ss<70){var pe=h[0].flags;pe.dependsOn=2,pe.isNonSync=0}}else if(Ts&&Z-Q<J-X&&P/J<.025&&0===h[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var ve=s,me=0,ye=h.length;me<ye;me++){var Ee=ve+h[me].duration,Se=ve+h[me].cts;if(me<ye-1){var Te=Ee+h[me+1].cts;h[me].duration=Te-Se}else h[me].duration=me?h[me-1].duration:P;h[me].cts=0,ve=Ee}}var _e=a+(p=z||!p?P:p);this.nextVideoTs=f=_e-c,this.videoSampleDuration=p,this.isVideoContiguous=!0;var Le={data1:ms.moof(e.sequenceNumber++,s,n(e,{samples:h})),data2:q,startPTS:(v-c)/o,endPTS:(m+p-c)/o,startDTS:(s-c)/o,endDTS:f/o,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Le},i.getSamplesPerFrame=function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}},i.remuxAudio=function(e,t,i,r,s){var a=e.inputTimeScale,o=a/(e.samplerate?e.samplerate:a),l=this.getSamplesPerFrame(e),h=l*o,u=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],f=void 0!==s,g=e.samples,p=d?0:8,v=this.nextAudioTs||-1,m=u.baseTime*a/u.timescale,y=m+t*a;if(this.isAudioContiguous=i=i||g.length&&v>0&&(r&&Math.abs(y-(v+m))<9e3||Math.abs(bs(g[0].pts,y)-(v+m))<20*h),g.forEach((function(e){e.pts=bs(e.pts,y)})),!i||v<0){if(g=g.filter((function(e){return e.pts>=0})),!g.length)return;v=0===s?0:r&&!f?Math.max(0,y-m):g[0].pts-m}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,S=0,T=v+m;S<g.length;S++){var _=g[S],L=_.pts,R=L-T,P=Math.abs(1e3*R/a);if(R<=-E*h&&f)0===S&&(this.warn("Audio frame @ "+(L/a).toFixed(3)+"s overlaps marker by "+Math.round(1e3*R/a)+" ms."),this.nextAudioTs=v=L-m,T=L);else if(R>=E*h&&P<1e4&&f){var k=Math.round(R/h);for(T=L-k*h;T<0&&k&&h;)k--,T+=h;0===S&&(this.nextAudioTs=v=T-m),this.warn("Injecting "+k+" audio frames @ "+((T-m)/a).toFixed(3)+"s due to "+Math.round(1e3*R/a)+" ms gap.");for(var D=0;D<k;D++){var w=ps.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);w||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),w=_.unit.subarray()),g.splice(S,0,{unit:w,pts:T}),T+=h,S++}}_.pts=T,T+=h}for(var C,M=null,O=null,x=0,F=g.length;F--;)x+=g[F].unit.byteLength;for(var N=0,B=g.length;N<B;N++){var U=g[N],G=U.unit,H=U.pts;if(null!==O)c[N-1].duration=Math.round((H-O)/o);else{if(i&&"aac"===e.segmentCodec&&(H=v+m),M=H,!(x>0))return;x+=p;try{C=new Uint8Array(x)}catch(e){return void this.observer.emit(I.ERROR,I.ERROR,{type:b.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:x,reason:"fail allocating audio mdat "+x})}d||(new DataView(C.buffer).setUint32(0,x),C.set(ms.types.mdat,4))}C.set(G,p);var K=G.byteLength;p+=K,c.push(_s(!0,l,K,0)),O=H}var V=c.length;if(V){var $=c[c.length-1];v=O-m,this.nextAudioTs=v+o*$.duration;var W=d?new Uint8Array(0):ms.moof(e.sequenceNumber++,M/o,n({},e,{samples:c}));e.samples=[];var q=(M-m)/a,j=v/a,Y={data1:W,data2:C,startPTS:q,endPTS:j,startDTS:q,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,Y}},t}(F);function bs(e,t){var i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function As(e,t,i,r){var s=e.samples.length;if(s){for(var n=e.inputTimeScale,a=0;a<s;a++){var o=e.samples[a];o.pts=bs(o.pts-i.baseTime*n/i.timescale,t*n)/n,o.dts=bs(o.dts-r.baseTime*n/r.timescale,t*n)/n}var l=e.samples;return e.samples=[],{samples:l}}}function Is(e,t,i){var r=e.samples.length;if(r){for(var s=e.inputTimeScale,n=0;n<r;n++){var a=e.samples[n];a.pts=bs(a.pts-i.baseTime*s/i.timescale,t*s)/s}e.samples.sort((function(e,t){return e.pts-t.pts}));var o=e.samples;return e.samples=[],{samples:o}}}var Rs,Ps=function(e){function t(t,i,r,s){var n;return(n=e.call(this,"passthrough-remuxer",s)||this).emitInitSegment=!1,n.audioCodec=void 0,n.videoCodec=void 0,n.initData=void 0,n.initPTS=null,n.initTracks=void 0,n.lastEndTime=null,n.isVideoContiguous=!1,n}o(t,e);var i=t.prototype;return i.destroy=function(){},i.resetTimeStamp=function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)},i.resetNextTimestamp=function(){this.isVideoContiguous=!1,this.lastEndTime=null},i.resetInitSegment=function(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=!0},i.generateInitSegment=function(e,t){var i=this.audioCodec,r=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var s=this.initData=ge(e),n=s.audio,a=s.video;if(t)!function(e,t){if(e&&t){var i=t.keyId;i&&t.isCommonEncryption&&ce(e,["moov","trak"]).forEach((function(e){var t=ce(e,["mdia","minf","stbl","stsd"])[0].subarray(8),r=ce(t,["enca"]),s=r.length>0;s||(r=ce(t,["encv"])),r.forEach((function(e){ce(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=Se(e);if(t){var r=t.subarray(8,24);r.some((function(e){return 0!==e}))||(V.log("[eme] Patching keyId in 'enc"+(s?"a":"v")+">sinf>>tenc' box: "+j(r)+" -> "+j(i)),t.set(i,8))}}))}))}))}}(e,t);else{var o=n||a;null!=o&&o.encrypted&&this.warn('Init segment with encrypted track with has no key ("'+o.codec+'")!')}n&&(i=Ds(n,X,this)),a&&(r=Ds(a,Q,this));var l={};n&&a?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?l.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?l.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l},i.remux=function(e,t,i,r,s,n){var a,o,l=this.initPTS,h=this.lastEndTime,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};T(h)||(h=this.lastEndTime=s||0);var d=t.samples;if(!d.length)return u;var c={initPTS:void 0,timescale:void 0,trackId:void 0},f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=function(e,t,i){for(var r={},s=ce(e,["moof","traf"]),n=0;n<s.length;n++){var a=s[n],o=ce(a,["tfhd"])[0],l=he(o,4),h=t[l];if(h){r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:h.timescale,type:h.type});var u=r[l],d=ce(a,["tfdt"])[0];if(d){var c=d[0],f=he(d,4);1===c&&(f===se?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=se+1,f+=he(d,8))),T(f)&&(!T(u.start)||f<u.start)&&(u.start=f)}var g=h.default,p=he(o,0)|(null==g?void 0:g.flags),v=(null==g?void 0:g.duration)||0;8&p&&(v=he(o,2&p?12:8));for(var m=ce(a,["trun"]),y=u.start||0,E=0,S=v,_=0;_<m.length;_++){var L=m[_],b=he(L,4),A=u.sampleCount;u.sampleCount+=b;var I=1&L[3],R=4&L[3],P=1&L[2],k=2&L[2],D=4&L[2],w=8&L[2],C=8,M=b;for(I&&(C+=4),R&&b&&(1&L[C+1]||void 0!==u.keyFrameIndex||(u.keyFrameIndex=A),C+=4,P?(S=he(L,C),C+=4):S=v,k&&(C+=4),w&&(C+=4),y+=S,E+=S,M--);M--;)P?(S=he(L,C),C+=4):S=v,k&&(C+=4),D&&(1&L[C+1]||void 0===u.keyFrameIndex&&(u.keyFrameIndex=u.sampleCount-(M+1),u.keyFrameStart=y),C+=4),w&&(C+=4),y+=S,E+=S;!E&&v&&(E+=v*b)}u.duration+=E}}if(!Object.keys(r).some((function(e){return r[e].duration}))){for(var O=1/0,x=0,F=ce(e,["sidx"]),N=0;N<F.length;N++){var B=fe(F[N]);if(null!=B&&B.references){O=Math.min(O,B.earliestPresentationTime/B.timescale);var U=B.references.reduce((function(e,t){return e+t.info.duration||0}),0);x=Math.max(x,U+B.earliestPresentationTime/B.timescale)}}x&&T(x)&&Object.keys(r).forEach((function(e){r[e].duration||(r[e].duration=x*r[e].timescale-r[e].start)}))}return r}(d,f,this),p=f.audio?g[f.audio.id]:null,v=f.video?g[f.video.id]:null,m=ks(v,1/0),y=ks(p,1/0),E=ks(v,0,!0),S=ks(p,0,!0),_=s,L=0,b=p&&(!v||!l&&y<m||l&&l.trackId===f.audio.id),A=b?p:v;if(A){var I=A.timescale,R=A.start-s*I,P=b?f.audio.id:f.video.id;_=A.start/I,L=b?S-y:E-m,!n&&l||!function(e,t,i,r){if(null===e)return!0;var s=Math.max(r,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>s}(l,_,s,L)&&I===l.timescale||(l&&this.warn("Timestamps at playlist time: "+(n?"":"~")+s+" "+R/I+" != initPTS: "+l.baseTime/l.timescale+" ("+l.baseTime+"/"+l.timescale+") trackId: "+l.trackId),this.log("Found initPTS at playlist time: "+s+" offset: "+(_-s)+" ("+R+"/"+I+") trackId: "+P),l=null,c.initPTS=R,c.timescale=I,c.trackId=P)}else this.warn("No audio or video samples found for initPTS at playlist time: "+s);l?(c.initPTS=l.baseTime,c.timescale=l.timescale,c.trackId=l.trackId):(c.timescale&&void 0!==c.trackId&&void 0!==c.initPTS||(this.warn("Could not set initPTS"),c.initPTS=_,c.timescale=1,c.trackId=-1),this.initPTS=l={baseTime:c.initPTS,timescale:c.timescale,trackId:c.trackId});var k=_-l.baseTime/l.timescale,D=k+L;L>0?this.lastEndTime=D:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var w=!!f.audio,C=!!f.video,M="";w&&(M+="audio"),C&&(M+="video");var O={data1:d,startPTS:k,startDTS:k,endPTS:D,endDTS:D,type:M,hasAudio:w,hasVideo:C,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};u.audio=w&&!C?O:void 0,u.video=C?O:void 0;var x=null==v?void 0:v.sampleCount;if(x){var F=v.keyFrameIndex,N=-1!==F;O.nb=x,O.dropped=0===F||this.isVideoContiguous?0:N?F:x,O.independent=N,O.firstKeyFrame=F,N&&v.keyFrameStart&&(O.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=N),this.isVideoContiguous||(this.isVideoContiguous=N),O.dropped&&this.warn("fmp4 does not start with IDR: firstIDR "+F+"/"+x+" dropped: "+O.dropped+" start: "+(O.firstKeyFramePTS||"NA"))}return u.initSegment=c,u.id3=As(i,s,l,l),r.samples.length&&(u.text=Is(r,s,l)),u},t}(F);function ks(e,t,i){return void 0===i&&(i=!1),void 0!==(null==e?void 0:e.start)?(e.start+(i?e.duration:0))/e.timescale:t}function Ds(e,t,i){var r=e.codec;return r&&r.length>4?r:t===X?"ec-3"===r||"ac-3"===r||"alac"===r?r:"fLaC"===r||"Opus"===r?Be(r,!1):(i.warn('Unhandled audio codec "'+r+'" in mp4 MAP'),r||"mp4a"):(i.warn('Unhandled video codec "'+r+'" in mp4 MAP'),r||"avc1")}try{Rs=self.performance.now.bind(self.performance)}catch(e){Rs=Date.now}var ws=[{demux:es,remux:Ps},{demux:ls,remux:Ls},{demux:Yr,remux:Ls},{demux:Jr,remux:Ls}];ws.splice(2,0,{demux:Xr,remux:Ls});var Cs=function(){function e(e,t,i,r,s,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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.id=s,this.logger=n}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,i,r){var s=this,n=i.transmuxing;n.executeStart=Rs();var a=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var h=r||o,u=h.contiguous,d=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,p=h.initSegmentChange,v=l.audioCodec,m=l.videoCodec,y=l.defaultInitPts,E=l.duration,S=l.initSegmentData,T=function(e,t){var i=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t),i}(a,t);if(T&&oi(T.method)){var _=this.getDecrypter(),L=li(T.method);if(!_.isSync())return this.asyncResult=!0,this.decryptionPromise=_.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,L).then((function(e){var t=s.push(e,null,i);return s.decryptionPromise=null,t})),this.decryptionPromise;var R=_.softwareDecrypt(a,T.key.buffer,T.iv.buffer,L);if(i.part>-1){var P=_.flush();R=P?P.buffer:P}if(!R)return n.executeEnd=Rs(),Ms(i);a=new Uint8Array(R)}var k=this.needsProbing(d,c);if(k){var D=this.configureTransmuxer(a);if(D)return this.logger.warn("[transmuxer] "+D.message),this.observer.emit(I.ERROR,I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),n.executeEnd=Rs(),Ms(i)}(d||c||p||k)&&this.resetInitSegment(S,v,m,E,t),(d||p||k)&&this.resetInitialTimestamp(y),u||this.resetContiguity();var w=this.transmux(a,T,g,f,i);this.asyncResult=Os(w);var C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,n.executeEnd=Rs(),w},t.flush=function(e){var t=this,i=e.transmuxing;i.executeStart=Rs();var r=this.decrypter,s=this.currentTransmuxState,n=this.decryptionPromise;if(n)return this.asyncResult=!0,n.then((function(){return t.flush(e)}));var a=[],o=s.timeOffset;if(r){var l=r.flush();l&&a.push(this.push(l.buffer,null,e))}var h=this.demuxer,u=this.remuxer;if(!h||!u){i.executeEnd=Rs();var d=[Ms(e)];return this.asyncResult?Promise.resolve(d):d}var c=h.flush(o);return Os(c)?(this.asyncResult=!0,c.then((function(i){return t.flushRemux(a,i,e),a}))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)},t.flushRemux=function(e,t,i){var r=t.audioTrack,s=t.videoTrack,n=t.id3Track,a=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,h=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+i.sn+(i.part>-1?" part: "+i.part:"")+" of "+(this.id===w?"level":"track")+" "+i.level);var u=this.remuxer.remux(r,s,n,a,h,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Rs()},t.resetInitialTimestamp=function(e){var t=this.demuxer,i=this.remuxer;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,i,r,s){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,s))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,i,r,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s)},t.transmuxUnencrypted=function(e,t,i,r){var s=this.demuxer.demux(e,t,!1,!this.config.progressive),n=s.audioTrack,a=s.videoTrack,o=s.id3Track,l=s.textTrack;return{remuxResult:this.remuxer.remux(n,a,o,l,t,i,!1,this.id),chunkMeta:r}},t.transmuxSampleAes=function(e,t,i,r,s){var n=this;return this.demuxer.demuxSampleAes(e,t,i).then((function(e){return{remuxResult:n.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,n.id),chunkMeta:s}}))},t.configureTransmuxer=function(e){for(var t,i=this.config,r=this.observer,s=this.typeSupported,n=0,a=ws.length;n<a;n++){var o;if(null!=(o=ws[n].demux)&&o.probe(e,this.logger)){t=ws[n];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,h=this.remuxer,u=t.remux,d=t.demux;h&&h instanceof u||(this.remuxer=new u(r,i,s,this.logger)),l&&l instanceof d||(this.demuxer=new d(r,i,s,this.logger),this.probe=d.probe)},t.needsProbing=function(e,t){return!this.demuxer||!this.remuxer||e||t},t.getDecrypter=function(){var e=this.decrypter;return e||(e=this.decrypter=new Bt(this.config)),e},e}(),Ms=function(e){return{remuxResult:{},chunkMeta:e}};function Os(e){return"then"in e&&e.then instanceof Function}var xs=function(e,t,i,r,s){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=s||null},Fs=function(e,t,i,r,s,n){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=s,this.initSegmentChange=n},Ns=[];function Bs(e,t,i){if(!((r=t.remuxResult).audio||r.video||r.text||r.id3||r.initSegment))return!1;var r,s=[],n=t.remuxResult,a=n.audio,o=n.video;return a&&Us(s,a),o&&Us(s,o),e.postMessage({event:"transmuxComplete",data:t,instanceNo:i},s),!0}function Us(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function Gs(e,t,i,r){t.reduce((function(t,i){return Bs(e,i,r)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0],instanceNo:r}),e.postMessage({event:"flush",data:i,instanceNo:r})}function Hs(e,t,i){self.postMessage({event:e,data:t,instanceNo:i})}void 0!==i&&i&&self.addEventListener("message",(function(e){var t=e.data,i=t.instanceNo;if(void 0!==i){var r=Ns[i];if("reset"===t.cmd&&(delete Ns[t.resetNo],r&&r.destroy(),t.cmd="init"),"init"===t.cmd){var s=JSON.parse(t.config),n=new y;n.on(I.FRAG_DECRYPTED,Hs),n.on(I.ERROR,Hs);var a=K(s.debug,t.id);return function(e,t){var i=function(i){e[i]=function(){var e=Array.prototype.join.call(arguments," ");Hs("workerLog",{logType:i,message:e},t)}};for(var r in e)i(r)}(a,i),Ns[i]=new Cs(n,t.typeSupported,s,"",t.id,a),void Hs("init",null,i)}if(r)switch(t.cmd){case"configure":r.configure(t.config);break;case"demux":var o=r.push(t.data,t.decryptdata,t.chunkMeta,t.state);Os(o)?o.then((function(e){Bs(self,e,i)})).catch((function(e){Hs(I.ERROR,{instanceNo:i,type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker push error"},i)})):Bs(self,o,i);break;case"flush":var l=t.chunkMeta,h=r.flush(l);Os(h)?h.then((function(e){Gs(self,e,l,i)})).catch((function(e){Hs(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker flush error"},i)})):Gs(self,h,l,i)}}}));var Ks="1.6.12",Vs={},$s=0,Ws=function(){function e(e,i,r,s){var n=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=$s++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,i=n.hls;if(i&&null!=t&&t.event&&t.instanceNo===n.instanceNo)switch(t.event){case"init":var r,s=null==(r=n.workerContext)?void 0:r.objectURL;s&&self.URL.revokeObjectURL(s);break;case"transmuxComplete":n.handleTransmuxComplete(t.data);break;case"flush":n.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=n.frag,t.data.part=n.part,t.data.id=n.id,i.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(n.hls){var t=new Error(e.message+" ("+e.filename+":"+e.lineno+")");n.hls.config.enableWorker=!1,n.hls.logger.warn('Error in "'+n.id+'" Web Worker, fallback to inline'),n.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var a=e.config;this.hls=e,this.id=i,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=r,this.onFlush=s;var o=function(e,t){(t=t||{}).frag=n.frag||void 0,e===I.ERROR&&(t.parent=n.id,t.part=n.part,n.error=t.error),n.hls.trigger(e,t)};this.observer=new y,this.observer.on(I.FRAG_DECRYPTED,o),this.observer.on(I.ERROR,o);var l=Ke(a.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var h=this.hls.logger;a.workerPath;try{a.workerPath?(h.log("loading Web Worker "+a.workerPath+' for "'+i+'"'),this.workerContext=function(e){var t=Vs[e];if(t)return t.clientCount++,t;var i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Vs[e]=r,r}(a.workerPath)):(h.log('injecting Web Worker for "'+i+'"'),this.workerContext=function(){var e=Vs[Ks];if(e)return e.clientCount++,e;var i=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+t.toString()+")(true);"],{type:"text/javascript"}),r=self.URL.createObjectURL(i),s={worker:new self.Worker(r),objectURL:r,clientCount:1};return Vs[Ks]=s,s}());var u=this.workerContext.worker;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:i,config:it(a)})}catch(t){h.warn('Error setting up "'+i+'" Web Worker, fallback to inline',t),this.terminateWorker(),this.error=null,this.transmuxer=new Cs(this.observer,l,a,"",i,e.logger)}}else this.transmuxer=new Cs(this.observer,l,a,"",i,e.logger)}var i=e.prototype;return i.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=$s++;var t=this.hls.config,i=Ke(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:it(t)})}},i.terminateWorker=function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=Vs[e||Ks];if(t&&1==t.clientCount--){var i=t.worker,r=t.objectURL;delete Vs[e||Ks],r&&self.URL.revokeObjectURL(r),i.terminate()}}(this.hls.config.workerPath)}},i.destroy=function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null},i.push=function(e,t,i,r,s,n,a,o,l,h){var u,d,c=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,g=this.transmuxer,p=n?n.start:s.start,v=s.decryptdata,m=this.frag,y=!(m&&s.cc===m.cc),E=!(m&&l.level===m.level),S=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,_=0===S&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),L=!E&&(1===S||0===S&&(1===T||_&&T<=0)),b=self.performance.now();(E||S||0===s.stats.parsing.start)&&(s.stats.parsing.start=b),!n||!T&&L||(n.stats.parsing.start=b);var A=!(m&&(null==(u=s.initSegment)?void 0:u.url)===(null==(d=m.initSegment)?void 0:d.url)),I=new Fs(y,L,o,E,p,A);if(!L||y||A){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+s.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===w?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+p+"\n initSegmentChange: "+A);var R=new xs(i,r,t,a,h);this.configureTransmuxer(R)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:v,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(g){var P=g.push(e,v,l,I);Os(P)?P.then((function(e){c.handleTransmuxComplete(e)})).catch((function(e){c.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(P)}},i.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var i=this.instanceNo,r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:e});else if(r){var s=r.flush(e);Os(s)?s.then((function(i){t.handleFlushResult(i,e)})).catch((function(i){t.transmuxerError(i,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}},i.transmuxerError=function(e,t,i){this.hls&&(this.error=e,this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))},i.handleFlushResult=function(e,t){var i=this;e.forEach((function(e){i.handleTransmuxComplete(e)})),this.onFlush(t)},i.configureTransmuxer=function(e){var t=this.instanceNo,i=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)},i.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}(),qs=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"audio-stream-controller",C)||this).mainAnchor=null,s.mainFragLoading=null,s.audioOnly=!1,s.bufferedTrack=null,s.switchingTrack=null,s.trackId=-1,s.waitingData=null,s.mainDetails=null,s.flushing=!1,s.bufferFlushed=!1,s.cachedTrackLoadedData=null,s.registerListeners(),s}o(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.resetItem()},i.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(I.BUFFER_RESET,this.onBufferReset,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(I.FRAG_LOADING,this.onFragLoading,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){var t=this.hls;t&&(e.prototype.unregisterListeners.call(this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(I.BUFFER_RESET,this.onBufferReset,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(I.FRAG_LOADING,this.onFragLoading,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this))},i.onInitPtsFound=function(e,t){var i=t.frag,r=t.id,s=t.initPTS,n=t.timescale,a=t.trackId;if(r===w){var o=i.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:s,timescale:n,trackId:a},this.log("InitPTS for cc: "+o+" found from main: "+s/n+" ("+s+"/"+n+") trackId: "+a),this.mainAnchor=i,this.state===lr.WAITING_INIT_PTS){var h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==o)&&this.syncWithAnchor(i,null==h?void 0:h.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(i,l)):this.state===lr.IDLE&&this.tick()}},i.getLoadPosition=function(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:e.prototype.getLoadPosition.call(this)},i.syncWithAnchor=function(e,t){var i,r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(!t||(null==r?void 0:r.cc)!==t.cc){var s=(r||e).cc,n=vt(this.getLevelDetails(),s,this.getLoadPosition());n&&(this.log("Syncing with main frag at "+n.start+" cc "+n.cc),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===lr.IDLE&&this.doTickIdle())}},i.startLoad=function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=lr.STOPPED);var i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i,this.state=lr.IDLE):this.state=lr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.doTick=function(){switch(this.state){case lr.IDLE:this.doTickIdle();break;case lr.WAITING_TRACK:var t=this.levels,i=this.trackId,r=null==t?void 0:t[i],s=null==r?void 0:r.details;if(s&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(s))break;this.state=lr.WAITING_INIT_PTS}break;case lr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case lr.WAITING_INIT_PTS:var n=this.waitingData;if(n){var a=n.frag,o=n.part,l=n.cache,h=n.complete,u=this.mainAnchor;if(void 0!==this.initPTS[a.cc]){this.waitingData=null,this.state=lr.FRAG_LOADING;var d={frag:a,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),h&&e.prototype._handleFragmentLoadComplete.call(this,d)}else u&&u.cc!==n.frag.cc&&this.syncWithAnchor(u,n.frag)}else this.state=lr.IDLE}this.onTickEnd()},i.resetLoadingState=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),e.prototype.resetLoadingState.call(this)},i.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)},i.doTickIdle=function(){var e,t=this.hls,i=this.levels,r=this.media,s=this.trackId,n=t.config;if(this.buffering&&(r||this.primaryPrefetch||!this.startFragRequested&&n.startFragPrefetch)&&null!=i&&i[s]){var a=i[s],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=lr.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,X,C));var h=this.getFwdBufferInfo(l,C);if(null!==h){if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(I.BUFFER_EOS,{type:"audio"}),void(this.state=lr.ENDED);var u=h.len,d=t.maxBufferLength,c=o.fragments,f=c[0].start,g=this.getLoadPosition(),p=this.flushing?g:h.end;if(this.switchingTrack&&r){var v=g;o.PTSKnown&&v<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(!(u>=d&&!this.switchingTrack&&p<c[c.length-1].start)){var m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,h,w,d)),m){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&ee(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Dt&&(this.mainFragLoading=y=null),y&&ee(y))){if(m.start>y.end){var E=this.fragmentTracker.getFragAtPos(p,w);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(m.start>y.end)return}this.loadFragment(m,a,p)}else this.bufferFlushed=!0}}}},i.onMediaDetaching=function(t,i){this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this,t,i)},i.onAudioTracksUpdated=function(e,t){var i=t.audioTracks;this.resetTransmuxer(),this.levels=i.map((function(e){return new et(e)}))},i.onAudioTrackSwitching=function(e,t){var i=!!t.url;this.trackId=t.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==lr.STOPPED&&(this.setInterval(100),this.state=lr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},i.onLevelLoaded=function(e,t){this.mainDetails=t.details;var i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(I.AUDIO_TRACK_LOADED,i))},i.onAudioTrackLoaded=function(e,t){var i,r=this.levels,s=t.details,n=t.id,a=t.groupId,o=t.track;if(r){var l=this.mainDetails;if(!l||s.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==lr.STOPPED&&(this.state=lr.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+n+' "'+o.name+'" of "'+a+'" loaded ['+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+",duration:"+s.totalduration);var h=r[n],u=0;if(s.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;var d;h.details&&(u=this.alignPlaylists(s,h.details,null==(d=this.levelLastLoaded)?void 0:d.details)),s.alignedSliding||(sr(s,l),s.alignedSliding||nr(s,l),u=s.fragmentStart)}h.details=s,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(I.AUDIO_TRACK_UPDATED,{details:s,id:n,groupId:t.groupId}),this.state!==lr.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=lr.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+n+' "'+o.name+'" of "'+a+'"')},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,s=e.payload,n=this.config,a=this.trackId,o=this.levels;if(o){var l=o[a];if(l){var h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);var u=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new Ws(this.hls,C,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){var g=r?r.index:-1,p=-1!==g,v=new Wt(i.level,i.sn,i.stats.chunkCount,s.byteLength,g,p);d.push(s,f,u,"",i,r,h.totalduration,!1,v,c)}else this.log("Unknown video PTS for cc "+i.cc+", waiting for video PTS before demuxing audio frag "+i.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+a),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new dr,complete:!1}).cache.push(new Uint8Array(s)),this.state!==lr.STOPPED&&(this.state=lr.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},i.onBufferReset=function(){this.mediaBuffer=null},i.onBufferCreated=function(e,t){this.bufferFlushed=this.flushing=!1;var i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)},i.onFragLoading=function(e,t){!this.audioOnly&&t.frag.type===w&&ee(t.frag)&&(this.mainFragLoading=t,this.state===lr.IDLE&&this.tick())},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part;if(i.type===C)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"));else{if(ee(i)){this.fragPrevious=i;var s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(I.AUDIO_TRACK_SWITCHED,u({},s)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==w||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},i.onError=function(t,i){var r;if(i.fatal)this.state=lr.ERROR;else switch(i.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(C,i);break;case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==lr.WAITING_TRACK||(null==(r=i.context)?void 0:r.type)!==k||(this.state=lr.IDLE);break;case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)||this.resetLoadingState();break;case A.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}},i.onBufferFlushing=function(e,t){t.type!==Q&&(this.flushing=!0)},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==Q){this.flushing=!1,this.bufferFlushed=!0,this.state===lr.ENDED&&(this.state=lr.IDLE);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,C),this.tick())}},i._handleTransmuxComplete=function(e){var t,i="audio",r=this.hls,s=e.remuxResult,a=e.chunkMeta,o=this.getCurrentContext(a);if(o){var l=o.frag,h=o.part,u=o.level,d=u.details,c=s.audio,f=s.text,g=s.id3,p=s.initSegment;if(!this.fragContextChanged(l)&&d){if(this.state=lr.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){var v=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,v,a),r.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:p.tracks})}if(c){var m=c.startPTS,y=c.endPTS,E=c.startDTS,S=c.endDTS;h&&(h.elementaryStreams[X]={startPTS:m,endPTS:y,startDTS:E,endDTS:S}),l.setElementaryStreamInfo(X,m,y,E,S),this.bufferFragmentData(c,l,h,a)}if(null!=g&&null!=(t=g.samples)&&t.length){var T=n({id:i,frag:l,details:d},g);r.trigger(I.FRAG_PARSING_METADATA,T)}if(f){var _=n({id:i,frag:l,details:d},f);r.trigger(I.FRAG_PARSING_USERDATA,_)}}else this.fragmentTracker.removeFragment(l)}else this.resetWhenMissingContext(a)},i._bufferInitSegment=function(e,t,i,r){if(this.state===lr.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var s=t.audio;s.id=C;var n=e.audioCodec;this.log("Init audio buffer, container:"+s.container+", codecs[level/parsed]=["+n+"/"+s.codec+"]"),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(I.BUFFER_CODECS,t);var a=s.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(I.BUFFER_APPENDING,o)}this.tickImmediate()}},i.loadFragment=function(t,i,r){var s,n=this.fragmentTracker.getState(t);if(this.switchingTrack||n===Rt||n===kt)if(ee(t))if(null!=(s=i.details)&&s.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=lr.WAITING_INIT_PTS;var a=this.mainDetails;a&&a.fragmentStart!==i.details.fragmentStart&&nr(i.details,a)}else e.prototype.loadFragment.call(this,t,i,r);else this._loadInitSegment(t,i);else this.clearTrackerIfNeeded(t)},i.flushAudioIfNeeded=function(t){if(this.media&&this.bufferedTrack){var i=this.bufferedTrack;ot({name:i.name,lang:i.lang,assocLang:i.assocLang,characteristics:i.characteristics,audioCodec:i.audioCodec,channels:i.channels},t,lt)||(ut(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}},i.completeAudioSwitch=function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(I.AUDIO_TRACK_SWITCHED,u({},e))},t}(hr),js=function(e){function t(t,i){var r;return(r=e.call(this,i,t.logger)||this).hls=void 0,r.canLoad=!1,r.timer=-1,r.hls=t,r}o(t,e);var i=t.prototype;return i.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},i.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},i.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},i.stopLoad=function(){this.canLoad=!1,this.clearTimer()},i.switchParams=function(e,t,i){var r=null==t?void 0:t.renditionReports;if(r){for(var s=-1,n=0;n<r.length;n++){var a=r[n],o=void 0;try{o=new self.URL(a.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: "+e),o=a.URI||""}if(o===e){s=n;break}o===e.substring(0,o.length)&&(s=n)}if(-1!==s){var l=r[s],h=parseInt(l["LAST-MSN"])||t.lastPartSn,u=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);u>=0&&d>t.partTarget&&(u+=1)}var c=i&&Je(i);return new Ze(h,u>=0?u:void 0,c)}}},i.loadPlaylist=function(e){this.clearTimer()},i.loadingPlaylist=function(e,t){this.clearTimer()},i.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},i.getUrlWithDirectives=function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}return e},i.playlistLoaded=function(e,t,i){var r=t.details,s=t.stats,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;r.advancedDateTime=Date.now()-a;var o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){var l=Math.max(o||0,0);r.appliedTimelineOffset=l,r.fragments.forEach((function(e){e.setStart(e.playlistOffset+l)}))}if(r.live||null!=i&&i.live){var h="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){$i(i,r,this);var u=r.playlistParsingError;if(u){this.warn(u);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var c,f=t.networkDetails;return void d.trigger(I.ERROR,{type:b.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:u,reason:u.message,level:t.level||void 0,parent:null==(c=r.fragments[0])?void 0:c.type,networkDetails:f,stats:s})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);var g,p=this.hls.mainForwardBufferInfo,v=p?p.end-p.len:0,m=Yi(r,1e3*(r.edge-v));if(r.requestScheduled+m<n?r.requestScheduled=n:r.requestScheduled+=m,this.log("live playlist "+e+" "+(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;var y=void 0,E=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){var S=this.hls.config.lowLatencyMode,T=r.lastPartSn,_=r.endSN,L=r.lastPartIndex,R=T===_;-1!==L?R?(y=_+1,E=S?0:L):(y=T,E=S?L+1:r.maxPartIndex):y=_+1;var P=r.age,k=P+r.ageHeader,D=Math.min(k-r.partTarget,1.5*r.targetduration);if(D>0){if(k>3*r.targetduration)this.log("Playlist last advanced "+P.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=i&&i.tuneInGoal&&k-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+i.tuneInGoal+" to: "+D+" with playlist age: "+r.age),D=0;else{var w=Math.floor(D/r.targetduration);y+=w,void 0!==E&&(E+=Math.round(D%r.targetduration/r.partTarget)),this.log("CDN Tune-in age: "+r.ageHeader+"s last advanced "+P.toFixed(2)+"s goal: "+D+" skip sn "+w+" to part "+E)}r.tuneInGoal=D}if(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E),S||!R)return r.requestScheduled=n,void this.loadingPlaylist(h,g)}else(r.canBlockReload||r.canSkipUntil)&&(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E));g&&void 0!==y&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(m-2*a,m/2)),this.scheduleLoading(h,g,r)}else this.clearTimer()},i.scheduleLoading=function(e,t,i){var r=this,s=i||e.details;if(s){var n=self.performance.now(),a=s.requestScheduled;if(n>=a)this.loadingPlaylist(e,t);else{var o=a-n;this.log("reload live playlist "+(e.name||e.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return r.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},i.getDeliveryDirectives=function(e,t,i,r){var s=Je(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=""),new Ze(i,r,s)},i.checkRetry=function(e){var t=this,i=e.details,r=mt(e),s=e.errorAction,n=s||{},a=n.action,o=n.retryCount,l=void 0===o?0:o,h=n.retryConfig,u=!!s&&!!h&&(5===a||!s.resolved&&2===a);if(u){var d;if(l>=h.maxNumRetry)return!1;if(r&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" without delivery-directives'),this.loadPlaylist();else{var c=Tt(h,l);this.clearTimer(),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" in '+c+"ms")}e.levelRetry=!0,s.resolved=!0}return u},t}(F);function Ys(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(!zs(e[i].attrs,t[i].attrs))return!1;return!0}function zs(e,t,i){var r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((function(i){return e[i]!==t[i]}))}function Xs(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var Qs=function(e){function t(t){var i;return(i=e.call(this,t,"audio-track-controller")||this).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.registerListeners(),i}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(I.ERROR,this.onError,this)},i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,e.prototype.destroy.call(this)},i.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.audioTracks||[]},i.onAudioTrackLoaded=function(e,t){var i=t.id,r=t.groupId,s=t.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=t.details,this.log("Audio track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Audio track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(e,t){e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.audioPreference;if(!s&&a){var o=at(a,n,lt);if(o>-1)s=n[o];else{var l=at(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var u={audioTracks:n};this.log("Updating audio tracks, "+n.length+" track(s) found in group(s): "+(null==i?void 0:i.join(","))),this.hls.trigger(I.AUDIO_TRACKS_UPDATED,u);var d=this.trackId;if(-1!==h&&-1===d)this.setAudioTrack(h);else if(n.length&&-1===d){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+n.length);this.warn(f.message),this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==k||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&ot(e,r,lt))return r;var s=at(e,this.tracksInGroup,lt);if(s>-1){var n=this.tracksInGroup[s];return this.setAudioTrack(s),n}if(r){var a=t.loadLevel;-1===a&&(a=t.firstAutoLevel);var o=function(e,t,i,r,s){var n=t[r],a=t.reduce((function(e,t,i){var r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));var o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),u=ht(t,r,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;var r=t.audioGroups,n=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return at(e,n,s)>-1}));return u>-1?u:ht(t,r,(function(t){var r=t.audioGroups,n=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return at(e,n,s)>-1}))}(e,t.levels,i,a,lt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=at(e,i);if(l>-1)return i[l]}}}return null},i.setAudioTrack=function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(!(e===this.trackId&&r===i&&s||(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(I.AUDIO_TRACK_SWITCHING,u({},r)),s))){var n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=0;i<t.length;i++){var r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||ot(e,r,lt)))return i}if(e){for(var s=e.name,n=e.lang,a=e.assocLang,o=e.characteristics,l=e.audioCodec,h=e.channels,u=0;u<t.length;u++)if(ot({name:s,lang:n,assocLang:a,characteristics:o,audioCodec:l,channels:h},t[u],lt))return u;for(var d=0;d<t.length;d++){var c=t[d];if(zs(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var g=t[f];if(zs(e.attrs,g.attrs,["LANGUAGE"]))return f}}return-1},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var i=this.currentTrack;this.shouldLoadPlaylist(i)&&ut(i.url,this.hls)&&this.scheduleLoading(i,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,s=t.groupId,n=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading audio-track "+r+' "'+t.name+'" lang:'+t.lang+" group:"+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+n),this.hls.trigger(I.AUDIO_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:i||null,track:t})},r(t,[{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}}])}(js),Js=function(){function e(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}var t=e.prototype;return t.destroy=function(){this.tracks=this.queues=null},t.append=function(e,t,i){if(null!==this.queues&&null!==this.tracks){var r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}},t.appendBlocker=function(e){var t=this;return new Promise((function(i){var r={label:"async-blocker",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(r,e)}))},t.prependBlocker=function(e){var t=this;return new Promise((function(i){if(t.queues){var r={label:"async-blocker-prepend",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(r)}}))},t.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(e){var t,i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))}))},t.unblockAudio=function(e){null!==this.queues&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")},t.executeNext=function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var i=t[0];try{i.execute()}catch(t){var r;if(i.onError(t),null===this.queues||null===this.tracks)return;var s=null==(r=this.tracks[e])?void 0:r.buffer;null!=s&&s.updating||this.shiftAndExecuteNext(e)}}}},t.shiftAndExecuteNext=function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))},t.current=function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null},t.toString=function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},t.list=function(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?"SourceBuffer"+(r.updating?" updating":"")+(i.ended?" ended":"")+(i.ending?" ending":""):"none"},t.listOps=function(e){var t;return(null==(t=this.queues)?void 0:t[e].map((function(e){return e.label})).join(", "))||""},e}(),Zs=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,en="HlsJsTrackRemovedError",tn=function(e){function t(t){var i;return(i=e.call(this,t)||this).name=en,i}return o(t,e),t}(f(Error)),rn=function(e){function t(t,i){var r,s;return(r=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.details=null,r._objectUrl=null,r.operationQueue=null,r.bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.lastMpegAudioChunk=null,r.blockedAudioAppend=null,r.lastVideoAppendEnd=0,r.appendSource=void 0,r.transferData=void 0,r.overrides=void 0,r.appendErrors={audio:0,video:0,audiovideo:0},r.tracks={},r.sourceBuffers=[[null,null],[null,null]],r._onEndStreaming=function(e){var t;r.hls&&"open"===(null==(t=r.mediaSource)?void 0:t.readyState)&&r.hls.pauseBuffering()},r._onStartStreaming=function(e){r.hls&&r.hls.resumeBuffering()},r._onMediaSourceOpen=function(e){var t=r,i=t.media,s=t.mediaSource;e&&r.log("Media source opened"),i&&s&&(s.removeEventListener("sourceopen",r._onMediaSourceOpen),i.removeEventListener("emptied",r._onMediaEmptied),r.updateDuration(),r.hls.trigger(I.MEDIA_ATTACHED,{media:i,mediaSource:s}),null!==r.mediaSource&&r.checkPendingTracks())},r._onMediaSourceClose=function(){r.log("Media source closed")},r._onMediaSourceEnded=function(){r.log("Media source ended")},r._onMediaEmptied=function(){var e=r,t=e.mediaSrc,i=e._objectUrl;t!==i&&r.error("Media element src was set while attaching MediaSource ("+i+" > "+t+")")},r.hls=t,r.fragmentTracker=i,r.appendSource=(s=$(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),r.initTracks(),r.registerListeners(),r}o(t,e);var i=t.prototype;return i.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},i.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null},i.registerListeners=function(){var e=this.hls;e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.BUFFER_RESET,this.onBufferReset,this),e.on(I.BUFFER_APPENDING,this.onBufferAppending,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.BUFFER_EOS,this.onBufferEos,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.FRAG_PARSED,this.onFragParsed,this),e.on(I.FRAG_CHANGED,this.onFragChanged,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.BUFFER_RESET,this.onBufferReset,this),e.off(I.BUFFER_APPENDING,this.onBufferAppending,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_EOS,this.onBufferEos,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.FRAG_PARSED,this.onFragParsed,this),e.off(I.FRAG_CHANGED,this.onFragChanged,this),e.off(I.ERROR,this.onError,this)},i.transferMedia=function(){var e=this,t=this.media,i=this.mediaSource;if(!t)return null;var r={};if(this.operationQueue){var s=this.isUpdating();s||this.operationQueue.removeBlockers();var a=this.isQueued();(s||a)&&this.warn("Transfering MediaSource with"+(a?" operations in queue":"")+(s?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var o=this.transferData;return!this.sourceBufferCount&&o&&o.mediaSource===i?n(r,o.tracks):this.sourceBuffers.forEach((function(t){var i=t[0];i&&(r[i]=n({},e.tracks[i]),e.removeBuffer(i)),t[0]=t[1]=null})),{media:t,mediaSource:i,tracks:r}},i.initTracks=function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},i.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},i.onManifestParsed=function(e,t){var i,r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(r+" bufferCodec event(s) expected."),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()},i.onMediaAttaching=function(e,t){var i=this.media=t.media;this.transferData=this.overrides=void 0;var r=$(this.appendSource);if(r){var s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var n=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(n),s)this._objectUrl=i.src,this.attachTransferred();else{var a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&n instanceof o,sn(i),function(e,t){var i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,a),i.load()}catch(e){i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}},i.assignMediaSource=function(e){var t,i;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(i=e.constructor)?void 0:i.name)),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))},i.attachTransferred=function(){var e=this,t=this.media,i=this.transferData;if(i&&t){var r=this.tracks,s=i.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=function(){Promise.resolve().then((function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()}))};if(s&&n&&a){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+it(r,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+it(s,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!W(s,r)){i.mediaSource=null,i.tracks=void 0;var l=t.currentTime,h=this.details,u=Math.max(l,(null==h?void 0:h.fragments[0].start)||0);return u-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+u):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(s)+'"->"'+Object.keys(r)+'") start time: '+u+" currentTime: "+l),this.onMediaDetaching(I.MEDIA_DETACHING,{}),this.onMediaAttaching(I.MEDIA_ATTACHING,i),void(t.currentTime=u))}this.transferData=void 0,n.forEach((function(t){var i=t,r=s[i];if(r){var n=r.buffer;if(n){var a=e.fragmentTracker,o=r.id;if(a.hasFragments(o)||a.hasParts(o)){var l=jt.getBuffered(n);a.detectEvictedFragments(i,l,o,null,!0)}var h=nn(i),u=[i,n];e.sourceBuffers[h]=u,n.updating&&e.operationQueue&&e.operationQueue.prependBlocker(i),e.trackSourceBuffer(i,r)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},i.onMediaDetaching=function(e,t){var i=this,r=!!t.transferMedia;this.transferData=this.overrides=void 0;var s=this.media,n=this.mediaSource,a=this._objectUrl;if(n){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===n.readyState;try{for(var l=n.sourceBuffers,h=l.length;h--;)o&&l[h].abort(),n.removeSourceBuffer(l[h]);o&&n.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&sn(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(I.MEDIA_DETACHED,t)},i.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];i&&e.resetBuffer(i)})),this.initTracks()},i.resetBuffer=function(e){var t,i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},i.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[nn(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)},i.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Js(this.tracks)},i.onBufferCodecs=function(e,t){var i,r=this,s=this.tracks,n=Object.keys(t);this.log('BUFFER_CODECS: "'+n+'" (current SB count '+this.sourceBufferCount+")");var a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some((function(e){return!s[e]}));a||o?this.warn('Unsupported transition between "'+Object.keys(s)+'" and "'+n+'" SourceBuffers'):(n.forEach((function(e){var i,n,a=t[e],o=a.id,l=a.codec,h=a.levelCodec,u=a.container,d=a.metadata,c=a.supplemental,f=s[e],g=null==(i=r.transferData)||null==(i=i.tracks)?void 0:i[e],p=null!=g&&g.buffer?g:f,v=(null==p?void 0:p.pendingCodec)||(null==p?void 0:p.codec),m=null==p?void 0:p.levelCodec;f||(f=s[e]={buffer:void 0,listeners:[],codec:l,supplemental:c,container:u,levelCodec:h,metadata:d,id:o});var y=Ue(v,m),E=null==y?void 0:y.replace(Zs,"$1"),S=Ue(l,h),T=null==(n=S)?void 0:n.replace(Zs,"$1");S&&y&&E!==T&&("audio"===e.slice(0,5)&&(S=Be(S,r.appendSource)),r.log("switching codec "+v+" to "+S),S!==(f.pendingCodec||f.codec)&&(f.pendingCodec=S),f.container=u,r.appendChangeType(e,u,S))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(i=t.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))},i.appendChangeType=function(e,t,i){var r=this,s=t+";codecs="+i,n={label:"change-type="+s,execute:function(){var n=r.tracks[e];if(n){var a=n.buffer;null!=a&&a.changeType&&(r.log("changing "+e+" sourceBuffer type to "+s),a.changeType(s),n.codec=i,n.container=t)}r.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(n,e,this.isPending(this.tracks[e]))},i.blockAudio=function(e){var t,i=this,r=e.start,s=r+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(r,w))?void 0:t.gap)){var n={label:"block-audio",execute:function(){var e,t=i.tracks.video;(i.lastVideoAppendEnd>s||null!=t&&t.buffer&&jt.isBuffered(t.buffer,s)||!0===(null==(e=i.fragmentTracker.getAppendedFrag(s,w))?void 0:e.gap))&&(i.blockedAudioAppend=null,i.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){i.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}},i.unblockAudio=function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))},i.onBufferAppending=function(e,t){var i=this,r=this.tracks,s=t.data,n=t.type,a=t.parent,o=t.frag,l=t.part,h=t.chunkMeta,u=t.offset,d=h.buffering[n],c=o.sn,f=o.cc,g=self.performance.now();d.start=g;var p=o.stats.buffering,v=l?l.stats.buffering:null;0===p.start&&(p.start=g),v&&0===v.start&&(v.start=g);var m=r.audio,y=!1;"audio"===n&&"audio/mpeg"===(null==m?void 0:m.container)&&(y=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var E=r.video,S=null==E?void 0:E.buffer;if(S&&"initSegment"!==c){var _=l||o,L=this.blockedAudioAppend;if("audio"!==n||"main"===a||this.blockedAudioAppend||E.ending||E.ended){if("video"===n){var R=_.end;if(L){var P=L.frag.start;(R>P||R<this.lastVideoAppendEnd||jt.isBuffered(S,P))&&this.unblockAudio()}this.lastVideoAppendEnd=R}}else{var k=_.start+.05*_.duration,D=S.buffered,C=this.currentOp("video");D.length||C?!C&&!jt.isBuffered(S,k)&&this.lastVideoAppendEnd<k&&this.blockAudio(_):this.blockAudio(_)}}var M=(l||o).start,O={label:"append-"+n,execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=i.tracks[n])?void 0:e.buffer;t&&(y?i.updateTimestampOffset(t,M,.1,n,c,f):void 0!==u&&T(u)&&i.updateTimestampOffset(t,u,1e-6,n,c,f)),i.appendExecutor(s,n)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===p.first&&(p.first=e),v&&0===v.first&&(v.first=e);var t={};i.sourceBuffers.forEach((function(e){var i=e[0],r=e[1];i&&(t[i]=jt.getBuffered(r))})),i.appendErrors[n]=0,"audio"===n||"video"===n?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(I.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:t})},onError:function(e){var t,r={type:b.MEDIA_ERROR,parent:o.type,details:A.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1},s=null==(t=i.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)r.details=A.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&i.mediaSourceOpenOrEnded&&!s)r.errorAction=It(!0);else if(e.name===en&&0===i.sourceBufferCount)r.errorAction=It(!0);else{var a=++i.appendErrors[n];i.warn("Failed "+a+"/"+i.hls.config.appendErrorMaxRetry+' times to append segment in "'+n+'" sourceBuffer ('+(s||"no media error")+")"),(a>=i.hls.config.appendErrorMaxRetry||s)&&(r.fatal=!0)}i.hls.trigger(I.ERROR,r)}};this.log('queuing "'+n+'" append sn: '+c+(l?" p: "+l.index:"")+" of "+(o.type===w?"level":"track")+" "+o.level+" cc: "+f),this.append(O,n,this.isPending(this.tracks[n]))},i.getFlushOp=function(e,t,i){var r=this;return this.log('queuing "'+e+'" remove '+t+"-"+i),{label:"remove",execute:function(){r.removeExecutor(e,t,i)},onStart:function(){},onComplete:function(){r.hls.trigger(I.BUFFER_FLUSHED,{type:e})},onError:function(s){r.warn("Failed to remove "+t+"-"+i+' from "'+e+'" SourceBuffer',s)}}},i.onBufferFlushing=function(e,t){var i=this,r=t.type,s=t.startOffset,n=t.endOffset;r?this.append(this.getFlushOp(r,s,n),r):this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.append(i.getFlushOp(t,s,n),t)}))},i.onFragParsed=function(e,t){var i=this,r=t.frag,s=t.part,n=[],a=s?s.elementaryStreams:r.elementaryStreams;a[J]?n.push("audiovideo"):(a[X]&&n.push("audio"),a[Q]&&n.push("video")),0===n.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+r.type+" level: "+r.level+" sn: "+r.sn),this.blockBuffers((function(){var e=self.performance.now();r.stats.buffering.end=e,s&&(s.stats.buffering.end=e);var t=s?s.stats:r.stats;i.hls.trigger(I.FRAG_BUFFERED,{frag:r,part:s,stats:t,id:r.type})}),n).catch((function(e){i.warn("Fragment buffered callback "+e),i.stepOperationQueue(i.sourceBufferTypes)}))},i.onFragChanged=function(e,t){this.trimBuffers()},i.onBufferEos=function(e,t){var i,r=this;this.sourceBuffers.forEach((function(e){var i=e[0];if(i){var s=r.tracks[i];t.type&&t.type!==i||(s.ending=!0,s.ended||(s.ended=!0,r.log(i+" buffer reached EOS")))}}));var s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,i=e[0];return i&&!(null!=(t=r.tracks[i])&&t.ended)}))?s?(this.log("Queueing EOS"),this.blockUntilOpen((function(){r.tracksEnded();var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream(),r.hls.trigger(I.BUFFERED_TO_END,void 0)):e&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(I.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()},i.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];if(null!==i){var r=e.tracks[i];r&&(r.ending=!1)}}))},i.onLevelUpdated=function(e,t){var i=t.details;i.fragments.length&&(this.details=i,this.updateDuration())},i.updateDuration=function(){var e=this;this.blockUntilOpen((function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)}))},i.onError=function(e,t){if(t.details===A.BUFFER_APPEND_ERROR&&t.frag){var i,r=null==(i=t.errorAction)?void 0:i.nextAutoLevel;T(r)&&r!==t.frag.level&&this.resetAppendErrors()}},i.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},i.trimBuffers=function(){var e=this.hls,t=this.details,i=this.media;if(i&&null!==t&&this.sourceBufferCount){var r=e.config,s=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(T(a)&&a>=0){var o=Math.max(a,n),l=Math.floor(s/n)*n-o;this.flushBackBuffer(s,n,l)}var h=r.frontBufferFlushThreshold;if(T(h)&&h>0){var u=Math.max(r.maxBufferLength,h),d=Math.max(u,n),c=Math.floor(s/n)*n+d;this.flushFrontBuffer(s,n,c)}}},i.flushBackBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(e){var t=e[0],s=e[1];if(s){var n=jt.getBuffered(s);if(n.length>0&&i>n.start(0)){var a;r.hls.trigger(I.BACK_BUFFER_REACHED,{bufferEnd:i});var o=r.tracks[t];if(null!=(a=r.details)&&a.live)r.hls.trigger(I.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=o&&o.ended)return void r.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");r.hls.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}}))},i.flushFrontBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(t){var s=t[0],n=t[1];if(n){var a=jt.getBuffered(n),o=a.length;if(o<2)return;var l=a.start(o-1),h=a.end(o-1);if(i>l||e>=l&&e<=h)return;r.hls.trigger(I.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}}))},i.getDurationAndRange=function(){var e,t=this.details,i=this.mediaSource;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;var r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){var s=Math.max(0,t.fragmentStart);return{duration:1/0,start:s,end:Math.max(s,r)}}return{duration:1/0}}var n=null==(e=this.overrides)?void 0:e.duration;if(n)return T(n)?{duration:n}:null;var a=this.media.duration;return r>(T(i.duration)?i.duration:0)&&r>a||!T(a)?{duration:r}:null},i.updateMediaSource=function(e){var t=e.duration,i=e.start,r=e.end,s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==t&&(T(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),s.duration=t),void 0!==i&&void 0!==r&&(this.log("MediaSource duration is set to "+s.duration+". Setting seekable range to "+i+"-"+r+"."),s.setLiveSeekableRange(i,r)))},i.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,i=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+it(i)),this.tracksReady){var r,s=null==(r=this.transferData)?void 0:r.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}},i.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(i){var r=i[0],s=i[1];if(r){var n=e.tracks[r];t[r]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}})),this.hls.trigger(I.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var i=t[0];e.executeNext(i)}))}else{var i=new Error("could not create source buffer for media codec(s)");this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:i,reason:i.message})}},i.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,i=this.mediaSource;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(var r in e){var s=r,n=e[s];if(this.isPending(n)){var a=this.getTrackCodec(n,s),o=n.container+";codecs="+a;n.codec=a,this.log("creating sourceBuffer("+o+")"+(this.currentOp(s)?" Queued":"")+" "+it(n));try{var l=i.addSourceBuffer(o),h=nn(s),u=[s,l];t[h]=u,n.buffer=l}catch(e){var d;return this.error("error while trying to add sourceBuffer: "+e.message),this.shiftAndExecuteNext(s),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[s],void this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:o,parent:n.id})}this.trackSourceBuffer(s,n)}}this.bufferCreated()},i.getTrackCodec=function(e,t){var i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&we(i,"video")&&(r=function(e,t){var i=[];if(e)for(var r=e.split(","),s=0;s<r.length;s++)De(r[s],"video")||i.push(r[s]);return t&&i.push(t),i.join(",")}(r,i));var s=Ue(r,e.levelCodec);return s?"audio"===t.slice(0,5)?Be(s,this.appendSource):s:""},i.trackSourceBuffer=function(e,t){var i=this,r=t.buffer;if(r){var s=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(function(e,t){var r=t.removedRanges;null!=r&&r.length&&i.hls.trigger(I.BUFFER_FLUSHED,{type:e})}))}},i.onSBUpdateStart=function(e){var t=this.currentOp(e);t&&t.onStart()},i.onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)},i.onSBUpdateError=function(e,t){var i,r=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(i=this.mediaSource)?void 0:i.readyState));this.error(""+r,t),this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});var s=this.currentOp(e);s&&s.onError(r)},i.updateTimestampOffset=function(e,t,i,r,s,n){var a=t-e.timestampOffset;Math.abs(a)>=i&&(this.log("Updating "+r+" SourceBuffer timestampOffset to "+t+" (sn: "+s+" cc: "+n+")"),e.timestampOffset=t)},i.removeExecutor=function(e,t,i){var r=this.media,s=this.mediaSource,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!r||!s||!a)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(e);var o=T(r.duration)?r.duration:1/0,l=T(s.duration)?s.duration:1/0,h=Math.max(0,t),u=Math.min(i,o,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log("Removing ["+h+","+u+"] from the "+e+" SourceBuffer"),a.remove(h,u)):this.shiftAndExecuteNext(e)},i.appendExecutor=function(e,t){var i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new tn("Attempting to append to the "+t+" SourceBuffer, but it does not exist");i.ending=!1,i.ended=!1,r.appendBuffer(e)},i.blockUntilOpen=function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((function(e){t.warn("SourceBuffer blocked callback "+e),t.stepOperationQueue(t.sourceBufferTypes)}));else try{e()}catch(e){this.warn("Callback run without blocking "+this.operationQueue+" "+e)}},i.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],i=e[1];return t&&i.updating}))},i.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var i=t[0];return i&&!!e.currentOp(i)}))},i.isPending=function(e){return!!e&&!e.buffer},i.blockBuffers=function(e,t){var i=this;if(void 0===t&&(t=this.sourceBufferTypes),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var r=this.operationQueue,s=t.map((function(e){return i.appendBlocker(e)}));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then((function(t){r===i.operationQueue&&(e(),i.stepOperationQueue(i.sourceBufferTypes))}))},i.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var i,r=null==(i=t.tracks[e])?void 0:i.buffer;r&&!r.updating&&t.shiftAndExecuteNext(e)}))},i.append=function(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)},i.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},i.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},i.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},i.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},i.addBufferListener=function(e,t,i){var r=this.tracks[e];if(r){var s=r.buffer;if(s){var n=i.bind(this,e);r.listeners.push({event:t,listener:n}),s.addEventListener(t,n)}}},i.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var i=t.buffer;i&&(t.listeners.forEach((function(e){i.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},r(t,[{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){var r=e.tracks[i];return t[i]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var i=t[0];if(i){var r=e.tracks[i];if(r)return!r.ended||r.ending}return!1}))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"mediaSrc",get:function(){var e,t,i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){return t+(e.isPending(e.tracks[i])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(e,t){return e+(t[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(e){return e[0]})).filter((function(e){return!!e}))}}])}(F);function sn(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function nn(e){return"audio"===e?1:0}var an=function(){function e(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},t.registerListeners=function(){var e=this.hls;e.on(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.BUFFER_CODECS,this.onBufferCodecs,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListener=function(){var e=this.hls;e.off(I.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)},t.onFpsDropLevelCapping=function(e,t){var i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})},t.onMediaAttaching=function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},t.onManifestParsed=function(e,t){var i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&T(this.autoLevelCapping)&&this.detectPlayerSize()},t.onBufferCodecs=function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping(),this.media=null},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+i+": "+e[i].height+"p@"+e[i].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var i=this,r=this.hls.levels;if(!r.length)return-1;var s=r.filter((function(e,r){return i.isLevelAllowed(e)&&r<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)},t.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var 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},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,i){if(null==e||!e.length)return-1;for(var r,s,n=e.length-1,a=Math.max(t,i),o=0;o<e.length;o+=1){var l=e[o];if((l.width>=a||l.height>=a)&&(r=l,!(s=e[o+1])||r.width!==s.width||r.height!==s.height)){n=o;break}}return n},r(e,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}}])}(),on="m",ln="a",hn="v",un="av",dn="i",cn="tt",fn="h",gn=function e(t,i){Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=i},pn="Dict";function vn(e,t,i){return function(e,t,i,r){return new Error("failed to "+e+' "'+(s=t,(Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s))+'" as ')+i,{cause:r});var s}("serialize",e,t,i)}var mn=function(e){this.description=e},yn="Bare Item",En="Boolean",Sn="Byte Sequence";var Tn="Integer";function _n(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw vn(e,Tn);return e.toString()}function Ln(e,t){if(e<0)return-Ln(-e,t);var i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){var r=Math.floor(e*i);return(r%2==0?r:r+1)/i}return Math.round(e*i)/i}var bn="Decimal";function An(e){var t=Ln(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw vn(e,bn);var i=t.toString();return i.includes(".")?i:i+".0"}var In="String",Rn=/[\x00-\x1f\x7f]+/,Pn="Token";function kn(e){var t,i=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw vn(i,Pn);return i}function Dn(e){switch(typeof e){case"number":if(!T(e))throw vn(e,yn);return Number.isInteger(e)?_n(e):An(e);case"string":return function(e){if(Rn.test(e))throw vn(e,In);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(e);case"symbol":return kn(e);case"boolean":return function(e){if("boolean"!=typeof e)throw vn(e,En);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@"+_n(e.getTime()/1e3)}(e);if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw vn(e,Sn);return":"+(t=e,btoa(String.fromCharCode.apply(String,t))+":");var t}(e);if(e instanceof mn)return kn(e);default:throw vn(e,yn)}}var wn="Key";function Cn(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw vn(e,wn);return e}function Mn(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],i=e[1];return!0===i?";"+Cn(t):";"+Cn(t)+"="+Dn(i)})).join("")}function On(e){return e instanceof gn?""+Dn(e.value)+Mn(e.params):Dn(e)}function xn(e,t){return function(e,t){if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e||null==e)throw vn(e,pn);var i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map((function(e){var t=e[0],i=e[1];i instanceof gn==0&&(i=new gn(i));var r,s=Cn(t);return!0===i.value?s+=Mn(i.params):(s+="=",Array.isArray(i.value)?s+="("+(r=i).value.map(On).join(" ")+")"+Mn(r.params):s+=On(i)),s})).join(","+r)}(e,t)}var Fn="CMCD-Object",Nn="CMCD-Request",Bn="CMCD-Session",Un="CMCD-Status",Gn={br:Fn,ab:Fn,d:Fn,ot:Fn,tb:Fn,tpb:Fn,lb:Fn,tab:Fn,lab:Fn,url:Fn,pb:Nn,bl:Nn,tbl:Nn,dl:Nn,ltc:Nn,mtp:Nn,nor:Nn,nrr:Nn,rc:Nn,sn:Nn,sta:Nn,su:Nn,ttfb:Nn,ttfbb:Nn,ttlb:Nn,cmsdd:Nn,cmsds:Nn,smrt:Nn,df:Nn,cs:Nn,ts:Nn,cid:Bn,pr:Bn,sf:Bn,sid:Bn,st:Bn,v:Bn,msd:Bn,bs:Un,bsd:Un,cdn:Un,rtp:Un,bg:Un,pt:Un,ec:Un,e:Un},Hn={REQUEST:Nn};var Kn="event",Vn=function(e){return Math.round(e)},$n=function(e,t){return Array.isArray(e)?e.map((function(e){return $n(e,t)})):e instanceof gn&&"string"==typeof e.value?new gn($n(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;for(var s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e)},Wn=function(e){return 100*Vn(e/100)},qn={br:Vn,d:Vn,bl:Wn,dl:Wn,mtp:Wn,nor:function(e,t){var i=e;return t.version>=2&&(e instanceof gn&&"string"==typeof e.value?i=new gn([e]):"string"==typeof e&&(i=[e])),$n(i,t)},rtp:Wn,tb:Vn},jn="request",Yn="response",zn=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Xn=["e"],Qn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Jn(e){return Qn.test(e)}var Zn,ea=["d","dl","nor","ot","rtp","su"],ta=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],ia=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ra(e){return ia.includes(e)||Jn(e)}var sa=((Zn={})[Yn]=function(e){return zn.includes(e)||ea.includes(e)||ta.includes(e)||Jn(e)},Zn[Kn]=function(e){return zn.includes(e)||Xn.includes(e)||Jn(e)},Zn[jn]=function(e){return zn.includes(e)||ea.includes(e)||Jn(e)},Zn);function na(e,t){void 0===t&&(t={});var i={};if(null==e||"object"!=typeof e)return i;var r=t.version||e.v||1,s=t.reportingMode||jn,a=1===r?ra:sa[s],o=Object.keys(e).filter(a),l=t.filter;"function"==typeof l&&(o=o.filter(l));var h=s===Yn||s===Kn;h&&!o.includes("ts")&&o.push("ts"),r>1&&!o.includes("v")&&o.push("v");var u=n({},qn,t.formatters),d={version:r,reportingMode:s,baseUrl:t.baseUrl};return o.sort().forEach((function(t){var s=e[t],n=u[t];if("function"==typeof n&&(s=n(s,d)),"v"===t){if(1===r)return;s=r}"pr"==t&&1===s||(h&&"ts"===t&&!T(s)&&(s=Date.now()),function(e){return"number"==typeof e?T(e):null!=e&&""!==e&&!1!==e}(s)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof s&&(s=new mn(s)),i[t]=s))})),i}function aa(e,t,i){return n(e,function(e,t){void 0===t&&(t={});var i={};if(!e)return i;var r=function(e,t){var i={};if(!e)return i;var r,s=Object.keys(e),n=t?(r=t,Object.keys(r).reduce((function(e,t){var i;return null===(i=r[t])||void 0===i||i.forEach((function(i){return e[i]=t})),e}),{})):{};return s.reduce((function(t,i){var r,s=Gn[i]||n[i]||Hn.REQUEST;return(null!==(r=t[s])&&void 0!==r?r:t[s]={})[i]=e[i],t}),i)}(na(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(r).reduce((function(e,t){var i=t[0],r=xn(t[1],{whitespace:!1});return r&&(e[i]=r),e}),i)}(t,i))}var oa=/CMCD=[^&#]+/;function la(e,t,i){var r=function(e,t){if(void 0===t&&(t={}),!e)return"";var i=function(e,t){if(void 0===t&&(t={}),!e)return"";var i=function(e,t){return void 0===t&&(t={}),e?xn(na(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(i)}(e,t);return"CMCD="+i}(t,i);if(!r)return e;if(oa.test(e))return e.replace(oa,r);var s=e.includes("?")?"&":"?";return""+e+s+r}var ha=function(){function e(e){var t=this;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=function(){t.initialized&&(t.starved=!0),t.buffering=!0},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1},this.applyPlaylistData=function(e){try{t.apply(e,{ot:on,su:!t.initialized})}catch(e){t.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var i=e.frag,r=e.part,s=t.hls.levels[i.level],n=t.getObjectType(i),a={d:1e3*(r||i).duration,ot:n};n!==hn&&n!==ln&&n!=un||(a.br=s.bitrate/1e3,a.tb=t.getTopBandwidth(n)/1e3,a.bl=t.getBufferLength(n));var o=r?t.getNextPart(r):t.getNextFrag(i);null!=o&&o.url&&o.url!==i.url&&(a.nor=o.url),t.apply(e,a)}catch(e){t.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;var i=this.config=e.config,r=i.cmcd;null!=r&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHED,this.onMediaDetached,this),e.on(I.BUFFER_CREATED,this.onBufferCreated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHED,this.onMediaDetached,this),e.off(I.BUFFER_CREATED,this.onBufferCreated,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},t.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},t.onBufferCreated=function(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer},t.createData=function(){var e;return{v:1,sf:fn,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},t.apply=function(e,t){void 0===t&&(t={}),n(t,this.createData());var i=t.ot===dn||t.ot===hn||t.ot===un;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var r=this.includeKeys;r&&(t=Object.keys(t).reduce((function(e,i){return r.includes(i)&&(e[i]=t[i]),e}),{}));var s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),aa(e.headers,t,s)):e.url=la(e.url,t,s)},t.getNextFrag=function(e){var t,i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){var r=e.sn-i.startSN;return i.fragments[r+1]}},t.getNextPart=function(e){var t,i=e.index,r=e.fragment,s=null==(t=this.hls.levels[r.level])||null==(t=t.details)?void 0:t.partList;if(s)for(var n=r.sn,a=s.length-1;a>=0;a--){var o=s[a];if(o.index===i&&o.fragment.sn===n)return s[a+1]}},t.getObjectType=function(e){var t=e.type;return"subtitle"===t?cn:"initSegment"===e.sn?dn:"audio"===t?ln:"main"===t?this.hls.audioTracks.length?hn:un:void 0},t.getTopBandwidth=function(e){var t,i=0,r=this.hls;if(e===ln)t=r.audioTracks;else{var s=r.maxAutoLevel,n=s>-1?s+1:r.levels.length;t=r.levels.slice(0,n)}return t.forEach((function(e){e.bitrate>i&&(i=e.bitrate)})),i>0?i:NaN},t.getBufferLength=function(e){var t=this.media,i=e===ln?this.audioBuffer:this.videoBuffer;return i&&t?1e3*jt.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var s=e.prototype;return s.destroy=function(){this.loader.destroy()},s.abort=function(){this.loader.abort()},s.load=function(e,i,r){t(e),this.loader.load(e,i,r)},r(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var s=e.prototype;return s.destroy=function(){this.loader.destroy()},s.abort=function(){this.loader.abort()},s.load=function(e,i,r){t(e),this.loader.load(e,i,r)},r(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},e}(),ua=function(e){function t(t){var i;return(i=e.call(this,"content-steering",t.logger)||this).hls=void 0,i.loader=null,i.uri=null,i.pathwayId=".",i._pathwayPriority=null,i.timeToLoad=300,i.reloadTimer=-1,i.updated=0,i.started=!1,i.enabled=!0,i.levels=null,i.audioTracks=null,i.subtitleTracks=null,i.penalizedPathways={},i.hls=t,i.registerListeners(),i}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.ERROR,this.onError,this))},i.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},i.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},i.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},i.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},i.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},i.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},i.onManifestLoaded=function(e,t){var i=t.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())},i.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},i.onError=function(e,t){var i=t.errorAction;if(2===(null==i?void 0:i.action)&&1===i.flags){var r=this.levels,s=this._pathwayPriority,n=this.pathwayId;if(t.context){var a=t.context,o=a.groupId,l=a.pathwayId,h=a.type;o&&r?n=this.getPathwayForGroupId(o,h,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&r&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n),t.details!==A.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+n+" levels: "+(r?r.length:r)+" priorities: "+it(s)+" penalized: "+it(this.penalizedPathways)):i.resolved=!0}},i.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var 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},i.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},i.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((function(e){r-i[e]>3e5&&delete i[e]}));for(var s=0;s<e.length;s++){var n=e[s];if(!(n in i)){if(n===this.pathwayId)return;var a=this.hls.nextLoadLevel,o=this.hls.levels[a];if((t=this.getLevelsForPathway(n)).length>0){this.log('Setting Pathway to "'+n+'"'),this.pathwayId=n,Ji(t),this.hls.trigger(I.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[a];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=a);break}}}},i.getPathwayForGroupId=function(e,t,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),s=0;s<r.length;s++)if(t===k&&r[s].hasAudioGroup(e)||t===D&&r[s].hasSubtitleGroup(e))return r[s].pathwayId;return i},i.clonePathways=function(e){var t=this,i=this.levels;if(i){var r={},s={};e.forEach((function(e){var n=e.ID,a=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!i.some((function(e){return e.pathwayId===n}))){var l=t.getLevelsForPathway(a).map((function(e){var t=new ti(e.attrs);t["PATHWAY-ID"]=n;var i=t.AUDIO&&t.AUDIO+"_clone_"+n,a=t.SUBTITLES&&t.SUBTITLES+"_clone_"+n;i&&(r[t.AUDIO]=i,t.AUDIO=i),a&&(s[t.SUBTITLES]=a,t.SUBTITLES=a);var l=ca(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new et({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var u=1;u<e.audioGroups.length;u++)h.addGroupId("audio",e.audioGroups[u]+"_clone_"+n);if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)h.addGroupId("text",e.subtitleGroups[d]+"_clone_"+n);return h}));i.push.apply(i,l),da(t.audioTracks,r,o,n),da(t.subtitleTracks,s,o,n)}}))}},i.loadSteeringManifest=function(e){var t,i=this,r=this.hls.config,s=r.loader;this.loader&&this.loader.destroy(),this.loader=new s(r);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+e)}if("data:"!==t.protocol){var n=0|(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+n)}var a={responseType:"json",url:t.href},o=r.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},u={onSuccess:function(e,r,s,n){i.log('Loaded steering manifest: "'+t+'"');var a=e.data;if(1===(null==a?void 0:a.VERSION)){i.updated=performance.now(),i.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,t).href}catch(e){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}i.scheduleRefresh(i.uri||s.url),l&&i.clonePathways(l);var u={steeringManifest:a,url:t.toString()};i.hls.trigger(I.STEERING_MANIFEST_LOADED,u),h&&i.updatePathwayPriority(h)}else i.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(e,t,r,s){if(i.log("Error loading steering manifest: "+e.code+" "+e.text+" ("+t.url+")"),i.stopLoad(),410===e.code)return i.enabled=!1,void i.log("Steering manifest "+t.url+" no longer available");var n=1e3*i.timeToLoad;if(429!==e.code)i.scheduleRefresh(i.uri||t.url,n);else{var a=i.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(n=1e3*parseFloat(o))}i.log("Steering manifest "+t.url+" rate limited")}},onTimeout:function(e,t,r){i.log("Timeout loading steering manifest ("+t.url+")"),i.scheduleRefresh(i.uri||t.url)}};this.log("Requesting steering manifest: "+t),this.loader.load(a,h,u)},i.scheduleRefresh=function(e,t){var i=this;void 0===t&&(t=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var t,r=null==(t=i.hls)?void 0:t.media;!r||r.ended?i.scheduleRefresh(e,1e3*i.timeToLoad):i.loadSteeringManifest(e)}),t)},r(t,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}}])}(F);function da(e,t,i,r){e&&Object.keys(t).forEach((function(s){var a=e.filter((function(e){return e.groupId===s})).map((function(e){var a=n({},e);return a.details=void 0,a.attrs=new ti(a.attrs),a.url=a.attrs.URI=ca(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=r,a}));e.push.apply(e,a)}))}function ca(e,t,i,r){var s,n=r.HOST,a=r.PARAMS,o=r[i];t&&(s=null==o?void 0:o[t])&&(e=s);var l=new self.URL(e);return n&&!s&&(l.host=n),a&&Object.keys(a).sort().forEach((function(e){e&&l.searchParams.set(e,a[e])})),l.href}var fa=function(e){function t(i){var r;return(r=e.call(this,"eme",i.logger)||this).hls=void 0,r.config=void 0,r.media=null,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.mediaKeys=null,r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.bannedKeyIds={},r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,s='"'+e.type+'" event: init data type: "'+t+'"';if(r.debug(s),null!==i){if(!r.keyFormatPromise){var n=Object.keys(r.keySystemAccessPromises);n.length||(n=Si(r.config));var a=n.map(Ei).filter((function(e){return!!e}));r.keyFormatPromise=r.getKeyFormatPromise(a)}r.keyFormatPromise.then((function(n){var a=yi(n);if("sinf"===t&&a===fi.FAIRPLAY){var o;try{var l=oe(new Uint8Array(i)),h=Se(hi(JSON.parse(l).sinf));if(!h)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(h.subarray(8,24))}catch(e){return void r.warn(s+" Failed to parse sinf: "+e)}for(var u,d=j(o),c=r,f=c.keyIdToKeySessionPromise,g=c.mediaKeySessions,p=f[d],v=function(){var e=g[m],s=e.decryptdata;if(!s.keyId)return 0;var n=j(s.keyId);return ni(o,s.keyId)||-1!==s.uri.replace(/-/g,"").indexOf(d)?(p=f[n])?(s.pssh||(delete f[n],s.pssh=new Uint8Array(i),s.keyId=o,(p=f[d]=p.then((function(){return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-key-match")}))).catch((function(e){return r.handleError(e)}))),1):0:void 0},m=0;m<g.length&&(0===(u=v())||1!==u);m++);p||r.handleError(new Error("Key ID "+d+" not encountered in playlist. Key-system sessions "+g.length+"."))}else r.log('Ignoring "'+e.type+'" event with init data type: "'+t+'" for selected key-system '+a)})).catch((function(e){return r.handleError(e)}))}},r.onWaitingForKey=function(e){r.log('"'+e.type+'" event')},r.hls=i,r.config=i.config,r.registerListeners(),r}o(t,e);var i=t.prototype;return i.destroy=function(){this.onDestroying(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null},i.registerListeners=function(){this.hls.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(I.DESTROYING,this.onDestroying,this)},i.unregisterListeners=function(){this.hls.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(I.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(I.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(I.DESTROYING,this.onDestroying,this)},i.getLicenseServerUrl=function(e){var t=this.config,i=t.drmSystems,r=t.widevineLicenseUrl,s=null==i?void 0:i[e];return s?s.licenseUrl:e===fi.WIDEVINE&&r?r:void 0},i.getLicenseServerUrlOrThrow=function(e){var t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error('no license server URL configured for key-system "'+e+'"');return t},i.getServerCertificateUrl=function(e){var t=this.config.drmSystems,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+e+'"]')},i.attemptKeySystemAccess=function(e){var t=this,i=this.hls.levels,r=function(e,t,i){return!!e&&i.indexOf(e)===t},s=i.map((function(e){return e.audioCodec})).filter(r),n=i.map((function(e){return e.videoCodec})).filter(r);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((function(i,r){var a=function(e){var o=e.shift();t.getMediaKeysPromise(o,s,n).then((function(e){return i({keySystem:o,mediaKeys:e})})).catch((function(t){e.length?a(e):r(t instanceof va?t:new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};a(e)}))},i.requestMediaKeySystemAccess=function(e,t){var i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function "+i;return null===_i&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(r))}return i(e,t)},i.getMediaKeysPromise=function(e,t,i){var r,s=this,n=function(e,t,i,r){var s;switch(e){case fi.FAIRPLAY:s=["cenc","sinf"];break;case fi.WIDEVINE:case fi.PLAYREADY:s=["cenc"];break;case fi.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+e)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((function(e){return{contentType:"audio/mp4; codecs="+e,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}})),videoCapabilities:i.map((function(e){return{contentType:"video/mp4; codecs="+e,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}}))}]}(s,t,i,r)}(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=null==(r=a)?void 0:r.keySystemAccess;if(!o){this.log('Requesting encrypted media "'+e+'" key-system access with config: '+it(n)),o=this.requestMediaKeySystemAccess(e,n);var l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch((function(t){s.log('Failed to obtain access to key-system "'+e+'": '+t)})),o.then((function(t){s.log('Access for key-system "'+t.keySystem+'" obtained');var i=s.fetchServerCertificate(e);s.log('Create media-keys for "'+e+'"');var r=l.mediaKeys=t.createMediaKeys().then((function(t){return s.log('Media-keys created for "'+e+'"'),l.hasMediaKeys=!0,i.then((function(i){return i?s.setMediaKeysServerCertificate(t,e,i):t}))}));return r.catch((function(t){s.error('Failed to create media-keys for "'+e+'"}: '+t)})),r}))}return o.then((function(){return a.mediaKeys}))},i.createMediaKeySessionContext=function(e){var t=e.decryptdata,i=e.keySystem,r=e.mediaKeys;this.log('Creating key-system session "'+i+'" keyId: '+j(t.keyId||[])+" keyUri: "+t.uri);var s=r.createSession(),n={decryptdata:t,keySystem:i,mediaKeys:r,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n},i.renewKeySession=function(e){var t=e.decryptdata;if(t.pssh){var i=this.createMediaKeySessionContext(e),r=ga(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)},i.updateKeySession=function(e,t){var i=e.mediaKeysSession;return this.log('Updating key-session "'+i.sessionId+'" for keyId '+j(e.decryptdata.keyId||[])+"\n } (data length: "+t.byteLength+")"),i.update(t)},i.getSelectedKeySystemFormats=function(){var e=this;return Object.keys(this.keySystemAccessPromises).map((function(t){return{keySystem:t,hasMediaKeys:e.keySystemAccessPromises[t].hasMediaKeys}})).filter((function(e){return!!e.hasMediaKeys})).map((function(e){return Ei(e.keySystem)})).filter((function(e){return!!e}))},i.getKeySystemAccess=function(e){var t=this;return this.getKeySystemSelectionPromise(e).then((function(e){var i=e.keySystem,r=e.mediaKeys;return t.attemptSetMediaKeys(i,r)}))},i.selectKeySystem=function(e){var t=this;return new Promise((function(i,r){t.getKeySystemSelectionPromise(e).then((function(e){var t=e.keySystem,s=Ei(t);s?i(s):r(new Error('Unable to find format for key-system "'+t+'"'))})).catch(r)}))},i.selectKeySystemFormat=function(e){var 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},i.getKeyFormatPromise=function(e){var t=Si(this.config),i=e.map(yi).filter((function(e){return!!e&&-1!==t.indexOf(e)}));return this.selectKeySystem(i)},i.getKeyStatus=function(e){for(var t=this.mediaKeySessions,i=0;i<t.length;i++){var r=pa(e,t[i]);if(r)return r}},i.loadKey=function(e){var t=this,i=e.keyInfo.decryptdata,r=ga(i),s=this.bannedKeyIds[r];if(s||"internal-error"===this.getKeyStatus(i)){var n=ma(s||"internal-error",i);return this.handleError(n,e.frag),Promise.reject(n)}var a="(keyId: "+r+' format: "'+i.keyFormat+'" method: '+i.method+" uri: "+i.uri+")";this.log("Starting session for key "+a);var o=this.keyIdToKeySessionPromise[r];if(!o){var l=this.getKeySystemForKeyPromise(i).then((function(r){var s=r.keySystem,n=r.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: "+e.frag.sn+" "+e.frag.type+": "+e.frag.level+" using key "+a),t.attemptSetMediaKeys(s,n).then((function(){return t.throwIfDestroyed(),t.createMediaKeySessionContext({keySystem:s,mediaKeys:n,decryptdata:i})}))})).then((function(e){var r=i.pssh?i.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",r,"playlist-key")}));return l.catch((function(i){return t.handleError(i,e.frag)})),this.keyIdToKeySessionPromise[r]=l,l}return o.catch((function(r){if(r instanceof va){var s=u({},r.data);"internal-error"===t.getKeyStatus(i)&&(s.decryptdata=i);var n=new va(s,r.message);t.handleError(n,e.frag)}})),o},i.throwIfDestroyed=function(e){if(!this.hls)throw new Error("invalid state")},i.handleError=function(e,t){if(this.hls)if(e instanceof va){t&&(e.data.frag=t);var i=e.data.decryptdata;this.error(e.message+(i?" ("+j(i.keyId||[])+")":"")),this.hls.trigger(I.ERROR,e.data)}else this.error(e.message),this.hls.trigger(I.ERROR,{type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})},i.getKeySystemForKeyPromise=function(e){var t=ga(e),i=this.keyIdToKeySessionPromise[t];if(!i){var r=yi(e.keyFormat),s=r?[r]:Si(this.config);return this.attemptKeySystemAccess(s)}return i},i.getKeySystemSelectionPromise=function(e){if(e.length||(e=Si(this.config)),0===e.length)throw new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+it({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(e)},i.attemptSetMediaKeys=function(e,t){var i=this;if(this.mediaKeys===t)return Promise.resolve();var r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+e+'"');var s=Promise.all(r).then((function(){if(!i.media)throw i.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return i.media.setMediaKeys(t)}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then((function(){i.log('Media-keys set for "'+e+'"'),r.push(s),i.setMediaKeysQueue=i.setMediaKeysQueue.filter((function(e){return-1===r.indexOf(e)}))}))},i.generateRequestWithPreferredKeySession=function(e,t,i,r){var s,n=this,a=null==(s=this.config.drmSystems)||null==(s=s[e.keySystem])?void 0:s.generateRequest;if(a)try{var o=a.call(this.hls,t,i,e);if(!o)throw new Error("Invalid response from configured generateRequest filter");t=o.initDataType,i=o.initData?o.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log('Skipping key-session request for "'+r+'" (no initData)'),Promise.resolve(e);var l=ga(e.decryptdata),h=e.decryptdata.uri;this.log('Generating key-session request for "'+r+'" keyId: '+l+" URI: "+h+" (init data type: "+t+" length: "+i.byteLength+")");var u=new y,d=e._onmessage=function(t){var i=e.mediaKeysSession;if(i){var r=t.messageType,s=t.message;n.log('"'+r+'" message event for session "'+i.sessionId+'" message size: '+s.byteLength),"license-request"===r||"license-renewal"===r?n.renewLicense(e,s).catch((function(e){u.eventNames().length?u.emit("error",e):n.handleError(e)})):"license-release"===r?e.keySystem===fi.FAIRPLAY&&n.updateKeySession(e,ui("acknowledged")).then((function(){return n.removeSession(e)})).catch((function(e){return n.handleError(e)})):n.warn('unhandled media key message type "'+r+'"')}else u.emit("error",new Error("invalid state"))},c=function(e,t){var i;t.keyStatus=e,e.startsWith("usable")?u.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=ma(e,t.decryptdata):"expired"===e?i=new Error("key expired (keyId: "+l+")"):"released"===e?i=new Error("key released"):"status-pending"===e||n.warn('unhandled key status change "'+e+'" (keyId: '+l+")"),i&&(u.eventNames().length?u.emit("error",i):n.handleError(i))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){var i=n.getKeyStatuses(e);if(Object.keys(i).some((function(e){return"status-pending"!==i[e]}))){if("expired"===i[l])return n.log("Expired key "+it(i)+' in key-session "'+e.mediaKeysSession.sessionId+'"'),void n.renewKeySession(e);var r,s=i[l];s?c(s,e):(e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(r=e.keyStatusTimeouts)[l]||(r[l]=self.setTimeout((function(){if(e.mediaKeysSession&&n.mediaKeys){var t=n.getKeyStatus(e.decryptdata);if(t&&"status-pending"!==t)return n.log("No status for keyId "+l+' in key-session "'+e.mediaKeysSession.sessionId+'". Using session key-status '+t+" from other session."),c(t,e);n.log("key status for "+l+' in key-session "'+e.mediaKeysSession.sessionId+'" timed out after 0ms'),c(s="internal-error",e)}}),0)),n.log("No status for keyId "+l+" ("+it(i)+")."))}}else u.emit("error",new Error("invalid state"))};ar(e.mediaKeysSession,"message",d),ar(e.mediaKeysSession,"keystatuseschange",f);var g=new Promise((function(e,t){u.on("error",t),u.on("resolved",e)}));return e.mediaKeysSession.generateRequest(t,i).then((function(){n.log('Request generated for key-session "'+e.mediaKeysSession.sessionId+'" keyId: '+l+" URI: "+h)})).catch((function(t){throw new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},"Error generating key-session request: "+t)})).then((function(){return g})).catch((function(t){return u.removeAllListeners(),n.removeSession(e).then((function(){throw t}))})).then((function(){return u.removeAllListeners(),e}))},i.getKeyStatuses=function(e){var t=this,i={};return e.mediaKeysSession.keyStatuses.forEach((function(r,s){if("string"==typeof s&&"object"==typeof r){var n=s;s=r,r=n}var a="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);e.keySystem===fi.PLAYREADY&&16===a.length&&di(a);var o=j(a);"internal-error"===r&&(t.bannedKeyIds[o]=r),t.log('key status change "'+r+'" for keyStatuses keyId: '+o+' key-session "'+e.mediaKeysSession.sessionId+'"'),i[o]=r})),i},i.fetchServerCertificate=function(e){var t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log('Fetching server certificate for "'+e+'"'),new Promise((function(s,n){var a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(e,t,i,r){s(e.data)},onError:function(t,i,s,o){n(new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:u({url:a.url,data:void 0},t)},'"'+e+'" certificate request failed ('+r+"). Status: "+t.code+" ("+t.text+")"))},onTimeout:function(t,i,s){n(new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},'"'+e+'" certificate request timed out ('+r+")"))},onAbort:function(e,t,i){n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()},i.setMediaKeysServerCertificate=function(e,t,i){var r=this;return new Promise((function(s,n){e.setServerCertificate(i).then((function(n){r.log("setServerCertificate "+(n?"success":"not supported by CDM")+" ("+i.byteLength+') on "'+t+'"'),s(e)})).catch((function(e){n(new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))},i.renewLicense=function(e,t){var i=this;return this.requestLicense(e,new Uint8Array(t)).then((function(t){return i.updateKeySession(e,new Uint8Array(t)).catch((function(t){throw new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}))},i.unpackPlayReadyKeyMessage=function(e,t){var i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0)for(var n,a=0,o=s.length;a<o;a++){var l,h,u=null==(l=(n=s[a]).querySelector("name"))?void 0:l.textContent,d=null==(h=n.querySelector("value"))?void 0:h.textContent;u&&d&&e.setRequestHeader(u,d)}var c=r.querySelector("Challenge"),f=null==c?void 0:c.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return ui(atob(f))},i.setupLicenseXHR=function(e,t,i,r){var s=this,n=this.config.licenseXhrSetup;return n?Promise.resolve().then((function(){if(!i.decryptdata)throw new Error("Key removed");return n.call(s.hls,e,t,i,r)})).catch((function(a){if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(s.hls,e,t,i,r)})).then((function(i){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))},i.requestLicense=function(e,t){var i=this,r=this.config.keyLoadPolicy.default;return new Promise((function(s,n){var a=i.getLicenseServerUrlOrThrow(e.keySystem);i.log("Sending license request to URL: "+a);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var h=i.config.licenseResponseCallback;if(h)try{l=h.call(i.hls,o,a,e)}catch(e){i.error(e)}s(l)}else{var u=r.errorRetry,d=u?u.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new va({type:b.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,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{var c=d-i._requestLicenseFailureCount+1;i.warn("Retrying license request, "+c+" attempts left"),i.requestLicense(e,t).then(s,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,i.setupLicenseXHR(o,a,e,t).then((function(t){var r=t.xhr,s=t.licenseChallenge;e.keySystem==fi.PLAYREADY&&(s=i.unpackPlayReadyKeyMessage(r,s)),r.send(s)})).catch(n)}))},i.onDestroying=function(){this.unregisterListeners(),this._clear()},i.onMediaAttached=function(e,t){if(this.config.emeEnabled){var i=t.media;this.media=i,ar(i,"encrypted",this.onMediaEncrypted),ar(i,"waitingforkey",this.onWaitingForKey)}},i.onMediaDetached=function(){var e=this.media;e&&(or(e,"encrypted",this.onMediaEncrypted),or(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)},i._clear=function(){var e,i=this;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},this.mediaKeys||this.mediaKeySessions.length){var r=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,bi.clearKeyUriToKeyIdMap();var n=s.length;t.CDMCleanupPromise=Promise.all(s.map((function(e){return i.removeSession(e)})).concat((null==r||null==(e=r.setMediaKeys(null))?void 0:e.catch((function(e){i.log("Could not clear media keys: "+e),i.hls&&i.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+e)})})))||Promise.resolve())).catch((function(e){i.log("Could not close sessions and clear media keys: "+e),i.hls&&i.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+e)})})).then((function(){n&&i.log("finished closing key sessions and clearing media keys")}))}},i.onManifestLoading=function(){this.keyFormatPromise=null,this.bannedKeyIds={}},i.onManifestLoaded=function(e,t){var i=t.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+r.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(r)}},i.removeSession=function(e){var t=this,i=e.mediaKeysSession,r=e.licenseXhr,s=e.decryptdata;if(i){this.log('Remove licenses and keys and close session "'+i.sessionId+'" keyId: '+j((null==s?void 0:s.keyId)||[])),e._onmessage&&(i.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);var a=e.keyStatusTimeouts;a&&Object.keys(a).forEach((function(e){return self.clearTimeout(a[e])}));var o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some((function(e){return"persistent-license"===e}))))}(this.config.drmSystemOptions)?new Promise((function(e,t){self.setTimeout((function(){return t(new Error("MediaKeySession.remove() timeout"))}),8e3),i.remove().then(e).catch(t)})):Promise.resolve();return o.catch((function(e){t.log("Could not remove session: "+e),t.hls&&t.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+e)})})).then((function(){return i.close()})).catch((function(e){t.log("Could not close session: "+e),t.hls&&t.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+e)})}))}return Promise.resolve()},t}(F);function ga(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return j(e.keyId)}function pa(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}fa.CDMCleanupPromise=void 0;var va=function(e){function t(t,i){var r;return(r=e.call(this,i)||this).data=void 0,t.error||(t.error=new Error(i)),r.data=t,t.err=t.error,r}return o(t,e),t}(f(Error));function ma(e,t){var i="output-restricted"===e,r=i?A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:A.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new va({type:b.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},i?"HDCP level output restricted":'key status changed to "'+e+'"')}var ya=function(){function e(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()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(I.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListeners=function(){this.hls.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(I.MEDIA_DETACHING,this.onMediaDetaching,this)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var i=this.hls.config;if(i.capLevelOnFPSDrop){var r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,i){var r=performance.now();if(t){if(this.lastTime){var s=r-this.lastTime,n=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*n/s,l=this.hls;if(l.trigger(I.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*a){var h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=h)&&(h-=1,l.trigger(I.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}();function Ea(e){for(var t=5381,i=e.length;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}var Sa=.025,Ta=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function _a(e,t,i){return e.identifier+"-"+(i+1)+"-"+Ea(t)}var La=function(){function e(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}var t=e.prototype;return t.setDateRange=function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)},t.reset=function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)},t.isAssetPastPlayoutLimit=function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var i=this.playoutLimit;return!(e<=0||isNaN(i))&&(0===i||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i)},t.findAssetIndex=function(e){return this.assetList.indexOf(e)},t.toString=function(){return'["'+(e=this).identifier+'" '+(e.cue.pre?"<pre>":e.cue.post?"<post>":"")+e.timelineStart.toFixed(2)+"-"+e.resumeTime.toFixed(2)+"]";var e},r(e,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return ba(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-ba(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=T(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return ba(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Sa))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Ta.Range:Ta.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}}])}();function ba(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Sa)?t.start:t.start+t.duration}function Aa(e,t,i){var r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function Ia(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function Ra(e){var t=e.timelineStart,i=e.duration||0;return'["'+e.identifier+'" '+t.toFixed(2)+"-"+(t+i).toFixed(2)+"]"}var Pa=function(){function e(e,t,i,r){var s=this;this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){s.reachedPlayout(s.currentTime)&&s.hls&&s.hls.trigger(I.PLAYOUT_LIMIT_REACHED,{})};var n=this.hls=new e(t);this.interstitial=i,this.assetItem=r;var a=function(){s.hasDetails=!0};n.once(I.LEVEL_LOADED,a),n.once(I.AUDIO_TRACK_LOADED,a),n.once(I.SUBTITLE_TRACK_LOADED,a),n.on(I.MEDIA_ATTACHING,(function(e,t){var i=t.media;s.removeMediaListeners(),s.mediaAttached=i,s.interstitial.playoutLimit&&(i.addEventListener("timeupdate",s.checkPlayout),s.appendInPlace&&n.on(I.BUFFER_APPENDED,(function(){var e=s.bufferedEnd;s.reachedPlayout(e)&&(s._bufferedEosTime=e,n.trigger(I.BUFFERED_TO_END,void 0))})))}))}var t=e.prototype;return t.loadSource=function(){var e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{var t=this.assetItem.uri;try{t=Aa(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}},t.bufferedInPlaceToEnd=function(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;var i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,s=jt.bufferInfo(e,r,0);return this.getAssetTime(s.end)>=i-.02},t.reachedPlayout=function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t},t.getAssetTime=function(e){var t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)},t.removeMediaListeners=function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))},t.bufferSnapShot=function(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},t.destroy=function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null},t.attachMedia=function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)},t.detachMedia=function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()},t.resumeBuffering=function(){var e;null==(e=this.hls)||e.resumeBuffering()},t.pauseBuffering=function(){var e;null==(e=this.hls)||e.pauseBuffering()},t.transferMedia=function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null},t.resetDetails=function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}},t.on=function(e,t,i){var r;null==(r=this.hls)||r.on(e,t)},t.once=function(e,t,i){var r;null==(r=this.hls)||r.once(e,t)},t.off=function(e,t,i){var r;null==(r=this.hls)||r.off(e,t)},t.toString=function(){var e;return"HlsAssetPlayer: "+Ra(this.assetItem)+" "+(null==(e=this.hls)?void 0:e.sessionId)+" "+(this.appendInPlace?"append-in-place":"")},r(e,[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=jt.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var i=t-this.startOffset;if(i>0&&i<e)return i}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}}])}(),ka=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials-sched",i)||this).onScheduleUpdate=void 0,r.eventMap={},r.events=null,r.items=null,r.durations={primary:0,playout:0,integrated:0},r.onScheduleUpdate=t,r}o(t,e);var i=t.prototype;return i.destroy=function(){this.reset(),this.onScheduleUpdate=null},i.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(e){return e.reset()})),this.events=this.items=null},i.resetErrorsInRange=function(e,t){return this.events?this.events.reduce((function(i,r){return e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i}),0):0},i.getEvent=function(e){return e&&this.eventMap[e]||null},i.hasEvent=function(e){return e in this.eventMap},i.findItemIndex=function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);var r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i},i.findItemIndexAtTime=function(e,t){var i=this.items;if(i)for(var r=0;r<i.length;r++){var s=i[r];if(t&&"primary"!==t&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return r}return-1},i.findJumpRestrictedIndex=function(e,t){var i=this.items;if(i)for(var r=e;r<=t&&i[r];r++){var s=i[r].event;if(null!=s&&s.restrictions.jump&&!s.appendInPlace)return r}return-1},i.findEventIndex=function(e){var t=this.items;if(t)for(var i=t.length;i--;){var r;if((null==(r=t[i].event)?void 0:r.identifier)===e)return i}return-1},i.findAssetIndex=function(e,t){var i=e.assetList,r=i.length;if(r>1)for(var s=0;s<r;s++){var n=i[s];if(!n.error){var a=n.timelineStart;if(t===a||t>a&&(t<a+(n.duration||0)||s===r-1))return s}}return 0},i.parseInterstitialDateRanges=function(e,t){var i=this,r=e.main.details,s=r.dateRanges,n=this.events,a=this.parseDateRanges(s,{url:r.url},t),o=Object.keys(s),l=n?n.filter((function(e){return!o.includes(e.identifier)})):[];a.length&&a.sort((function(e,t){var i=e.cue.pre,r=e.cue.post,s=t.cue.pre,n=t.cue.post;if(i&&!s)return-1;if(s&&!i)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(i||s||r||n)){var a=e.startTime,o=t.startTime;if(a!==o)return a-o}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=a,l.forEach((function(e){i.removeEvent(e)})),this.updateSchedule(e,l)},i.updateSchedule=function(e,t,i){void 0===t&&(t=[]),void 0===i&&(i=!1);var r=this.events||[];if(r.length||t.length||this.length<2){var s=this.items,n=this.parseSchedule(r,e);(i||t.length||(null==s?void 0:s.length)!==n.length||n.some((function(e,t){return Math.abs(e.playout.start-s[t].playout.start)>.005||Math.abs(e.playout.end-s[t].playout.end)>.005})))&&(this.items=n,this.onScheduleUpdate(t,s))}},i.parseDateRanges=function(e,t,i){for(var r=[],s=Object.keys(e),n=0;n<s.length;n++){var a=s[n],o=e[a];if(o.isInterstitial){var l=this.eventMap[a];l?l.setDateRange(o):(l=new La(o,t),this.eventMap[a]=l,!1===i&&(l.appendInPlace=i)),r.push(l)}}return r},i.parseSchedule=function(e,t){var i=[],r=t.main.details,s=r.live?1/0:r.edge,n=0;if((e=e.filter((function(e){return!(e.error||e.cue.once&&e.hasPlayed)}))).length){this.resolveOffsets(e,t);var a=0,o=0;if(e.forEach((function(t,r){var l=t.cue.pre,h=t.cue.post,u=e[r-1]||null,d=t.appendInPlace,c=h?s:t.startOffset,f=t.duration,g=t.timelineOccupancy===Ta.Range?f:0,p=t.resumptionOffset,v=(null==u?void 0:u.startTime)===c,m=c+t.cumulativeDuration,y=d?m+f:c+p;if(l||!h&&c<=0){var E=o;o+=g,t.timelineStart=m;var S=n;n+=f,i.push({event:t,start:m,end:y,playout:{start:S,end:n},integrated:{start:E,end:o}})}else{if(!(c<=s))return;if(!v){var T=c-a;if(T>.033){var _=a,L=o;o+=T;var b=n;n+=T;var A={previousEvent:e[r-1]||null,nextEvent:t,start:_,end:_+T,playout:{start:b,end:n},integrated:{start:L,end:o}};i.push(A)}else T>0&&u&&(u.cumulativeDuration+=T,i[i.length-1].end=c)}h&&(y=m),t.timelineStart=m;var I=o;o+=g;var R=n;n+=f,i.push({event:t,start:m,end:y,playout:{start:R,end:n},integrated:{start:I,end:o}})}var P=t.resumeTime;a=h||P>s?s:P})),a<s){var l,h=a,u=o,d=s-a;o+=d;var c=n;n+=d,i.push({previousEvent:(null==(l=i[i.length-1])?void 0:l.event)||null,nextEvent:null,start:a,end:h+d,playout:{start:c,end:n},integrated:{start:u,end:o}})}this.setDurations(s,n,o)}else i.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return i},i.setDurations=function(e,t,i){this.durations={primary:e,playout:t,integrated:i}},i.resolveOffsets=function(e,t){var i=this,r=t.main.details,s=r.live?1/0:r.edge,n=0,a=-1;e.forEach((function(o,l){var h=o.cue.pre,u=o.cue.post,d=h?0:u?s:o.startTime;i.updateAssetDurations(o),a===d?o.cumulativeDuration=n:(n=0,a=d),!u&&o.snapOptions.in&&(o.resumeAnchor=ft(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(i.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&i.warn("Could not change append strategy for abutting event "+o));var c=T(o.resumeOffset)?o.resumeOffset:o.duration;n+=c}))},i.primaryCanResumeInPlaceAt=function(e,t){var i=this,r=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(r-s)>Sa?(this.log('"'+e.identifier+'" resumption '+r+" not aligned with estimated timeline end "+s),!1):!Object.keys(t).some((function(s){var n=t[s].details,a=n.edge;if(r>=a)return i.log('"'+e.identifier+'" resumption '+r+" past "+s+" playlist end "+a),!1;var o=ft(null,n.fragments,r);if(!o)return i.log('"'+e.identifier+'" resumption '+r+" does not align with any fragments in "+s+" playlist ("+n.fragStart+"-"+n.fragmentEnd+")"),!0;var l="audio"===s?.175:0;return!(Math.abs(o.start-r)<Sa+l||Math.abs(o.end-r)<Sa+l||(i.log('"'+e.identifier+'" resumption '+r+" not aligned with "+s+" fragment bounds ("+o.start+"-"+o.end+" sn: "+o.sn+" cc: "+o.cc+")"),0))}))},i.updateAssetDurations=function(e){if(e.assetListLoaded){for(var t=e.timelineStart,i=0,r=!1,s=!1,n=0;n<e.assetList.length;n++){var a=e.assetList[n],o=t+i;a.startOffset=i,a.timelineStart=o,r||(r=null===a.duration),s||(s=!!a.error),i+=a.error?0:a.duration||0}e.duration=r&&!s?Math.max(i,e.duration):i}},i.removeEvent=function(e){e.reset(),delete this.eventMap[e.identifier]},r(t,[{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}}])}(F);function Da(e){return"["+(e.event?'"'+e.event.identifier+'"':"primary")+": "+e.start.toFixed(2)+"-"+e.end.toFixed(2)+"]"}var wa=function(){function e(e){this.hls=void 0,this.hls=e}var t=e.prototype;return t.destroy=function(){this.hls=null},t.loadAssetList=function(e,t){var i,r=this,s=e.assetListUrl;try{i=Aa(s,this.hls.sessionId,e.baseUrl)}catch(t){var n=this.assignAssetListError(e,A.ASSET_LIST_LOAD_ERROR,t,s);return void this.hls.trigger(I.ERROR,n)}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);var a=this.hls.config,o=new(0,a.loader)(a),l={responseType:"json",url:i.href},h=a.interstitialAssetListLoadPolicy.default,u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,i,s,n){var a=t.data,o=null==a?void 0:a.ASSETS;if(Array.isArray(o))e.assetListResponse=a,r.hls.trigger(I.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:n});else{var l=r.assignAssetListError(e,A.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,n);r.hls.trigger(I.ERROR,l)}},onError:function(t,i,s,n){var a=r.assignAssetListError(e,A.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status "+t.code+" "+t.text+" ("+i.url+")"),i.url,n,s);r.hls.trigger(I.ERROR,a)},onTimeout:function(t,i,s){var n=r.assignAssetListError(e,A.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST ("+i.url+")"),i.url,t,s);r.hls.trigger(I.ERROR,n)}};return o.load(l,u,d),this.hls.trigger(I.ASSET_LIST_LOADING,{event:e}),o},t.assignAssetListError=function(e,t,i,r,s,n){return e.error=i,{type:b.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:n,stats:s}},e}();function Ca(e){null==e||e.play().catch((function(){}))}function Ma(e,t){return"["+e+"] Advancing timeline position to "+t}var Oa=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials",t.logger)||this).HlsPlayerClass=void 0,r.hls=void 0,r.assetListLoader=void 0,r.mediaSelection=null,r.altSelection=null,r.media=null,r.detachedData=null,r.requiredTracks=null,r.manager=null,r.playerQueue=[],r.bufferedPos=-1,r.timelinePos=-1,r.schedule=void 0,r.playingItem=null,r.bufferingItem=null,r.waitingItem=null,r.endedItem=null,r.playingAsset=null,r.endedAsset=null,r.bufferingAsset=null,r.shouldPlay=!1,r.onPlay=function(){r.shouldPlay=!0},r.onPause=function(){r.shouldPlay=!1},r.onSeeking=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&r.schedule){var t=e-r.timelinePos;if(!(Math.abs(t)<1/7056e5)){var i=t<=-.01;r.timelinePos=e,r.bufferedPos=e;var s=r.playingItem;if(s)if(i&&r.schedule.resetErrorsInRange(e,e-t)&&r.updateSchedule(!0),r.checkBuffer(),i&&e<s.start||e>=s.end){var n,a=r.findItemIndex(s),o=r.schedule.findItemIndexAtTime(e);if(-1===o&&(o=a+(i?-1:1),r.log("seeked "+(i?"back ":"")+"to position not covered by schedule "+e+" (resolving from "+a+" to "+o+")")),!r.isInterstitial(s)&&null!=(n=r.media)&&n.paused&&(r.shouldPlay=!1),!i&&o>a){var l=r.schedule.findJumpRestrictedIndex(a+1,o);if(l>a)return void r.setSchedulePosition(l)}r.setSchedulePosition(o)}else{var h=r.playingAsset;if(h){var u,d=h.timelineStart,c=h.duration||0;(i&&e<d||e>=d+c)&&(null!=(u=s.event)&&u.appendInPlace&&(r.clearInterstitial(s.event,s),r.flushFrontBuffer(e)),r.setScheduleToAssetAtTime(e,h))}else if(r.playingLastItem&&r.isInterstitial(s)){var f=s.event.assetList[0];f&&(r.endedItem=r.playingItem,r.playingItem=null,r.setScheduleToAssetAtTime(e,f))}}else r.checkBuffer()}}},r.onTimeupdate=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&e>r.timelinePos){r.timelinePos=e,e>r.bufferedPos&&r.checkBuffer();var t=r.playingItem;if(t&&!r.playingLastItem){if(e>=t.end){r.timelinePos=t.end;var i=r.findItemIndex(t);r.setSchedulePosition(i+1)}var s=r.playingAsset;s&&e>=s.timelineStart+(s.duration||0)&&r.setScheduleToAssetAtTime(e,s)}}},r.onScheduleUpdate=function(e,t){var i=r.schedule;if(i){var s=r.playingItem,n=i.events||[],a=i.items||[],o=i.durations,l=e.map((function(e){return e.identifier})),h=!(!n.length&&!l.length);(h||t)&&r.log("INTERSTITIALS_UPDATED ("+n.length+"): "+n+"\nSchedule: "+a.map((function(e){return Da(e)}))+" pos: "+r.timelinePos),l.length&&r.log("Removed events "+l);var u=null,d=null;s&&(u=r.updateItem(s,r.timelinePos),r.itemsMatch(s,u)?r.playingItem=u:r.waitingItem=r.endedItem=null),r.waitingItem=r.updateItem(r.waitingItem),r.endedItem=r.updateItem(r.endedItem);var c=r.bufferingItem;if(c&&(d=r.updateItem(c,r.bufferedPos),r.itemsMatch(c,d)?r.bufferingItem=d:c.event&&(r.bufferingItem=r.playingItem,r.clearInterstitial(c.event,null))),e.forEach((function(e){e.assetList.forEach((function(e){r.clearAssetPlayer(e.identifier,null)}))})),r.playerQueue.forEach((function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>Sa&&r.warn(s+' ("'+e.assetId+'" '+e.timelineOffset+"->"+t+")")}}})),h||t){if(r.hls.trigger(I.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:a.slice(0),durations:o,removedIds:l}),r.isInterstitial(s)&&l.includes(s.event.identifier))return r.warn('Interstitial "'+s.event.identifier+'" removed while playing'),void r.primaryFallback(s.event);s&&r.trimInPlace(u,s),c&&d!==u&&r.trimInPlace(d,c),r.checkBuffer()}}},r.hls=t,r.HlsPlayerClass=i,r.assetListLoader=new wa(t),r.schedule=new ka(r.onScheduleUpdate,t.logger),r.registerListeners(),r}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e&&(e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this),e.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(I.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(I.MEDIA_ENDED,this.onMediaEnded,this),e.on(I.ERROR,this.onError,this),e.on(I.DESTROYING,this.onDestroying,this))},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(I.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(I.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(I.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(I.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(I.BUFFER_CODECS,this.onBufferCodecs,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this),e.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(I.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(I.MEDIA_ENDED,this.onMediaEnded,this),e.off(I.ERROR,this.onError,this),e.off(I.DESTROYING,this.onDestroying,this))},i.startLoad=function(){this.resumeBuffering()},i.stopLoad=function(){this.pauseBuffering()},i.resumeBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()},i.pauseBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},i.onDestroying=function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)},i.removeMediaListeners=function(e){or(e,"play",this.onPlay),or(e,"pause",this.onPause),or(e,"seeking",this.onSeeking),or(e,"timeupdate",this.onTimeupdate)},i.onMediaAttaching=function(e,t){var i=this.media=t.media;ar(i,"seeking",this.onSeeking),ar(i,"timeupdate",this.onTimeupdate),ar(i,"play",this.onPlay),ar(i,"pause",this.onPause)},i.onMediaAttached=function(e,t){var i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();var s=this.findItemIndex(i);this.setSchedulePosition(s)}},i.clearScheduleState=function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){var s=this.getBufferingPlayer();s&&(this.log("Removing schedule state for detachedData and "+s),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}},i.isInterstitial=function(e){return!(null==e||!e.event)},i.retreiveMediaSource=function(e,t){var i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)},i.transferMediaFromPlayer=function(e,t){var i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});var s=e.transferMedia();this.log("transfer MediaSource from "+e+" "+it(s)),this.detachedData=s}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))},i.transferMediaTo=function(e,t){var i,r,s=this;if(e.media!==t){var n,a=null,o=this.hls,l=e!==o,h=l&&e.interstitial.appendInPlace,u=null==(i=this.detachedData)?void 0:i.mediaSource;if(o.media)h&&(a=o.transferMedia(),this.detachedData=a),n="Primary";else if(u){var d=this.getBufferingPlayer();d?(a=d.transferMedia(),n=""+d):n="detached MediaSource"}else n="detached media";if(!a)if(u)a=this.detachedData,this.log("using detachedData: MediaSource "+it(a));else if(!this.detachedData||o.media===t){var c=this.playerQueue;c.length>1&&c.forEach((function(e){if(l&&e.interstitial.appendInPlace!==h){var t=e.interstitial;s.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&s.warn("Could not change append strategy for queued assets "+t)}})),this.hls.detachMedia(),this.detachedData={media:t}}var f=a&&"mediaSource"in a&&"closed"!==(null==(r=a.mediaSource)?void 0:r.readyState),g=f&&a?a:t;this.log((f?"transfering MediaSource":"attaching media")+" to "+(l?e:"Primary")+" from "+n+" (media.currentTime: "+t.currentTime+")");var p=this.schedule;if(g===a&&p){var v=l&&e.assetId===p.assetIdAtEnd;g.overrides={duration:p.duration,endOfStream:!l||v,cueRemoval:!l}}e.attachMedia(g)}},i.onInterstitialCueEnter=function(){this.onTimeupdate()},i.checkStart=function(){var e=this.schedule,t=null==e?void 0:e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){var s=this.hls.startPosition;if(this.log(Ma("checkStart",s)),this.timelinePos=s,t.length&&t[0].cue.pre){var n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(s>=0||!this.primaryLive){var a=this.timelinePos=s>0?s:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){var l=e.findItemIndex(r);this.setSchedulePosition(l)}}},i.advanceAssetBuffering=function(e,t){var i=e.event,r=i.findAssetIndex(t),s=Ia(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var n,a=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(e)+1];a&&this.bufferedToItem(a)}}else this.bufferedToEvent(e,s)},i.advanceAfterAssetEnded=function(e,t,i){var r=Ia(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){var s=this.schedule.items;if(s){var n=t+1;if(n>=s.length)return void this.setSchedulePosition(-1);var a=e.resumeTime;this.timelinePos<a&&(this.log(Ma("advanceAfterAssetEnded",a)),this.timelinePos=a,e.appendInPlace&&this.advanceInPlace(a),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){var o=e.assetList[r];o&&this.advanceInPlace(o.timelineStart)}this.setSchedulePosition(t,r)}},i.setScheduleToAssetAtTime=function(e,t){var i=this.schedule;if(i){var r=t.parentIdentifier,s=i.getEvent(r);if(s){var n=i.findEventIndex(r),a=i.findAssetIndex(s,e);this.advanceAfterAssetEnded(s,n,a-1)}}},i.setSchedulePosition=function(e,t){var i,r=null==(i=this.schedule)?void 0:i.items;if(r&&!this.playbackDisabled){var s=e>=0?r[e]:null;this.log("setSchedulePosition "+e+", "+t+" ("+(s?Da(s):s)+") pos: "+this.timelinePos);var n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){var o=n.event,l=this.playingAsset,h=null==l?void 0:l.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(n,s)||void 0!==t&&h!==o.assetList[t].identifier)){var d,c=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED "+(c+1)+"/"+o.assetList.length+" "+Ra(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(I.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:c,event:o,schedule:r.slice(0),scheduleIndex:e,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),c));this.retreiveMediaSource(h,s),!u.media||null!=(d=this.detachedData)&&d.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+Da(n)),o.hasPlayed=!0,this.hls.trigger(I.INTERSTITIAL_ENDED,{event:o,schedule:r.slice(0),scheduleIndex:e}),o.cue.once)){var f;this.updateSchedule();var g=null==(f=this.schedule)?void 0:f.items;if(s&&g){var p=this.findItemIndex(s);this.advanceSchedule(p,g,t,n,a)}return}}this.advanceSchedule(e,r,t,n,a)}},i.advanceSchedule=function(e,t,i,r,s){var n=this,a=this.schedule;if(a){var o=t[e]||null,l=this.primaryMedia,h=this.playerQueue;if(h.length&&h.forEach((function(t){var i=t.interstitial,r=a.findEventIndex(i.identifier);(r<e||r>e+1)&&n.clearInterstitial(i,o)})),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var u=o.event;if(void 0===i){var d=Ia(u,(i=a.findAssetIndex(u,this.timelinePos))-1);if(u.isAssetPastPlayoutLimit(d)||u.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(u,e,i);i=d}var c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(u,i);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED "+Da(o)+" "+(u.appendInPlace?"append in place":"")),this.hls.trigger(I.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+u);if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial "+u);this.waitingItem=this.endedItem=null,this.playingItem=o;var g=u.assetList[i];if(!g)return void this.advanceAfterAssetEnded(u,e,i||0);if(f||(f=this.getAssetPlayer(g.identifier)),null===f||f.destroyed){var p=u.assetList.length;this.warn("asset "+(i+1)+"/"+p+" player destroyed "+u),(f=this.createAssetPlayer(u,g,i)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(f,i,t,e,l),this.shouldPlay&&Ca(f.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&Ca(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}},i.resumePrimary=function(e,t,i){var r,s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming "+Da(e)),null==(r=this.detachedData)||!r.mediaSource){var n=this.timelinePos;(n<e.start||n>=e.end)&&(n=this.getPrimaryResumption(e,t),this.log(Ma("resumePrimary",n)),this.timelinePos=n),this.attachPrimary(n,e)}if(i){var a=null==(s=this.schedule)?void 0:s.items;a&&(this.log("INTERSTITIALS_PRIMARY_RESUMED "+Da(e)),this.hls.trigger(I.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}},i.getPrimaryResumption=function(e,t){var i=e.start;if(this.primaryLive){var r=this.primaryDetails;if(0===t)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i},i.isAssetBuffered=function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:jt.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)},i.attachPrimary=function(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var r=this.primaryMedia;if(r){var s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Ma("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}},i.startLoadingPrimaryAt=function(e,t){var i,r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()},i.onManifestLoading=function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(I.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(I.BUFFER_CODECS,this.onBufferCodecs,this)},i.onLevelUpdated=function(e,t){if(-1!==t.level&&this.schedule){var i=this.hls.levels[t.level];if(i.details){var r=u(u({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}}},i.onAudioTrackUpdated=function(e,t){var i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(r){var s=u(u({},r),{},{audio:i});this.mediaSelection=s}else this.altSelection=u(u({},this.altSelection),{},{audio:i})},i.onSubtitleTrackUpdated=function(e,t){var i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(r){var s=u(u({},r),{},{subtitles:i});this.mediaSelection=s}else this.altSelection=u(u({},this.altSelection),{},{subtitles:i})},i.onAudioTrackSwitching=function(e,t){var i=nt(t);this.playerQueue.forEach((function(e){var r=e.hls;return r&&(r.setAudioOption(t)||r.setAudioOption(i))}))},i.onSubtitleTrackSwitch=function(e,t){var i=nt(t);this.playerQueue.forEach((function(e){var r=e.hls;return r&&(r.setSubtitleOption(t)||-1!==t.id&&r.setSubtitleOption(i))}))},i.onBufferCodecs=function(e,t){var i=t.tracks;i&&(this.requiredTracks=i)},i.onBufferAppended=function(e,t){this.checkBuffer()},i.onBufferFlushed=function(e,t){var i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){var r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}},i.onBufferedToEnd=function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var i=0;i<t.length;i++){var r=t[i];if(r.cue.post){var s,n=this.schedule.findEventIndex(r.identifier),a=null==(s=this.schedule.items)?void 0:s[n];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}},i.onMediaEnded=function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1},i.updateItem=function(e,t){var i,r=null==(i=this.schedule)?void 0:i.items;return e&&r&&r[this.findItemIndex(e,t)]||null},i.trimInPlace=function(e,t){var i=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((function(t,r){e.event.isAssetPastPlayoutLimit(r)&&i.clearAssetPlayer(t.identifier,null)}));var r=e.end+.25,s=jt.bufferInfo(this.primaryMedia,r,0);(s.end>r||(s.nextStart||0)>r)&&(this.log("trim buffered interstitial "+Da(e)+" (was "+Da(t)+")"),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}},i.itemsMatch=function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))},i.eventItemsMatch=function(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))},i.findItemIndex=function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1},i.updateSchedule=function(e){var t;void 0===e&&(e=!1);var i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))},i.checkBuffer=function(e){var t,i=null==(t=this.schedule)?void 0:t.items;if(i){var r=jt.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}},i.updateBufferedPos=function(e,t,i){var r=this.schedule,s=this.bufferingItem;if(!(this.bufferedPos>e)&&r)if(1===t.length&&this.itemsMatch(t[0],s))this.bufferedPos=e;else{var n=this.playingItem,a=this.findItemIndex(n),o=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,h=this.findItemIndex(s),u=Math.min(h+1,t.length-1),d=t[u];if((-1===o&&s&&e>=s.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=u),this.isInterstitial(s)){var c=s.event;if(u-a>1&&!1===c.appendInPlace)return;if(0===c.assetList.length&&c.assetListLoader)return}if(this.bufferedPos=e,o>h&&o>a)this.bufferedToItem(d);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else i&&n&&!this.itemsMatch(n,s)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}},i.assetsBuffered=function(e,t){var i=this;return 0!==e.event.assetList.length&&!e.event.assetList.some((function(e){var r=i.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))}))},i.setBufferingItem=function(e){var t=this,i=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,i)&&r){var s=r.items,n=r.events;if(!s||!n)return i;var a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:i?i.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY "+Da(e)+(i?" ("+l.toFixed(2)+" remaining)":"")),!this.playbackDisabled)if(a){var h=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((function(e,i){var r=t.getAssetPlayer(e.identifier);r&&(i===h&&r.loadSource(),r.resumeBuffering())}))}else this.hls.resumeBuffering(),this.playerQueue.forEach((function(e){return e.pauseBuffering()}));this.hls.trigger(I.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return i},i.bufferedToItem=function(e,t){void 0===t&&(t=0);var i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;var r=this.detachedData;r&&r.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}},i.preloadPrimary=function(e){var t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)},i.bufferedToEvent=function(e,t){var i=e.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){var n=this.preloadAssets(i,t);if(null!=n&&n.interstitial.appendInPlace){var a=this.primaryMedia;a&&this.bufferAssetPlayer(n,a)}}},i.preloadAssets=function(e,t){var i=e.assetUrl,r=e.assetList.length,s=0===r&&!e.assetListLoader,n=e.cue.once;if(s){var a,o=e.timelineStart;if(e.appendInPlace){var l,h=this.playingItem;this.isInterstitial(h)||(null==h||null==(l=h.nextEvent)?void 0:l.identifier)!==e.identifier||this.flushFrontBuffer(o+.25)}var u=0;if(!this.playingItem&&this.primaryLive&&-1===(u=this.hls.startPosition)&&(u=this.hls.liveSyncPosition||0),u&&!e.cue.pre&&!e.cue.post){var d=u-o;d>0&&(a=Math.round(1e3*d)/1e3)}if(this.log("Load interstitial asset "+(t+1)+"/"+(i?1:r)+" "+e+(a?" live-start: "+u+" start-offset: "+a:"")),i)return this.createAsset(e,0,0,o,e.duration,i);var c=this.assetListLoader.loadAssetList(e,a);c&&(e.assetListLoader=c)}else if(!n&&r){for(var f=t;f<r;f++){var g=e.assetList[f],p=this.getAssetPlayerQueueIndex(g.identifier);-1!==p&&!this.playerQueue[p].destroyed||g.error||this.createAssetPlayer(e,g,f)}var v=e.assetList[t];if(v){var m=this.getAssetPlayer(v.identifier);return m&&m.loadSource(),m}}return null},i.flushFrontBuffer=function(e){var t=this,i=this.requiredTracks;i&&(this.log("Removing front buffer starting at "+e),Object.keys(i).forEach((function(i){t.hls.trigger(I.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})))},i.getAssetPlayerQueueIndex=function(e){for(var t=this.playerQueue,i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1},i.getAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null},i.getBufferingPlayer=function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null},i.createAsset=function(e,t,i,r,s,n){var a={parentIdentifier:e.identifier,identifier:_a(e,n,t),duration:s,startOffset:i,timelineStart:r,uri:n};return this.createAssetPlayer(e,a,t)},i.createAssetPlayer=function(e,t,i){var r=this,s=this.hls,a=s.userConfig,o=a.videoPreference,l=s.loadLevelObj||s.levels[s.currentLevel];(o||l)&&(o=n({},o),l.videoCodec&&(o.videoCodec=l.videoCodec),l.videoRange&&(o.allowedVideoRanges=[l.videoRange]));var h=s.audioTracks[s.audioTrack],d=s.subtitleTracks[s.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){var f=this.timelinePos-t.timelineStart;if(f>1){var g=t.duration;g&&f<g&&(c=f)}}var p=t.identifier,v=u(u({},a),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:p,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:h||a.audioPreference,subtitlePreference:d||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(v.timelineOffset=t.timelineStart));var m=v.cmcd;null!=m&&m.sessionId&&m.contentId&&(v.cmcd=n({},m,{contentId:Ea(t.uri)})),this.getAssetPlayer(p)&&this.warn("Duplicate date range identifier "+e+" and asset "+p);var y=new Pa(this.HlsPlayerClass,v,e,t);this.playerQueue.push(y),e.assetList[i]=t;var E=!0,S=function(s){if(s.live){var n,a=new Error("Interstitials MUST be VOD assets "+e),o={fatal:!0,type:b.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:a},l=(null==(n=r.schedule)?void 0:n.findEventIndex(e.identifier))||-1;r.handleAssetItemError(o,e,l,i,a.message)}else{var h=s.edge-s.fragmentStart,u=t.duration;(E||null===u||h>u)&&(E=!1,r.log('Interstitial asset "'+p+'" duration change '+u+" > "+h),t.duration=h,r.updateSchedule())}};y.on(I.LEVEL_UPDATED,(function(e,t){var i=t.details;return S(i)})),y.on(I.LEVEL_PTS_UPDATED,(function(e,t){var i=t.details;return S(i)})),y.on(I.EVENT_CUE_ENTER,(function(){return r.onInterstitialCueEnter()}));var T=function(e,t){var i=r.getAssetPlayer(p);if(i&&t.tracks){i.off(I.BUFFER_CODECS,T),i.tracks=t.tracks;var s=r.primaryMedia;r.bufferingAsset===i.assetItem&&s&&!i.media&&r.bufferAssetPlayer(i,s)}};y.on(I.BUFFER_CODECS,T),y.on(I.BUFFERED_TO_END,(function(){var i,s=r.getAssetPlayer(p);if(r.log("buffered to end of asset "+s),s&&r.schedule){var n=r.schedule.findEventIndex(e.identifier),a=null==(i=r.schedule.items)?void 0:i[n];r.isInterstitial(a)&&r.advanceAssetBuffering(a,t)}}));var _=function(t){return function(){if(r.getAssetPlayer(p)&&r.schedule){r.shouldPlay=!0;var i=r.schedule.findEventIndex(e.identifier);r.advanceAfterAssetEnded(e,i,t)}}};return y.once(I.MEDIA_ENDED,_(i)),y.once(I.PLAYOUT_LIMIT_REACHED,_(1/0)),y.on(I.ERROR,(function(t,s){if(r.schedule){var n=r.getAssetPlayer(p);if(s.details===A.BUFFER_STALLED_ERROR)return null!=n&&n.appendInPlace?void r.handleInPlaceStall(e):(r.onTimeupdate(),void r.checkBuffer(!0));r.handleAssetItemError(s,e,r.schedule.findEventIndex(e.identifier),i,"Asset player error "+s.error+" "+e)}})),y.on(I.DESTROYING,(function(){if(r.getAssetPlayer(p)&&r.schedule){var t=new Error("Asset player destroyed unexpectedly "+p),s={fatal:!0,type:b.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};r.handleAssetItemError(s,e,r.schedule.findEventIndex(e.identifier),i,t.message)}})),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED "+Ra(t)),this.hls.trigger(I.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:y}),y},i.clearInterstitial=function(e,t){var i=this;e.assetList.forEach((function(e){i.clearAssetPlayer(e.identifier,t)})),e.reset()},i.resetAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'+e+'" after error');var i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}},i.clearAssetPlayer=function(e,t){var i=this.getAssetPlayerQueueIndex(e);if(-1!==i){var r=this.playerQueue[i];this.log("clear "+r+" toSegment: "+(t?Da(t):t)),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}},i.emptyPlayerQueue=function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]},i.startAssetPlayer=function(e,t,i,r,s){var n=e.interstitial,a=e.assetItem,o=e.assetId,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log("INTERSTITIAL_ASSET_STARTED "+(t+1)+"/"+l+" "+Ra(a)),this.hls.trigger(I.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,s)},i.bufferAssetPlayer=function(e,t){var i,r;if(this.schedule){var s=e.interstitial,n=e.assetItem,a=this.schedule.findEventIndex(s.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(o){e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;var l=this.getBufferingPlayer();if(l!==e){var h=s.appendInPlace;if(!h||!1!==(null==l?void 0:l.interstitial.appendInPlace)){var u=(null==l?void 0:l.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering "+e);if(u&&!W(u,e.tracks)){var d=new Error("Asset "+Ra(n)+" SourceBuffer tracks ('"+Object.keys(e.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(u)+"')"),c={fatal:!0,type:b.OTHER_ERROR,details:A.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=s.findAssetIndex(n);return void this.handleAssetItemError(c,s,a,f,d.message)}}this.transferMediaTo(e,t)}}}}},i.handleInPlaceStall=function(e){var t=this.schedule,i=this.primaryMedia;if(t&&i){var r=i.currentTime,s=t.findAssetIndex(e,r),n=e.assetList[s];if(n){var a=this.getAssetPlayer(n.identifier);if(a){var o=a.currentTime||r-n.timelineStart,l=a.duration-o;if(this.warn("Stalled at "+o+" of "+(o+l)+" in "+a+" "+e+" (media.currentTime: "+r+")"),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){var h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,s)}}}}},i.advanceInPlace=function(e){var t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)},i.handleAssetItemError=function(e,t,i,r,s){if(e.details!==A.BUFFER_STALLED_ERROR){var a=t.assetList[r]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR "+(a?Ra(a):a)+" "+e.error),this.schedule){var o=(null==a?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),h=this.playerQueue[l]||null,u=this.schedule.items,d=n({},e,{fatal:!1,errorAction:It(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:i,player:h});if(this.hls.trigger(I.INTERSTITIAL_ASSET_ERROR,d),e.fatal){var c=this.playingAsset,f=this.bufferingAsset,g=new Error(s);if(a&&(this.clearAssetPlayer(o,null),a.error=g),t.assetList.some((function(e){return!e.error})))for(var p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);else t.error=g;this.updateSchedule(!0),t.error?this.primaryFallback(t):c&&c.identifier===o?this.advanceAfterAssetEnded(t,i,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}}}},i.primaryFallback=function(e){var t=e.timelineStart,i=this.effectivePlayingItem;if(i){this.log('Fallback to primary from event "'+e.identifier+'" start: '+t+" pos: "+this.timelinePos+" playing: "+Da(i)+" error: "+e.error);var r=this.timelinePos;-1===r&&(r=this.hls.startPosition);var s=this.updateItem(i,r);if(this.itemsMatch(i,s)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;var n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}else this.checkStart()},i.onAssetListLoaded=function(e,t){var i,r,s=this,n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(null!=(i=this.schedule)&&i.hasEvent(a)){var l=n.timelineStart,h=n.duration,u=0;o.forEach((function(e,t){var i=parseFloat(e.DURATION);s.createAsset(n,t,u,l+u,i,e.URI),u+=i})),n.duration=u,this.log("Loaded asset-list with duration: "+u+" (was: "+h+") "+n);var d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===a;this.updateSchedule();var f=null==(r=this.bufferingItem)?void 0:r.event;if(c){var g,p=this.schedule.findEventIndex(a),v=null==(g=this.schedule.items)?void 0:g[p];if(v){if(!this.playingItem&&this.timelinePos>v.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p)return n.error=new Error("Interstitial no longer within playback range "+this.timelinePos+" "+n),this.updateSchedule(!0),void this.primaryFallback(n);this.setBufferingItem(v)}this.setSchedulePosition(p)}else if((null==f?void 0:f.identifier)===a){var m=n.assetList[0];if(m){var y=this.getAssetPlayer(m.identifier);if(f.appendInPlace){var E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}},i.onError=function(e,t){if(this.schedule)switch(t.details){case A.ASSET_LIST_PARSING_ERROR:case A.ASSET_LIST_LOAD_ERROR:case A.ASSET_LIST_LOAD_TIMEOUT:var i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break;case A.BUFFER_STALLED_ERROR:var r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace)return void this.handleInPlaceStall(r.event);this.log("Primary player stall @"+this.timelinePos+" bufferedPos: "+this.bufferedPos),this.onTimeupdate(),this.checkBuffer(!0)}},r(t,[{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},i=function(t){return t?e.getAssetPlayer(t.identifier):t},r=function(t,r,n,a,o){if(t){var l=t[r].start,h=t.event;if(h){if("playout"===r||h.timelineOccupancy!==Ta.Point){var u=i(n);(null==u?void 0:u.interstitial)===h&&(l+=u.assetItem.startOffset+u[o])}}else l+=("bufferedPos"===a?s():e[a])-t.start;return l}return 0},s=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=function(t){var i,r;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(r=e.schedule)?void 0:r.durations[t])||0},a=function(t,s){var n,a,o=e.effectivePlayingItem;if((null==o||null==(n=o.event)||!n.restrictions.skip)&&e.schedule){e.log("seek to "+t+' "'+s+'"');var l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,s),u=null==(a=e.schedule.items)?void 0:a[h],d=e.getBufferingPlayer(),c=null==d?void 0:d.interstitial,f=null==c?void 0:c.appendInPlace,g=l&&e.itemsMatch(l,u);if(l&&(f||g)){var p=i(e.playingAsset),v=(null==p?void 0:p.media)||e.primaryMedia;if(v){var m="primary"===s?v.currentTime:r(l,s,e.playingAsset,"timelinePos","currentTime"),y=t-m,E=(f?m:v.currentTime)+y;if(E>=0&&(!p||f||E<=p.duration))return void(v.currentTime=E)}}if(u){var S=t;if("primary"!==s){var T=t-u[s].start;S=u.start+T}var _=!e.isInterstitial(u);if(e.isInterstitial(l)&&!l.event.appendInPlace||!_&&!u.event.appendInPlace){if(l){var L=e.findItemIndex(l);if(h>L){var b=e.schedule.findJumpRestrictedIndex(L+1,h);if(b>L)return void e.setSchedulePosition(b)}var A=0;if(_)e.timelinePos=S,e.checkBuffer();else for(var I=u.event.assetList,R=t-(u[s]||u).start,P=I.length;P--;){var k=I[P];if(k.duration&&R>=k.startOffset&&R<k.startOffset+k.duration){A=P;break}}e.setSchedulePosition(h,A)}}else{var D=e.media||(f?null==d?void 0:d.media:null);D&&(D.currentTime=S)}}}},o=function(){var i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;var r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){var i,s=t(),n=e.bufferingItem;return n&&n===s&&(r(n,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-n.playout.start||(null==(i=e.bufferingAsset)?void 0:i.startOffset))||0},get currentTime(){var t=o(),i=e.effectivePlayingItem;return i&&i===t?r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){var i=o(),r=e.effectivePlayingItem;r&&r===i&&a(t+r.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,i=null==(t=o())?void 0:t.event.assetList;return i?i.map((function(t){return e.getAssetPlayer(t.identifier)})):[]},get playingIndex(){var t,i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return s()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){var t;return function(t,i){var r;if(0!==t&&null!=(r=e.schedule)&&r.length){var s,n=e.schedule.findItemIndexAtTime(t),a=null==(s=e.schedule.items)?void 0:s[n];if(a)return t+(a[i].start-a.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){var r=e.findItemIndex(t);if(i.appendInPlace){var s=t.playout.start+t.event.duration;a(s+.001,"playout")}else e.advanceAfterAssetEnded(i,r,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var i=this.waitingItem||this.playingItem;if(!this.isInterstitial(i)||i.event.appendInPlace){var r=this.media;!r&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(r=this.primaryMedia);var s=null==(t=r)?void 0:t.currentTime;if(void 0!==s&&T(s))return s}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}}])}(F),xa=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"subtitle-stream-controller",M)||this).currentTrackId=-1,s.tracksBuffered=[],s.mainDetails=null,s.registerListeners(),s}o(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.mainDetails=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(I.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(I.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.startLoad=function(e,t){this.stopLoad(),this.state=lr.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.mainDetails=null},i.onMediaDetaching=function(t,i){this.tracksBuffered=[],e.prototype.onMediaDetaching.call(this,t,i)},i.onLevelLoaded=function(e,t){this.mainDetails=t.details},i.onSubtitleFragProcessed=function(e,t){var i=t.frag,r=t.success;if(this.fragContextChanged(i)||(ee(i)&&(this.fragPrevious=i),this.state=lr.IDLE),r){var s=this.tracksBuffered[this.currentTrackId];if(s){for(var n,a=i.start,o=0;o<s.length;o++)if(a>=s[o].start&&a<=s[o].end){n=s[o];break}var l=i.start+i.duration;n?n.end=l:(n={start:a,end:l},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}}},i.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var s=r-1;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach((function(e){for(var t=0;t<e.length;)if(e[t].end<=s)e.shift();else{if(!(e[t].start<s))break;e[t].start=s,t++}})),this.fragmentTracker.removeFragmentsInRange(i,s,M)}},i.onError=function(e,t){var i=t.frag;(null==i?void 0:i.type)===M&&(t.details===A.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==lr.STOPPED&&(this.state=lr.IDLE))},i.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks;this.levels&&Ys(this.levels,r)?this.levels=r.map((function(e){return new et(e)})):(this.tracksBuffered=[],this.levels=r.map((function(e){var t=new et(e);return i.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,M),this.fragPrevious=null,this.mediaBuffer=null)},i.onSubtitleTrackSwitch=function(e,t){var i;if(this.currentTrackId=t.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==lr.STOPPED&&this.setInterval(500)}else this.clearInterval()},i.onSubtitleTrackLoaded=function(e,t){var i,r=this.currentTrackId,s=this.levels,n=t.details,a=t.id;if(s){var o=s[a];if(!(a>=s.length)&&o){this.log("Subtitle track "+a+" loaded ["+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;var h=this.mainDetails;if(!h)return void(this.startFragRequested=!1);var u,d=h.fragments[0];o.details?0===(l=this.alignPlaylists(n,o.details,null==(u=this.levelLastLoaded)?void 0:u.details))&&d&&ji(n,l=d.start):n.hasProgramDateTime&&h.hasProgramDateTime?(nr(n,h),l=n.fragmentStart):d&&ji(n,l=d.start),h&&!this.startFragRequested&&this.setStartPosition(h,l)}o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(I.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===lr.IDLE&&(ft(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+a)},i._handleFragmentLoadComplete=function(e){var t=this,i=e.frag,r=e.payload,s=i.decryptdata,n=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&oi(s.method)){var a=performance.now();this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,li(s.method)).catch((function(e){throw n.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((function(e){var t=performance.now();n.trigger(I.FRAG_DECRYPTED,{frag:i,payload:e,stats:{tstart:a,tdecrypt:t}})})).catch((function(e){t.warn(e.name+": "+e.message),t.state=lr.IDLE}))}},i.doTick=function(){if(this.media){if(this.state===lr.IDLE){var e=this.currentTrackId,t=this.levels,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;var r=this.config,s=this.getLoadPosition(),n=jt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),a=n.end,o=n.len,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var h=l.fragments,u=h.length,d=l.edge,c=null,f=this.fragPrevious;if(a<d){var g=r.maxFragLookUpTolerance,p=a>d-g?0:g;!(c=ft(f,h,Math.max(h[0].start,a),p))&&f&&f.start<h[0].start&&(c=h[0])}else c=h[u-1];if(!(c=this.filterReplacedPrimary(c,i.details)))return;var v=h[c.sn-l.startSN-1];if(v&&v.cc===c.cc&&this.fragmentTracker.getState(v)===Rt&&(c=v),this.fragmentTracker.getState(c)===Rt){var m=this.mapToInitFragWhenRequired(c);m&&this.loadFragment(m,i,a)}}}else this.state=lr.IDLE},i.loadFragment=function(t,i,r){ee(t)?e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i)},r(t,[{key:"mediaBufferTimeRanges",get:function(){return new Fa(this.tracksBuffered[this.currentTrackId]||[])}}])}(hr),Fa=function(e){this.buffered=void 0;var t=function(t,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+i+") is greater than the maximum bound ("+r+")");return e[i][t]};this.buffered={get length(){return e.length},end:function(i){return t("end",i,e.length)},start:function(i){return t("start",i,e.length)}}};function Na(e,t){var i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function Ba(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(i){V.debug("[texttrack-utils]: "+i);try{var r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){V.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===i&&(e.mode=i)}function Ua(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===i&&(e.mode=i)}function Ga(e,t,i,r){var s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var n=function(e,t,i){var r=[],s=function(e,t){if(t<=e[0].startTime)return 0;var i=e.length-1;if(t>e[i].endTime)return-1;for(var r,s=0,n=i;s<=n;)if(t<e[r=Math.floor((n+s)/2)].startTime)n=r-1;else{if(!(t>e[r].startTime&&s<i))return r;s=r+1}return e[s].startTime-t<t-e[n].startTime?s:n}(e,t);if(s>-1)for(var n=s,a=e.length;n<a;n++){var o=e[n];if(o.startTime>=t&&o.endTime<=i)r.push(o);else if(o.startTime>i)return r}return r}(e.cues,t,i),a=0;a<n.length;a++)r&&!r(n[a])||e.removeCue(n[a]);"disabled"===s&&(e.mode=s)}function Ha(e){for(var t=[],i=0;i<e.length;i++){var r=e[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[i])}return t}var Ka=function(e){function t(t){var i;return(i=e.call(this,t,"subtitle-track-controller")||this).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var e=null,t=Ha(i.media.textTracks),r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}var s=i.findTrackForTextTrack(e);i.subtitleTrack!==s&&i.setSubtitleTrack(s)}},i.registerListeners(),i}o(t,e);var i=t.prototype;return i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,e.prototype.destroy.call(this)},i.registerListeners=function(){var e=this.hls;e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_PARSED,this.onManifestParsed,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(I.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_PARSED,this.onManifestParsed,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(I.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(I.ERROR,this.onError,this)},i.onMediaAttached=function(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))},i.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},i.onMediaDetaching=function(e,t){var i=this.media;if(i){var r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r||Ha(i.textTracks).forEach((function(e){Ua(e)}))}},i.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},i.onSubtitleTrackLoaded=function(e,t){var i=t.id,r=t.groupId,s=t.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=t.details,this.log("Subtitle track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Subtitle track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(e,t){e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;var o=at(a,n);if(o>-1)s=n[o];else{var l=at(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var u={subtitleTracks:n};this.log("Updating subtitle tracks, "+n.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(I.SUBTITLE_TRACKS_UPDATED,u),-1!==h&&-1===this.trackId&&this.setSubtitleTrack(h)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=this.selectDefaultTrack,r=0;r<t.length;r++){var s=t[r];if((!i||s.default)&&(i||e)&&(!e||ot(s,e)))return r}if(e){for(var n=0;n<t.length;n++){var a=t[n];if(zs(e.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(var o=0;o<t.length;o++){var l=t[o];if(zs(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1},i.findTrackForTextTrack=function(e){if(e)for(var t=this.tracksInGroup,i=0;i<t.length;i++)if(Xs(t[i],e))return i;return-1},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==D||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setSubtitleOption=function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var i=this.currentTrack;if(i&&ot(e,i))return i;var r=at(e,this.tracksInGroup);if(r>-1){var s=this.tracksInGroup[r];return this.setSubtitleTrack(r),s}if(i)return null;var n=at(e,t);if(n>-1)return t[n]}}return null},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,s=t.groupId,n=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading subtitle "+r+' "'+t.name+'" lang:'+t.lang+" group:"+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+n),this.hls.trigger(I.SUBTITLE_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:i||null,track:t})},i.toggleTrackModes=function(){var e=this.media;if(e){var t,i=Ha(e.textTracks),r=this.currentTrack;if(r&&((t=i.filter((function(e){return Xs(r,e)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+r.name+'" and language "'+r.lang+'"')),[].slice.call(i).forEach((function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")})),t){var s=this.subtitleDisplay?"showing":"hidden";t.mode!==s&&(t.mode=s)}}},i.setSubtitleTrack=function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!T(e))this.warn("Invalid subtitle track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),r){var s=!!r.details&&!r.details.live;if(e!==this.trackId||r!==i||!s){this.log("Switching to subtitle-track "+e+(r?' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId:""));var n=r.id,a=r.groupId,o=void 0===a?"":a,l=r.name,h=r.type,u=r.url;this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:l,type:h,url:u});var d=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(d)}}else this.hls.trigger(I.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e},r(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}}])}(js),Va={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},$a=function(e){return String.fromCharCode(Va[e]||e)},Wa=15,qa=100,ja={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ya={17:2,18:4,21:6,22:8,23:10,19:13,20:15},za={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Xa={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Qa=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Ja=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var i="function"==typeof t?t():t;V.log(this.time+" ["+e+"] "+i)}},e}(),Za=function(e){for(var t=[],i=0;i<e.length;i++)t.push(e[i].toString(16));return t},eo=function(){function e(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}var t=e.prototype;return t.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},t.setStyles=function(e){for(var t=["foreground","underline","italics","background","flash"],i=0;i<t.length;i++){var r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}},t.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},t.equals=function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash},t.copy=function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash},t.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},e}(),to=function(){function e(){this.uchar=" ",this.penState=new eo}var t=e.prototype;return t.reset=function(){this.uchar=" ",this.penState.reset()},t.setChar=function(e,t){this.uchar=e,this.penState.copy(t)},t.setPenState=function(e){this.penState.copy(e)},t.equals=function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)},t.copy=function(e){this.uchar=e.uchar,this.penState.copy(e.penState)},t.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},e}(),io=function(){function e(e){this.chars=[],this.pos=0,this.currPenState=new eo,this.cueStartTime=null,this.logger=void 0;for(var t=0;t<qa;t++)this.chars.push(new to);this.logger=e}var t=e.prototype;return t.equals=function(e){for(var t=0;t<qa;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0},t.copy=function(e){for(var t=0;t<qa;t++)this.chars[t].copy(e.chars[t])},t.isEmpty=function(){for(var e=!0,t=0;t<qa;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e},t.setCursor=function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>qa&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=qa)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)},t.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},t.insertChar=function(e){var t=this;e>=144&&this.backSpace();var i=$a(e);this.pos>=qa?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+i+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t<qa;t++)this.chars[t].reset()},t.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},t.clearToEndOfRow=function(){this.clearFromPos(this.pos)},t.getTextString=function(){for(var e=[],t=!0,i=0;i<qa;i++){var r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")},t.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),ro=function(){function e(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var t=0;t<Wa;t++)this.rows.push(new io(e));this.logger=e}var t=e.prototype;return t.reset=function(){for(var e=0;e<Wa;e++)this.rows[e].clear();this.currRow=14},t.equals=function(e){for(var t=!0,i=0;i<Wa;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t},t.copy=function(e){for(var t=0;t<Wa;t++)this.rows[t].copy(e.rows[t])},t.isEmpty=function(){for(var e=!0,t=0;t<Wa;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},t.backSpace=function(){this.rows[this.currRow].backSpace()},t.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},t.insertChar=function(e){this.rows[this.currRow].insertChar(e)},t.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},t.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},t.setCursor=function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)},t.setPAC=function(e){this.logger.log(2,(function(){return"pacData = "+it(e)}));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var i=0;i<Wa;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){var n=s.rows[r].cueStartTime,a=this.logger.time;if(null!==n&&null!==a&&n<a)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(s.rows[r+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var h=e.indent,u=Math.max(h-1,0);l.setCursor(e.indent),e.color=l.chars[u].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)},t.setBkgData=function(e){this.logger.log(2,(function(){return"bkgData = "+it(e)})),this.backSpace(),this.setPen(e),this.insertChar(32)},t.setRollUpRows=function(e){this.nrRollUpRows=e},t.rollUp=function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return e.getDisplayText()}));var t=this.currRow+1-this.nrRollUpRows,i=this.rows.splice(t,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")},t.getDisplayText=function(e){e=e||!1;for(var t=[],i="",r=-1,s=0;s<Wa;s++){var n=this.rows[s].getTextString();n&&(r=s+1,e?t.push("Row "+r+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i},t.getTextAndFormat=function(){return this.rows},e}(),so=function(){function e(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 ro(i),this.nonDisplayedMemory=new ro(i),this.lastOutputScreen=new ro(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(function(){return"MODE="+e})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},t.insertChars=function(e){for(var t=this,i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return r+": "+t.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())},t.ccRCL=function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},t.ccBS=function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},t.ccAOF=function(){},t.ccAON=function(){},t.ccDER=function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},t.ccRU=function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},t.ccFON=function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},t.ccRDC=function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},t.ccTR=function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")},t.ccRTD=function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")},t.ccEDM=function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},t.ccCR=function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},t.ccENM=function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},t.ccEOC=function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+e.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)},t.ccTO=function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},t.ccMIDROW=function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var i=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][i]}this.logger.log(2,"MIDROW: "+it(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?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.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),no=function(){function e(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var r=this.logger=new Ja;this.channels=[null,new so(e,t,r),new so(e+1,i,r)]}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var i=this;this.logger.time=e;for(var r=function(e){var r=127&t[e],s=127&t[e+1],n=!1,a=null;if(0===r&&0===s)return 0;i.logger.log(3,(function(){return"["+Za([t[e],t[e+1]])+"] -> ("+Za([r,s])+")"}));var o=i.cmdHistory;if(r>=16&&r<=31){if(function(e,t,i){return i.a===e&&i.b===t}(r,s,o))return ao(null,null,o),i.logger.log(3,(function(){return"Repeated command ("+Za([r,s])+") is dropped"})),0;ao(r,s,i.cmdHistory),(n=i.parseCmd(r,s))||(n=i.parseMidrow(r,s)),n||(n=i.parsePAC(r,s)),n||(n=i.parseBackgroundAttributes(r,s))}else ao(null,null,o);if(!n&&(a=i.parseChars(r,s))){var l=i.currentChannel;l&&l>0?i.channels[l].insertChars(a):i.logger.log(2,"No channel found yet. TEXT-MODE?")}n||a||i.logger.log(2,(function(){return"Couldn't parse cleaned data "+Za([r,s])+" orig: "+Za([t[e],t[e+1]])}))},s=0;s<t.length;s+=2)r(s)},t.parseCmd=function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0},t.parseMidrow=function(e,t){var i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+Za([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var r=e<=23?1:2;i=t>=64&&t<=95?1===r?ja[e]:za[e]:1===r?Ya[e]:Xa[e];var s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)},t.interpretPAC=function(e,t){var i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),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=4*Math.floor((i-16)/2),r},t.parseChars=function(e,t){var i,r,s=null,n=null;return e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19?(r=17===n?t+80:18===n?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+$a(r)+"' in channel "+i})),s=[r]):e>=32&&e<=127&&(s=0===t?[e]:[e,t]),s&&this.logger.log(3,(function(){return"Char codes = "+Za(s).join(",")})),s},t.parseBackgroundAttributes=function(e,t){var i;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;var r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=Qa[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));var s=e<=23?1:2;return this.channels[s].setBkgData(r),!0},t.reset=function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}ao(null,null,this.cmdHistory)},t.cueSplitAtTime=function(e){for(var t=0;t<this.channels.length;t++){var i=this.channels[t];i&&i.cueSplitAtTime(e)}},e}();function ao(e,t,i){i.a=e,i.b=t}var oo=function(){if(null!=ci&&ci.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function s(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)e[a]=n[a]}return e}function n(t,n,a){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var h="",u=!1,d=t,c=n,f=a,g=null,p="",v=!0,m="auto",y="start",E=50,S="middle",T=50,_="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return u},set:function(e){u=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return p},set:function(t){var r=function(t){return i(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");p=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return v},set:function(e){v=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return y},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return S},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return _},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");_=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),lo=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function ho(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}var i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}var uo=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,i){for(var r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}},t.integer=function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},t.percent=function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1},e}();function co(e,t,i,r){var s=r?e.split(r):[e];for(var n in s)if("string"==typeof s[n]){var a=s[n].split(i);2===a.length&&t(a[0],a[1])}}var fo=new oo(0,0,""),go="middle"===fo.align?"middle":"center";function po(e,t,i){var r=e;function s(){var t=ho(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=s(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=s(),n(),function(e,t){var r=new uo;co(e,(function(e,t){var s;switch(e){case"region":for(var n=i.length-1;n>=0;n--)if(i[n].id===t){r.set(e,i[n].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",go,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",go,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",go,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");var s=r.get("line","auto");"auto"===s&&-1===fo.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",go);var n=r.get("position","auto");"auto"===n&&50===fo.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function vo(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var mo=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new lo,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function i(){var e=t.buffer,i=0;for(e=vo(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;var r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var r="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var s=(r=i()).match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var n=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=i(),t.state){case"HEADER":/:/.test(r)?co(r,(function(e,t){}),/:/):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new oo(0,0,""),t.state="CUE",-1===r.indexOf("--\x3e")){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{po(r,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var a=-1!==r.indexOf("--\x3e");if(!r||a&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=r;continue;case"BADCUE":r||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},t.flush=function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this},e}(),yo=/\r\n|\n\r|\n|\r/g,Eo=function(e,t,i){return void 0===i&&(i=0),e.slice(i,i+t.length)===t};function So(e,t,i){return Ea(e.toString())+Ea(t.toString())+Ea(i)}var To="stpp.ttml.im1t",_o=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Lo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,bo={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ao(e,t,i,r){var s=ce(new Uint8Array(e),["mdat"]);if(0!==s.length){var a,o,l,h=s.map((function(e){return q(e)})),u=(a=t.baseTime,1,void 0===(o=t.timescale)&&(o=1),void 0===l&&(l=!1),ys(a,1,1/o,l));try{h.forEach((function(e){return i(function(e,t){var i=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((function(e,t){return e[t]=i.getAttribute("ttp:"+t)||r[t],e}),{}),a="preserve"!==i.getAttribute("xml:space"),o=Ro(Io(i,"styling","style")),l=Ro(Io(i,"layout","region")),h=Io(i,"body","[begin]");return[].map.call(h,(function(e){var i=Po(e,a);if(!i||!e.hasAttribute("begin"))return null;var r=wo(e.getAttribute("begin"),s),h=wo(e.getAttribute("dur"),s),u=wo(e.getAttribute("end"),s);if(null===r)throw Do(e);if(null===u){if(null===h)throw Do(e);u=r+h}var d=new oo(r-t,u-t,i);d.id=So(d.startTime,d.endTime,d.text);var c=function(e,t,i){var r="http://www.w3.org/ns/ttml#styling",s=null,n=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return n&&i.hasOwnProperty(n)&&(s=i[n]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((function(i,n){var a=ko(t,r,n)||ko(e,r,n)||ko(s,r,n);return a&&(i[n]=a),i}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),f=c.textAlign;if(f){var g=bo[f];g&&(d.lineAlign=g),d.align=f}return n(d,c),d})).filter((function(e){return null!==e}))}(e,u))}))}catch(e){r(e)}}else r(new Error("Could not parse IMSC1 mdat"))}function Io(e,t,i){var r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Ro(e){return e.reduce((function(e,t){var i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function Po(e,t){return[].slice.call(e.childNodes).reduce((function(e,i,r){var s;return"br"===i.nodeName&&r?e+"\n":null!=(s=i.childNodes)&&s.length?Po(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function ko(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Do(e){return new Error("Could not parse ttml timestamp "+e)}function wo(e,t){if(!e)return null;var i=ho(e);return null===i&&(_o.test(e)?i=function(e,t){var i=_o.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):Lo.test(e)&&(i=function(e,t){var i=Lo.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}var Co=function(){function e(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}var t=e.prototype;return t.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},t.newCue=function(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}(),Mo=function(){function e(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={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(I.FRAG_LOADING,this.onFragLoading,this),e.on(I.FRAG_LOADED,this.onFragLoaded,this),e.on(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=function(){var e=this.hls;e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(I.FRAG_LOADING,this.onFragLoading,this),e.off(I.FRAG_LOADED,this.onFragLoaded,this),e.off(I.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(I.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(I.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(I.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){var e=new Co(this,"textTrack1"),t=new Co(this,"textTrack2"),i=new Co(this,"textTrack3"),r=new Co(this,"textTrack4");this.cea608Parser1=new no(1,e,t),this.cea608Parser2=new no(3,i,r)},t.addCues=function(e,t,i,r,s){for(var n,a,o,l,h=!1,u=s.length;u--;){var d=s[u],c=(n=d[0],a=d[1],o=t,l=i,Math.min(a,l)-Math.max(n,o));if(c>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],i),h=!0,c/(i-t)>.5))return}if(h||s.push([t,i]),this.config.renderTextTracksNatively){var f=this.captionsTracks[e];this.Cues.newCue(f,t,i,r)}else{var g=this.Cues.newCue(null,t,i,r);this.hls.trigger(I.CUES_PARSED,{type:"captions",cues:g,track:e})}},t.onInitPtsFound=function(e,t){var i=this,r=t.frag,s=t.id,n=t.initPTS,a=t.timescale,o=t.trackId,l=this.unparsedVttFrags;s===w&&(this.initPTS[r.cc]={baseTime:n,timescale:a,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach((function(e){i.initPTS[e.frag.cc]?i.onFragLoaded(I.FRAG_LOADED,e):i.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))},t.getExistingTrack=function(e,t){var i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var s=i.textTracks[r];if(xo(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null},t.createCaptionsTrack=function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)},t.createNativeTrack=function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,i=this.captionsTracks,r=this.media,s=t[e],n=s.label,a=s.languageCode,o=this.getExistingTrack(n,a);if(o)i[e]=o,Ua(i[e]),Na(i[e],r);else{var l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}},t.createNonNativeTrack=function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}},t.createTextTrack=function(e,t,i){var r=this.media;if(r)return r.addTextTrack(e,t,i)},t.onMediaAttaching=function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()},t.onMediaDetaching=function(e,t){var i=!!t.transferMedia;if(this.media=null,!i){var r=this.captionsTracks;Object.keys(r).forEach((function(e){Ua(r[e]),delete r[e]})),this.nonNativeCaptionsTracks={}}},t.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},t._cleanTracks=function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var i=0;i<t.length;i++)Ua(t[i])}},t.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks||[],s=r.some((function(e){return e.textCodec===To}));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Ys(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var n=this.media,a=n?Ha(n.textTracks):null;if(this.tracks.forEach((function(e,t){var r;if(a){for(var s=null,n=0;n<a.length;n++)if(a[n]&&xo(a[n],e)){s=a[n],a[n]=null;break}s&&(r=s)}if(r)Ua(r);else{var o=Oo(e);(r=i.createTextTrack(o,e.name,e.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)})),null!=a&&a.length){var o=a.filter((function(e){return null!==e})).map((function(e){return e.label}));o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: "+o.join(", ")+". Replace media element for each source to clear TextTracks and captions menu.")}}else if(this.tracks.length){var l=this.tracks.map((function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}}));this.hls.trigger(I.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}},t.onManifestLoaded=function(e,t){var i=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var r="textTrack"+t[1],s=i.captionsProperties[r];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)}}))},t.closedCaptionsForLevel=function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]},t.onFragLoading=function(e,t){if(this.enabled&&t.frag.type===w){var i,r,s=this.cea608Parser1,n=this.cea608Parser2,a=this.lastSn,o=t.frag,l=o.cc,h=o.sn,u=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;s&&n&&(h!==a+1||h===a&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),n.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=u}},t.onFragLoaded=function(e,t){var i=t.frag,r=t.payload;if(i.type===M)if(r.byteLength){var s=i.decryptdata,n="stats"in t;if(null==s||!s.encrypted||n){var a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===To?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})},t._parseIMSC1=function(e,t){var i=this,r=this.hls;Ao(t,this.initPTS[e.cc],(function(t){i._appendCues(t,e.level),r.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(function(t){r.logger.log("Failed to parse IMSC1: "+t),r.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))},t._parseVTTs=function(e){var t,i=this,r=e.frag,s=e.payload,n=this.initPTS,a=this.unparsedVttFrags,o=n.length-1;if(n[r.cc]||-1!==o){var l=this.hls;!function(e,t,i,r,s,n,a){var o,l,h,u=new mo,d=q(new Uint8Array(e)).trim().replace(yo,"\n").split("\n"),c=[],f=t?(o=t.baseTime,void 0===(l=t.timescale)&&(l=1),ys(o,9e4,1/l)):0,g="00:00.000",p=0,v=0,m=!0;u.oncue=function(e){var n=i[r],a=i.ccOffset,o=(p-f)/9e4;if(null!=n&&n.new&&(void 0!==v?a=i.ccOffset=n.start:function(e,t,i){var r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=r.start-s.start,r.new=!1,s=e[(r=s).prevCC]}e.presentationOffset=i}(i,r,o)),o){if(!t)return void(h=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}var l=e.endTime-e.startTime,u=bs(9e4*(e.startTime+a-v),9e4*s)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);var d=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(d)),e.id||(e.id=So(e.startTime,e.endTime,d)),e.endTime>0&&c.push(e)},u.onparsingerror=function(e){h=e},u.onflush=function(){h?a(h):n(c)},d.forEach((function(e){if(m){if(Eo(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((function(e){Eo(e,"LOCAL:")?g=e.slice(6):Eo(e,"MPEGTS:")&&(p=parseInt(e.slice(7)))}));try{v=function(e){var t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(T(t)&&T(i)&&T(r)&&T(s)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*i,(t+=6e4*r)+36e5*s}(g)/1e3}catch(e){h=e}return}""===e&&(m=!1)}u.parse(e+"\n")})),u.flush()}(null!=(t=r.initSegment)&&t.data?Te(r.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(function(e){i._appendCues(e,r.level),l.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(function(t){var n="Missing initPTS for VTT MPEGTS"===t.message;n?a.push(e):i._fallbackToIMSC1(r,s),l.logger.log("Failed to parse VTT cue: "+t),n&&o>r.cc||l.trigger(I.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}else a.push(e)},t._fallbackToIMSC1=function(e,t){var i=this,r=this.tracks[e.level];r.textCodec||Ao(t,this.initPTS[e.cc],(function(){r.textCodec=To,i._parseIMSC1(e,t)}),(function(){r.textCodec="wvtt"}))},t._appendCues=function(e,t){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach((function(e){return Ba(r,e)}))}else{var s=this.tracks[t];if(!s)return;var n=s.default?"default":"subtitles"+t;i.trigger(I.CUES_PARSED,{type:"subtitles",cues:e,track:n})}},t.onFragDecrypted=function(e,t){t.frag.type===M&&this.onFragLoaded(I.FRAG_LOADED,t)},t.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},t.onFragParsingUserdata=function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var i=t.frag,r=t.samples;if(i.type!==w||"NONE"!==this.closedCaptionsForLevel(i))for(var s=0;s<r.length;s++){var n=r[s].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();var a=this.extractCea608Data(n);this.cea608Parser1.addData(r[s].pts,a[0]),this.cea608Parser2.addData(r[s].pts,a[1])}}}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,s=t.endOffsetSubtitles,n=t.type,a=this.media;if(a&&!(a.currentTime<r)){if(!n||"video"===n){var o=this.captionsTracks;Object.keys(o).forEach((function(e){return Ga(o[e],i,r)}))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==s){var l=this.textTracks;Object.keys(l).forEach((function(e){return Ga(l[e],i,s)}))}}},t.extractCea608Data=function(e){for(var t=[[],[]],i=31&e[0],r=2,s=0;s<i;s++){var n=e[r++],a=127&e[r++],o=127&e[r++];if((0!==a||0!==o)&&4&n){var l=3&n;0!==l&&1!==l||(t[l].push(a),t[l].push(o))}}return t},e}();function Oo(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function xo(e,t){return!!e&&e.kind===Oo(t)&&Xs(t,e)}var Fo=/\s/,No={newCue:function(e,t,i,r){for(var s,n,a,o,l,h=[],u=self.VTTCue||self.TextTrackCue,d=0;d<r.rows.length;d++)if(a=!0,o=0,l="",!(s=r.rows[d]).isEmpty()){for(var c,f=0;f<s.chars.length;f++)Fo.test(s.chars[f].uchar)&&a?o++:(l+=s.chars[f].uchar,a=!1);s.cueStartTime=t,t===i&&(i+=1e-4),o>=16?o--:o++;var g=vo(l.trim()),p=So(t,i,g);null!=e&&null!=(c=e.cues)&&c.getCueById(p)||((n=new u(t,i,g)).id=p,n.line=d+1,n.align="left",n.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(n))}return e&&h.length&&(h.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),h.forEach((function(t){return Ba(e,t)}))),h}},Bo=/(\d+)-(\d+)\/(\d+)/,Uo=function(){function e(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||Go,this.controller=new self.AbortController,this.stats=new z}var t=e.prototype;return t.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},t.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},t.load=function(e,t,i){var r=this,s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();var a=function(e,t){var i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(n({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(e,this.controller.signal),o="arraybuffer"===e.responseType,l=o?"byteLength":"length",h=t.loadPolicy,u=h.maxTimeToFirstByteMs,d=h.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&T(u)?u:d,this.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(s,e,r.response))}),t.timeout),(Os(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(i){var n;r.response=r.loader=i;var a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(r.requestTimeout),t.timeout=d,r.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(s,e,r.response))}),d-(a-s.loading.start)),!i.ok){var l=i.status,h=i.statusText;throw new Ho(h||"fetch, bad network response",l,i)}s.loading.first=a,s.total=function(e){var t=e.get("Content-Range");if(t){var i=function(e){var t=Bo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(T(i))return i}var r=e.get("Content-Length");if(r)return parseInt(r)}(i.headers)||s.total;var u=null==(n=r.callbacks)?void 0:n.onProgress;return u&&T(t.highWaterMark)?r.loadProgressively(i,s,e,t.highWaterMark,u):o?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((function(i){var n,a,o=r.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);var h=i[l];h&&(s.loaded=s.total=h);var u={url:o.url,data:i,code:o.status},d=null==(n=r.callbacks)?void 0:n.onProgress;d&&!T(t.highWaterMark)&&d(s,e,i,o),null==(a=r.callbacks)||a.onSuccess(u,s,e,o)})).catch((function(t){var i;if(self.clearTimeout(r.requestTimeout),!s.aborted){var n=t&&t.code||0,a=t?t.message:null;null==(i=r.callbacks)||i.onError({code:n,text:a},e,t?t.details:null,s)}}))},t.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},t.loadProgressively=function(e,t,i,r,s){void 0===r&&(r=0);var n=new dr,a=e.body.getReader(),o=function(){return a.read().then((function(a){if(a.done)return n.dataLength&&s(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return t.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(t,i,n.flush().buffer,e)):s(t,i,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},e}();function Go(e,t){return new self.Request(e.url,t)}var Ho=function(e){function t(t,i,r){var s;return(s=e.call(this,t)||this).code=void 0,s.details=void 0,s.code=i,s.details=r,s}return o(t,e),t}(f(Error)),Ko=/^age:\s*[\d.]+\s*$/im,Vo=function(){function e(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 z,this.retryDelay=0}var t=e.prototype;return t.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},t.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},t.load=function(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()},t.loadInternal=function(){var e=this,t=this.config,i=this.context;if(t&&i){var r=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;var n=this.xhrSetup;n?Promise.resolve().then((function(){if(e.loader===r&&!e.stats.aborted)return n(r,i.url)})).catch((function(t){if(e.loader===r&&!e.stats.aborted)return r.open("GET",i.url,!0),n(r,i.url)})).then((function(){e.loader!==r||e.stats.aborted||e.openAndSendXhr(r,i,t)})).catch((function(t){var n;null==(n=e.callbacks)||n.onError({code:r.status,text:t.message},i,r,s)})):this.openAndSendXhr(r,i,t)}},t.openAndSendXhr=function(e,t,i){e.readyState||e.open("GET",t.url,!0);var r=t.headers,s=i.loadPolicy,n=s.maxTimeToFirstByteMs,a=s.maxLoadTimeMs;if(r)for(var 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&&T(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()},t.readystatechange=function(){var e=this.context,t=this.loader,i=this.stats;if(e&&t){var r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var n=t.status,a="text"===t.responseType?t.responseText:null;if(n>=200&&n<300){var o=null!=a?a:t.response;if(null!=o){var l,h;i.loading.end=Math.max(self.performance.now(),i.loading.first);var u="arraybuffer"===t.responseType?o.byteLength:o.length;i.loaded=i.total=u,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(i,e,o,t);var c={url:t.responseURL,data:o,code:n};return void(null==(h=this.callbacks)||h.onSuccess(c,i,e,t))}}var f,g=s.loadPolicy.errorRetry;Lt(g,i.retry,!1,{url:e.url,data:void 0,code:n})?this.retry(g):(V.error(n+" while loading "+e.url),null==(f=this.callbacks)||f.onError({code:n,text:t.statusText},e,t,i))}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(Lt(e,this.stats.retry,!0))this.retry(e);else{var t;V.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,i=this.stats;this.retryDelay=Tt(e,i.retry),i.retry++,V.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?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)},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&Ko.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},e}(),$o=u(u({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:Vo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:dt,bufferController:rn,capLevelController:an,errorController:At,fpsController:ya,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:_i,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},{cueHandler:No,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:xa,subtitleTrackController:Ka,timelineController:Mo,audioStreamController:qs,audioTrackController:Qs,emeController:fa,cmcdController:ha,contentSteeringController:ua,interstitialsController:Oa});function Wo(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Wo):Object.keys(e).reduce((function(t,i){return t[i]=Wo(e[i]),t}),{}):e}var qo=function(e){function t(t,i){var r;return(r=e.call(this,"gap-controller",t.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.media=null,r.mediaSource=void 0,r.nudgeRetry=0,r.stallReported=!1,r.stalled=null,r.moved=!1,r.seeking=!1,r.buffered={},r.lastCurrentTime=0,r.ended=0,r.waiting=0,r.onMediaPlaying=function(){r.ended=0,r.waiting=0},r.onMediaWaiting=function(){var e;null!=(e=r.media)&&e.seeking||(r.waiting=self.performance.now(),r.tick())},r.onMediaEnded=function(){var e;r.hls&&(r.ended=(null==(e=r.media)?void 0:e.currentTime)||1,r.hls.trigger(I.MEDIA_ENDED,{stalled:!1}))},r.hls=t,r.fragmentTracker=i,r.registerListeners(),r}o(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e&&(e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.BUFFER_APPENDED,this.onBufferAppended,this))},i.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.BUFFER_APPENDED,this.onBufferAppended,this))},i.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},i.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var i=this.media=t.media;ar(i,"playing",this.onMediaPlaying),ar(i,"waiting",this.onMediaWaiting),ar(i,"ended",this.onMediaEnded)},i.onMediaDetaching=function(e,t){this.clearInterval();var i=this.media;i&&(or(i,"playing",this.onMediaPlaying),or(i,"waiting",this.onMediaWaiting),or(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},i.onBufferAppended=function(e,t){this.buffered=t.timeRanges},i.tick=function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}},i.poll=function(e,t){var i,r,s=null==(i=this.hls)?void 0:i.config;if(s){var n=this.media;if(n){var a=n.seeking,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(h)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(I.MEDIA_ENDED,{stalled:!1})));if(jt.getBuffered(n).length){var u=jt.bufferInfo(n,e,0),d=u.nextStart||0,c=this.fragmentTracker;if(a&&c&&this.hls){var f=jo(this.hls.inFlightFragments,e),g=u.len>2,p=!d||f||d-e>2&&!c.getPartialFragment(e);if(g||p)return;this.moved=!1}var v=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(u.len>0||d))return;var m=Math.max(d,u.start||0)-e,y=null!=v&&v.live?2*v.targetduration:2,E=zo(e,c);if(m>0&&(m<=y||E))return void(n.paused||this._trySkipBufferHole(E))}var S=s.detectStallWithCurrentTimeMs,T=self.performance.now(),_=this.waiting,L=this.stalled;if(null===L){if(!(_>0&&T-_<S))return void(this.stalled=T);L=this.stalled=_}var b=T-L;if(!a&&(b>=S||_)&&this.hls){var A;if("ended"===(null==(A=this.mediaSource)?void 0:A.readyState)&&(null==v||!v.live)&&Math.abs(e-((null==v?void 0:v.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(I.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}var R=jt.bufferInfo(n,e,s.maxBufferHole);this._tryFixBufferStall(R,b,e)}else this.nudgeRetry=0}}}},i.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var i=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(i)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(I.STALL_RESOLVED,{})}},i.nudgeOnVideoHole=function(e,t){var i,r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){var s=jt.bufferedInfo(jt.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){var n=jt.timeRangesToArray(r),a=jt.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&a<n.length-1){var o=jt.bufferedInfo(n,e,0).bufferedIndex,l=n[a].end,h=n[a+1].start;if((-1===o||o>a)&&h-l<1&&e-l<2){var u=new Error("nudging playhead to flush pipeline after video hole. currentTime: "+e+" hole: "+l+" -> "+h+" buffered index: "+o);this.warn(u.message),this.media.currentTime+=1e-6;var d=zo(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var c=jt.bufferInfo(this.media,e,0);this.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:c.len,bufferInfo:c})}}}}},i._tryFixBufferStall=function(e,t,i){var r,s,n=this.fragmentTracker,a=this.media,o=null==(r=this.hls)?void 0:r.config;if(a&&n&&o){var l=null==(s=this.hls)?void 0:s.latestLevelDetails,h=zo(i,n);if((h||null!=l&&l.live&&i<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;var u=e.buffered,d=this.adjacentTraversal(e,i);(u&&u.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}},i.adjacentTraversal=function(e,t){var i=this.fragmentTracker,r=e.nextStart;if(i&&r){var s=i.getFragAtPos(t,w),n=i.getFragAtPos(r,w);if(s&&n)return n.sn-s.sn<2}return!1},i._reportStall=function(e){var t=this.hls,i=this.media,r=this.stallReported,s=this.stalled;if(!r&&null!==s&&i&&t){this.stallReported=!0;var n=new Error("Playback stalling at @"+i.currentTime+" due to low buffer ("+it(e)+")");this.warn(n.message),t.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:s}})}},i._trySkipBufferHole=function(e){var t,i=this.fragmentTracker,r=this.media,s=null==(t=this.hls)?void 0:t.config;if(!r||!i||!s)return 0;var n=r.currentTime,a=jt.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){var l=a.len<=s.maxBufferHole,h=a.len>0&&a.len<1&&r.readyState<3,u=o-n;if(u>0&&(l||h)){if(u>s.maxBufferHole){var d=!1;if(0===n){var c=i.getAppendedFrag(0,w);c&&o<c.end&&(d=!0)}if(!d&&e){var f;if(null==(f=this.hls.loadLevelObj)||!f.details)return 0;if(jo(this.hls.inFlightFragments,o))return 0;for(var g=!1,p=e.end;p<o;){var v=zo(p,i);if(!v){g=!0;break}p+=v.duration}if(g)return 0}}var m=Math.max(o+.05,n+.1);if(this.warn("skipping hole, adjusting currentTime from "+n+" to "+m),this.moved=!0,r.currentTime=m,null==e||!e.gap){var y=new Error("fragment loaded with buffer holes, seeking from "+n+" to "+m),E={type:b.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:y,reason:y.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?E.part=e:E.frag=e),this.hls.trigger(I.ERROR,E)}return m}}return 0},i._tryNudgeBuffer=function(e){var t=this.hls,i=this.media,r=this.nudgeRetry,s=null==t?void 0:t.config;if(!i||!s)return 0;var n=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){var a=n+(r+1)*s.nudgeOffset,o=new Error("Nudging 'currentTime' from "+n+" to "+a);this.warn(o.message),i.currentTime=a,t.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{var l=new Error("Playhead still not moving while enough data buffered @"+n+" after "+s.nudgeMaxRetry+" nudges");this.error(l.message),t.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}},r(t,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}($t);function jo(e,t){var i=Yo(e.main);if(i&&i.start<=t)return i;var r=Yo(e.audio);return r&&r.start<=t?r:null}function Yo(e){if(!e)return null;switch(e.state){case lr.IDLE:case lr.STOPPED:case lr.ENDED:case lr.ERROR:return null}return e.frag}function zo(e,t){return t.getAppendedFrag(e,w)||t.getPartialFragment(e)}function Xo(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Qo(e,t,i,r,s){var n=new e(t,i,"");try{n.value=r,s&&(n.type=s)}catch(a){n=new e(t,i,it(s?u({type:s},r):r))}return n}var Jo=function(){var e=Xo();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),Zo=function(){function e(e){var t=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){t.hls&&t.hls.trigger(I.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}var t=e.prototype;return t.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null},t._registerListeners=function(){var e=this.hls;e&&(e.on(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},t._unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(I.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},t.onMediaAttaching=function(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)},t.onMediaAttached=function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)},t.onMediaDetaching=function(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&Ua(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})},t.onManifestLoading=function(){this.dateRangeCuesAppended={}},t.createTrack=function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t},t.getID3Track=function(e){if(this.media){for(var t=0;t<e.length;t++){var i=e[t];if("metadata"===i.kind&&"id3"===i.label)return Na(i,this.media),i}return this.media.addTextTrack("metadata","id3")}},t.onFragParsingMetadata=function(e,t){if(this.media&&this.hls){var i=this.hls.config,r=i.enableEmsgMetadataCues,s=i.enableID3MetadataCues;if(r||s){var n=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=Xo();if(a)for(var o=0;o<n.length;o++){var l=n[o].type;if((l!==Or.emsg||r)&&s){var h=Dr(n[o].data),u=n[o].pts,d=u+n[o].duration;d>Jo&&(d=Jo),d-u<=0&&(d=u+.25);for(var c=0;c<h.length;c++){var f=h[c];if(!wr(f)){this.updateId3CueEnds(u,l);var g=Qo(a,u,d,f,l);g&&this.id3Track.addCue(g)}}}}}}},t.updateId3CueEnds=function(e,t){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var s=r.length;s--;){var n=r[s];n.type===t&&n.startTime<e&&n.endTime===Jo&&(n.endTime=e)}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,s=t.type,n=this.id3Track,a=this.hls;if(a){var o=a.config,l=o.enableEmsgMetadataCues,h=o.enableID3MetadataCues;n&&(l||h)&&Ga(n,i,r,"audio"===s?function(e){return e.type===Or.audioId3&&h}:"video"===s?function(e){return e.type===Or.emsg&&l}:function(e){return e.type===Or.audioId3&&h||e.type===Or.emsg&&l})}},t.onLevelUpdated=function(e,t){var i=t.details;this.updateDateRangeCues(i,!0)},t.onLevelPtsUpdated=function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var i=this;if(this.hls&&this.media){var r=this.hls.config,s=r.assetPlayerId,n=r.timelineOffset,a=r.enableDateRangeMetadataCues,o=r.interstitialsController;if(a){var l=Xo();if(s&&n&&!o){var h=e.fragmentStart,u=e.fragmentEnd,d=this.assetCue;d?(d.startTime=h,d.endTime=u):l&&(d=this.assetCue=Qo(l,h,u,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var c,f=this.id3Track,g=e.dateRanges,p=Object.keys(g),v=this.dateRangeCuesAppended;if(f&&t)if(null!=(c=f.cues)&&c.length)for(var m=Object.keys(v).filter((function(e){return!p.includes(e)})),y=function(){var e,t=m[E],r=null==(e=v[t])?void 0:e.cues;delete v[t],r&&Object.keys(r).forEach((function(e){var t=r[e];if(t){t.removeEventListener("enter",i.onEventCueEnter);try{f.removeCue(t)}catch(e){}}}))},E=m.length;E--;)y();else v=this.dateRangeCuesAppended={};var S=e.fragments[e.fragments.length-1];if(0!==p.length&&T(null==S?void 0:S.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var _=function(){var e=p[L],t=g[e],r=t.startTime,s=v[e],n=(null==s?void 0:s.cues)||{},a=(null==s?void 0:s.durationKnown)||!1,h=Jo,u=t.duration;if(t.endDate&&null!==u)h=r+u,a=!0;else if(t.endOnNext&&!a){var d=p.reduce((function(e,i){if(i!==t.id){var r=g[i];if(r.class===t.class&&r.startDate>t.startDate&&(!e||t.startDate<e.startDate))return r}return e}),null);d&&(h=d.startTime,a=!0)}for(var c,f=Object.keys(t.attr),m=0;m<f.length;m++){var y=f[m];if("ID"!==(c=y)&&"CLASS"!==c&&"CUE"!==c&&"START-DATE"!==c&&"DURATION"!==c&&"END-DATE"!==c&&"END-ON-NEXT"!==c){var E=n[y];if(E)!a||null!=s&&s.durationKnown?Math.abs(E.startTime-r)>.01&&(E.startTime=r,E.endTime=h):E.endTime=h;else if(l){var S=t.attr[y];ii(y)&&(S=Y(S));var T=Qo(l,r,h,{key:y,data:S},Or.dateRange);T&&(T.id=e,i.id3Track.addCue(T),n[y]=T,o&&("X-ASSET-LIST"!==y&&"X-ASSET-URL"!==y||T.addEventListener("enter",i.onEventCueEnter)))}}}v[e]={cues:n,dateRange:t,durationKnown:a}},L=0;L<p.length;L++)_()}}}}},e}(),el=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e=t.media,i=t.levelDetails;if(e&&i){t.currentTime=e.currentTime;var r=t.computeLatency();if(null!==r){t._latency=r;var s=t.config,n=s.lowLatencyMode,a=s.maxLiveSyncPlaybackRate;if(n&&1!==a&&i.live){var o=t.targetLatency;if(null!==o){var l=r-o;if(l<Math.min(t.maxLatency,o+i.targetduration)&&l>.05&&t.forwardBufferLength>1){var h=Math.min(2,Math.max(1,a)),u=Math.round(2/(1+Math.exp(-.75*l-t.edgeStalled))*20)/20,d=Math.min(h,Math.max(1,u));t.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&t.changeMediaPlaybackRate(e,1)}}}}},this.hls=e,this.config=e.config,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},t.registerListeners=function(){var e=this.hls;e&&(e.on(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(I.ERROR,this.onError,this))},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(I.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(I.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(I.ERROR,this.onError,this))},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)},t.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)},t.onManifestLoading=function(){this._latency=null,this.stallCount=0},t.onLevelUpdated=function(e,t){var i=t.details;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onError=function(e,t){var i;t.details===A.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(r=this.targetLatency)?void 0:r.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+e.playbackRate+" to "+t),e.playbackRate=t)},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},r(e,[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,i=e.partHoldBack,r=e.targetduration,s=this.config,n=s.liveSyncDuration,a=s.liveSyncDurationCount,o=s.lowLatencyMode,l=this.hls.userConfig,h=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*r);var u=r;return h+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var i=this.levelDetails;if(null===i)return null;var r=i.edge,s=e-t-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}}])}(),tl=function(e){function t(t,i){var r;return(r=e.call(this,t,"level-controller")||this)._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,r._registerListeners(),r}o(t,e);var i=t.prototype;return i._registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(I.LEVEL_LOADED,this.onLevelLoaded,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(I.FRAG_BUFFERED,this.onFragBuffered,this),e.on(I.ERROR,this.onError,this)},i._unregisterListeners=function(){var e=this.hls;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(I.LEVEL_LOADED,this.onLevelLoaded,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(I.FRAG_BUFFERED,this.onFragBuffered,this),e.off(I.ERROR,this.onError,this)},i.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},i.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},i.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},i.onManifestLoading=function(e,t){this.resetLevels()},i.onManifestLoaded=function(e,t){var i=this,r=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,h=!1;t.levels.forEach((function(e){var t=e.attrs,u=e.audioCodec,d=e.videoCodec;u&&(e.audioCodec=u=Be(u,r)||void 0),d&&(d=e.videoCodec=function(e){for(var t=e.split(","),i=0;i<t.length;i++){var r=t[i].split(".");r.length>2&&"avc1"===r[0]&&(t[i]="avc1."+parseInt(r[1]).toString(16)+("000"+parseInt(r[2]).toString(16)).slice(-4))}return t.join(",")}(d));var c=e.width,f=e.height,g=e.unknownCodecs,p=(null==g?void 0:g.length)||0;if(o||(o=!(!c||!f)),l||(l=!!d),h||(h=!!u),p||u&&!i.isAudioSupported(u)||d&&!i.isVideoSupported(d))i.log('Some or all CODECS not supported "'+t.CODECS+'"');else{var v=t.CODECS,m=t["FRAME-RATE"],y=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],S=t.RESOLUTION,T=t["VIDEO-RANGE"],_=(E||".")+"-"+e.bitrate+"-"+S+"-"+m+"-"+v+"-"+T+"-"+y;if(n[_])if(n[_].uri===e.url||e.attrs["PATHWAY-ID"])n[_].addGroupId("audio",t.AUDIO),n[_].addGroupId("text",t.SUBTITLES);else{var L=a[_]+=1;e.attrs["PATHWAY-ID"]=new Array(L+1).join(".");var b=i.createLevel(e);n[_]=b,s.push(b)}else{var A=i.createLevel(e);n[_]=A,a[_]=1,s.push(A)}}})),this.filterAndSortMediaOptions(s,t,o,l,h)},i.createLevel=function(e){var t=new et(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){var r=new Error('SUPPLEMENTAL-CODECS not supported "'+i.videoCodec+'"');this.log(r.message),t.supportedResult=qe(r,[])}return t},i.isAudioSupported=function(e){return we(e,"audio",this.hls.config.preferManagedMediaSource)},i.isVideoSupported=function(e){return we(e,"video",this.hls.config.preferManagedMediaSource)},i.filterAndSortMediaOptions=function(e,t,i,r,s){var n,a=this,o=[],l=[],h=e,u=(null==(n=t.stats)?void 0:n.parsing)||{};if((i||r)&&s&&(h=h.filter((function(e){var t,i=e.videoCodec,r=e.videoRange,s=e.width,n=e.height;return(!!i||!(!s||!n))&&!!(t=r)&&Qe.indexOf(t)>-1}))),0===h.length)return Promise.resolve().then((function(){if(a.hls){var e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i="one or more CODECS in variant not supported: "+it(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,i){return i.indexOf(e)===t}))),a.warn(i),e+=" ("+i+")");var r=new Error(e);a.hls.trigger(I.ERROR,{type:b.MEDIA_ERROR,details:A.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}})),void(u.end=performance.now());t.audioTracks&&il(o=t.audioTracks.filter((function(e){return!e.audioCodec||a.isAudioSupported(e.audioCodec)}))),t.subtitles&&il(l=t.subtitles);var d=h.slice(0);h.sort((function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Qe.indexOf(e.videoRange)-Qe.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var r=Oe(e.videoCodec),s=Oe(t.videoCodec);if(r!==s)return s-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var n=xe(e.codecSet),a=xe(t.codecSet);if(n!==a)return a-n}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var c=d[0];if(this.steering&&(h=this.steering.filterParsedLevels(h)).length!==d.length)for(var f=0;f<d.length;f++)if(d[f].pathwayId===h[0].pathwayId){c=d[f];break}this._levels=h;for(var g=0;g<h.length;g++)if(h[g]===c){var p;this._firstLevel=g;var v=c.bitrate,m=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+h.length+" level(s) found, first bitrate: "+v),void 0===(null==(p=this.hls.userConfig)?void 0:p.abrEwmaDefaultEstimate)){var y=Math.min(v,this.hls.config.abrEwmaDefaultEstimateMax);y>m&&m===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}var E=s&&!r,S=this.hls.config,T=!(!S.audioStreamController||!S.audioTrackController),_={levels:h,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:T&&!E&&o.some((function(e){return!!e.url}))};u.end=performance.now(),this.hls.trigger(I.MANIFEST_PARSED,_)},i.onError=function(e,t){!t.fatal&&t.context&&t.context.type===P&&t.context.level===this.level&&this.checkRetry(t)},i.onFragBuffered=function(e,t){var i=t.frag;if(void 0!==i&&i.type===w){var r=i.elementaryStreams;if(!Object.keys(r).some((function(e){return!!r[e]})))return;var s=this._levels[i.level];null!=s&&s.loadError&&(this.log("Resetting level error count of "+s.loadError+" on frag buffered"),s.loadError=0)}},i.onLevelLoaded=function(e,t){var i,r,s=t.level,n=t.details,a=t.levelInfo;if(!a)return this.warn("Invalid level index "+s),void(null!=(r=t.deliveryDirectives)&&r.skip&&(n.deltaUpdateFailed=!0));if(a===this.currentLevel||t.withoutMultiVariant){0===a.fragmentError&&(a.loadError=0);var o=a.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(s,t,o)}else null!=(i=t.deliveryDirectives)&&i.skip&&(n.deltaUpdateFailed=!0)},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=this.getUrlWithDirectives(t.uri,i),s=this.currentLevelIndex,n=t.attrs["PATHWAY-ID"],a=t.details,o=null==a?void 0:a.age;this.log("Loading level index "+s+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(n?" Pathway "+n:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+r),this.hls.trigger(I.LEVEL_LOADING,{url:r,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||null})},i.removeLevel=function(e){var t,i=this;if(1!==this._levels.length){var r=this._levels.filter((function(t,r){return r!==e||(i.steering&&i.steering.removeLevel(t),t===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));Ji(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var s=r.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(I.LEVELS_UPDATED,{levels:r})}},i.onLevelsUpdated=function(e,t){var i=t.levels;this._levels=i},i.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,i=e.maxAutoLevel,r=e.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(I.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))},r(t,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}var s=this.currentLevelIndex,n=this.currentLevel,a=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,s!==e||!n||a!==l){this.log("Switching to level "+e+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+s+(a?" with Pathway "+a:""));var h={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(I.LEVEL_SWITCHING,h);var u=o.details;if(!u||u.live){var d=this.switchParams(o.uri,null==n?void 0:n.details,u);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),i=e.filter((function(e){return-1!==t.indexOf(e)}));if(e.length<1)return void this.warn("pathwayPriority "+e+" should contain at least one pathway from list: "+t);this.steering.pathwayPriority=i}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])}(js);function il(e){var t={};e.forEach((function(e){var i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}function rl(){return self.SourceBuffer||self.WebKitSourceBuffer}function sl(){if(!$())return!1;var e=rl();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var nl=function(e){function t(t,i,r){var s;return(s=e.call(this,t,i,r,"stream-controller",w)||this).audioCodecSwap=!1,s.level=-1,s._forceStartLoad=!1,s._hasEnoughToStart=!1,s.altAudio=0,s.audioOnly=!1,s.fragPlaying=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s.onMediaPlaying=function(){s.tick()},s.onMediaSeeked=function(){var e=s.media,t=e?e.currentTime:null;if(null!==t&&T(t)&&(s.log("Media seeked to "+t.toFixed(3)),s.getBufferedFrag(t))){var i=s.getFwdBufferInfoAtPos(e,t,w,0);null!==i&&0!==i.len?s.tick():s.warn("Main forward buffer length at "+t+' on "seeked" event '+(i?i.len:"empty")+")")}},s.registerListeners(),s}o(t,e);var i=t.prototype;return i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(I.MANIFEST_PARSED,this.onManifestParsed,this),t.on(I.LEVEL_LOADING,this.onLevelLoading,this),t.on(I.LEVEL_LOADED,this.onLevelLoaded,this),t.on(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(I.BUFFER_CREATED,this.onBufferCreated,this),t.on(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(I.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(I.MANIFEST_PARSED,this.onManifestParsed,this),t.off(I.LEVEL_LOADED,this.onLevelLoaded,this),t.off(I.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(I.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(I.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(I.BUFFER_CREATED,this.onBufferCreated,this),t.off(I.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(I.FRAG_BUFFERED,this.onFragBuffered,this)},i.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},i.startLoad=function(e,t){if(this.levels){var i=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var s=r.startLevel;-1===s&&(r.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=r.firstAutoLevel),r.nextLoadLevel=s,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i),this.state=lr.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=lr.STOPPED},i.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},i.doTick=function(){switch(this.state){case lr.WAITING_LEVEL:var e=this.levels,t=this.level,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=lr.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=lr.IDLE;break}break;case lr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===lr.IDLE&&this.doTickIdle(),this.onTickEnd()},i.onTickEnd=function(){var t;e.prototype.onTickEnd.call(this),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},i.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,i=this.levels,r=this.media;if(null!==t&&(r||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var s=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=i&&i[s]){var n=i[s],a=this.getMainFwdBufferInfo();if(null!==a){var o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){var l={};return 2===this.altAudio&&(l.type="video"),this.hls.trigger(I.BUFFER_EOS,l),void(this.state=lr.ENDED)}if(this.buffering){e.loadLevel!==s&&-1===e.manualLevel&&this.log("Adapting to level "+s+" from level "+this.level),this.level=e.nextLoadLevel=s;var h=n.details;if(!h||this.state===lr.WAITING_LEVEL||this.waitForLive(n))return this.level=s,this.state=lr.WAITING_LEVEL,void(this.startFragRequested=!1);var u=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(!(u>=d)){this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);var c=this.backtrackFragment?this.backtrackFragment.start:a.end,f=this.getNextFragment(c,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&ee(f)&&this.fragmentTracker.getState(f)!==Dt){var g,p=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,v=h.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?X:Q,y=(m===Q?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m,w)}f=this.getNextFragmentLoopLoading(f,h,a,w,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,c))}}}}}},i.loadFragment=function(t,i,r){var s=this.fragmentTracker.getState(t);s===Rt||s===kt?ee(t)?this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,i)):e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i):this.clearTrackerIfNeeded(t)},i.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,w)},i.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},i.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},i.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);var s=this.getLevelDetails();if(null!=s&&s.live){var n=this.getMainFwdBufferInfo();if(!n||n.len<2*s.targetduration)return}if(!t.paused&&e){var a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;i=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(t.currentTime+i);if(l){var h=this.followingBufferedFrag(l);if(h){this.abortCurrentFrag();var u=h.maxStartPTS?h.maxStartPTS:h.start,d=h.duration,c=Math.max(l.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},i.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case lr.KEY_LOADING:case lr.FRAG_LOADING:case lr.FRAG_LOADING_WAITING_RETRY:case lr.PARSING:case lr.PARSED:this.state=lr.IDLE}this.nextLoadPosition=this.getLoadPosition()},i.flushMainBuffer=function(t,i){e.prototype.flushMainBuffer.call(this,t,i,2===this.altAudio?"video":null)},i.onMediaAttached=function(t,i){e.prototype.onMediaAttached.call(this,t,i);var r=i.media;ar(r,"playing",this.onMediaPlaying),ar(r,"seeked",this.onMediaSeeked)},i.onMediaDetaching=function(t,i){var r=this.media;r&&(or(r,"playing",this.onMediaPlaying),or(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,e.prototype.onMediaDetaching.call(this,t,i),i.transferMedia||(this._hasEnoughToStart=!1)},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(I.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},i.onManifestParsed=function(e,t){for(var i,r,s=!1,n=!1,a=0;a<t.levels.length;a++){var o=t.levels[a].audioCodec;o&&(s=s||-1!==o.indexOf("mp4a.40.2"),n=n||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&n&&!("function"==typeof(null==(r=rl())||null==(i=r.prototype)?void 0:i.changeType)),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},i.onLevelLoading=function(e,t){if(this.levels&&this.state===lr.IDLE){var i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=lr.WAITING_LEVEL)}},i.onLevelLoaded=function(e,t){var i,r=this.levels,s=this.startFragRequested,n=t.level,a=t.details,o=a.totalduration;if(r){this.log("Level "+n+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+", cc ["+a.startCC+", "+a.endCC+"] duration:"+o);var l=t.levelInfo,h=this.fragCurrent;!h||this.state!==lr.FRAG_LOADING&&this.state!==lr.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();var u=0;if(a.live||null!=(i=l.details)&&i.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,s||this.setStartPosition(a,u),this.hls.trigger(I.LEVEL_UPDATED,{details:a,level:n}),this.state===lr.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=lr.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}else this.warn("Levels were reset while loading level "+n)},i.synchronizeToLiveEdge=function(e){var t=this.config,i=this.media;if(i){var r=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||s<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn("Playback: "+s.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+r.toFixed(3)),"buffered"===this.config.liveSyncMode){var h,u=jt.bufferInfo(i,r,0);if(null==(h=u.buffered)||!h.length)return void(i.currentTime=r);if(u.start<=s)return void(i.currentTime=r);var d=jt.bufferedInfo(u.buffered,s,0).nextStart;d&&(i.currentTime=d)}else i.currentTime=r}}},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,s=e.payload,n=this.levels;if(n){var a=n[i.level];if(a){var o=a.details;if(!o)return this.warn("Dropping fragment "+i.sn+" of level "+i.level+" after level details were reset"),void this.fragmentTracker.removeFragment(i);var l=a.videoCodec,h=o.PTSKnown||!o.live,u=null==(t=i.initSegment)?void 0:t.data,d=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Ws(this.hls,w,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,p=new Wt(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),v=this.initPTS[i.cc];c.push(s,u,d,l,i,r,o.totalduration,h,p,v)}else this.warn("Level "+i.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i.onAudioTrackSwitching=function(e,t){var i=this,r=this.hls,s=2===this.altAudio;if(ut(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.fragmentTracker.removeAllFragments(),r.once(I.BUFFER_FLUSHED,(function(){i.hls&&i.hls.trigger(I.AUDIO_TRACK_SWITCHED,t)})),void r.trigger(I.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(I.AUDIO_TRACK_SWITCHED,t)}},i.onAudioTrackSwitched=function(e,t){var i=ut(t.url,this.hls);if(i){var r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i?2:0,this.tick()},i.onBufferCreated=function(e,t){var i,r,s=t.tracks,n=!1;for(var a in s){var o=s[a];if("main"===o.id){if(r=a,i=o,"video"===a){var l=s[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log("Alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,s=i.type===w;if(s){if(this.fragContextChanged(i))return this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===lr.PARSED&&(this.state=lr.IDLE));var n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),ee(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}var a=this.media;a&&(!this._hasEnoughToStart&&jt.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())},i.onError=function(e,t){var i;if(t.fatal)this.state=lr.ERROR;else switch(t.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(w,t);break;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==lr.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==P||(this.state=lr.IDLE);break;case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case A.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},i.onFragLoadEmergencyAborted=function(){this.state=lr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==X||!this.altAudio){var r=(i===Q?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,i,w),this.tick())}},i.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels},i.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},i.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log("could not seek to "+i+", already seeking at "+t);var r=this.timelineOffset;r&&i&&(i+=r);var s=this.getLevelDetails(),n=jt.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0)))&&(this.log("adjusting start position by "+o+" to match buffer start"),i+=o,this.startPosition=i),t<i&&(this.log("seek to target start position "+i+" from current time "+t+" buffer start "+a),e.currentTime=i)}}},i._getAudioCodec=function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t},i._loadBitrateTestFrag=function(e,t){var i=this;e.bitrateTest=!0,this._doFragLoad(e,t).then((function(e){var r=i.hls,s=null==e?void 0:e.frag;if(s&&!i.fragContextChanged(s)){t.fragmentError=0,i.state=lr.IDLE,i.startFragRequested=!1,i.bitrateTest=!1;var n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(I.FRAG_LOADED,e),s.bitrateTest=!1}})).catch((function(t){i.state!==lr.STOPPED&&i.state!==lr.ERROR&&(i.warn(t),i.resetFragmentLoading(e))}))},i._handleTransmuxComplete=function(e){var t=this.playlistType,i=this.hls,r=e.remuxResult,s=e.chunkMeta,n=this.getCurrentContext(s);if(n){var a=n.frag,o=n.part,l=n.level,h=r.video,u=r.text,d=r.id3,c=r.initSegment,f=l.details,g=this.altAudio?void 0:r.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=lr.PARSING,c){var p=c.tracks;if(p){var v=a.initSegment||a;if(this.unhandledEncryptionError(c,a))return;this._bufferInitSegment(l,p,v,s),i.trigger(I.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:t,tracks:p})}var m=c.initPTS,y=c.timescale,E=this.initPTS[a.cc];if(T(m)&&(!E||E.baseTime!==m||E.timescale!==y)){var S=c.trackId;this.initPTS[a.cc]={baseTime:m,timescale:y,trackId:S},i.trigger(I.INIT_PTS_FOUND,{frag:a,id:t,initPTS:m,timescale:y,trackId:S})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);var _=f.fragments[a.sn-1-f.startSN],L=a.sn===f.startSN,b=!_||a.cc>_.cc;if(!1!==r.independent){var A=h.startPTS,R=h.endPTS,P=h.startDTS,k=h.endDTS;if(o)o.elementaryStreams[h.type]={startPTS:A,endPTS:R,startDTS:P,endDTS:k};else if(h.firstKeyFrame&&h.independent&&1===s.id&&!b&&(this.couldBacktrack=!0),h.dropped&&h.independent){var D=this.getMainFwdBufferInfo(),w=(D?D.end:this.getLoadPosition())+this.config.maxBufferHole,C=h.firstKeyFramePTS?h.firstKeyFramePTS:A;if(!L&&w<C-this.config.maxBufferHole&&!b)return void this.backtrack(a);b&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,R,a.start,k,!0)}else L&&A-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,A,R,P,k),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,s,L||b)}else{if(!L&&!b)return void this.backtrack(a);a.gap=!0}}if(g){var M=g.startPTS,O=g.endPTS,x=g.startDTS,F=g.endDTS;o&&(o.elementaryStreams[X]={startPTS:M,endPTS:O,startDTS:x,endDTS:F}),a.setElementaryStreamInfo(X,M,O,x,F),this.bufferFragmentData(g,a,o,s)}if(f&&null!=d&&d.samples.length){var N={id:t,frag:a,details:f,samples:d.samples};i.trigger(I.FRAG_PARSING_METADATA,N)}if(f&&u){var B={id:t,frag:a,details:f,samples:u.samples};i.trigger(I.FRAG_PARSING_USERDATA,B)}}}else this.resetWhenMissingContext(s)},i.logMuxedErr=function(e){this.warn((ee(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},i._bufferInitSegment=function(e,t,i,r){var s=this;if(this.state===lr.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));var n=t.audio,a=t.video,o=t.audiovideo;if(n){var l=e.audioCodec,h=Ue(n.codec,l);"mp4a"===h&&(h="mp4a.40.5");var u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h=-1!==h.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=n.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&-1===u.indexOf("firefox")&&(h="mp4a.40.5")}h&&-1!==h.indexOf("mp4a.40.5")&&-1!==u.indexOf("android")&&"audio/mpeg"!==n.container&&(h="mp4a.40.2",this.log("Android: force audio codec to "+h)),l&&l!==h&&this.log('Swapping manifest audio codec "'+l+'" for "'+h+'"'),n.levelCodec=h,n.id=w,this.log("Init audio buffer, container:"+n.container+", codecs[selected/level/parsed]=["+(h||"")+"/"+(l||"")+"/"+n.codec+"]"),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=w;var c=a.codec;if(4===(null==c?void 0:c.length))switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e"}this.log("Init video buffer, container:"+a.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+c+"]"+(a.codec!==c?" parsed-corrected="+a.codec:"")+(a.supplemental?" supplemental="+a.supplemental:"")),delete t.audiovideo}o&&(this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+e.codecs+"/"+o.codec+"]"),delete t.video,delete t.audio);var f=Object.keys(t);if(f.length){if(this.hls.trigger(I.BUFFER_CODECS,t),!this.hls)return;f.forEach((function(e){var n=t[e].initSegment;null!=n&&n.byteLength&&s.hls.trigger(I.BUFFER_APPENDING,{type:e,data:n,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}},i.getMainFwdBufferInfo=function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,w)},i.backtrack=function(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=lr.IDLE},i.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var i=e.currentTime;if(jt.isBuffered(e,i)?t=this.getAppendedFrag(i):jt.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;var r=this.fragPlaying,s=t.level;r&&t.sn===r.sn&&r.level===s||(this.fragPlaying=t,this.hls.trigger(I.FRAG_CHANGED,{frag:t}),r&&r.level===s||this.hls.trigger(I.LEVEL_SWITCHED,{level:s}))}}},r(t,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return T(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(T(t)){var i=this.getLevelDetails(),r=this.currentFrag||(i?ft(null,i.fragments,t):null);if(r){var s=r.programDateTime;if(null!==s){var n=s+1e3*(t-r.start);return new Date(n)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(hr),al=function(e){function t(t,i){var r;return(r=e.call(this,"key-loader",i)||this).config=void 0,r.keyIdToKeyInfo={},r.emeController=null,r.config=t,r}o(t,e);var i=t.prototype;return i.abort=function(e){for(var t in this.keyIdToKeyInfo){var i=this.keyIdToKeyInfo[t].loader;if(i){var r;if(e&&e!==(null==(r=i.context)?void 0:r.frag.type))return;i.abort()}}},i.detach=function(){for(var e in this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}},i.destroy=function(){for(var e in this.detach(),this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}},i.createKeyLoadError=function(e,t,i,r,s){return void 0===t&&(t=A.KEY_LOAD_ERROR),new Vt({type:b.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})},i.loadClear=function(e,t,i){var r=this;if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(var s,n=function(){var s=t[a];if(e.cc<=s.cc&&(!ee(e)||!ee(s)||e.sn<s.sn)||!i&&a==o-1)return{v:r.emeController.selectKeySystemFormat(s).then((function(e){if(r.emeController){s.setKeyFormat(e);var t=yi(e);return t?r.emeController.getKeySystemAccess([t]):void 0}}))}},a=0,o=t.length;a<o;a++)if(s=n())return s.v;if(this.config.requireKeySystemAccessOnStart){var l=Si(this.config);if(l.length)return this.emeController.getKeySystemAccess(l)}}return null},i.load=function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(i){return t.loadInternal(e,i)})):this.loadInternal(e)},i.loadInternal=function(e,t){var i,r;t&&e.setKeyFormat(t);var s=e.decryptdata;if(!s){var n=new Error(t?"Expected frag.decryptdata to be defined after setting format "+t:"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: "+(this.emeController&&this.config.emeEnabled)+")");return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,n))}var a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+a+'"')));var o=ol(s),l=this.keyIdToKeyInfo[o];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(r=l)&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then((function(t){var i=t.keyInfo;return s.key=i.decryptdata.key,{frag:e,keyInfo:i}}))}switch(this.log((this.keyIdToKeyInfo[o]?"Rel":"L")+"oading"+(s.keyId?" keyId: "+j(s.keyId):"")+" URI: "+s.uri+" from "+e.type+" "+e.level),l=this.keyIdToKeyInfo[o]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+s.method+'"')))}},i.loadKeyEME=function(e,t){var i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then((function(t){return e.mediaKeySessionContext=t,i}))).catch((function(i){throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i}))}return Promise.resolve(i)},i.loadKeyHTTP=function(e,t){var i=this,r=this.config,s=new(0,r.loader)(r);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((function(n,a){var o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,t,r,s){var o=r.frag,l=r.keyInfo,h=ol(l.decryptdata);if(!o.decryptdata||l!==i.keyIdToKeyInfo[h])return a(i.createKeyLoadError(o,A.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,l.loader=null,n({frag:o,keyInfo:l})},onError:function(e,r,s,n){i.resetLoader(r),a(i.createKeyLoadError(t,A.KEY_LOAD_ERROR,new Error("HTTP Error "+e.code+" loading key "+e.text),s,u({url:o.url,data:void 0},e)))},onTimeout:function(e,r,s){i.resetLoader(r),a(i.createKeyLoadError(t,A.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:function(e,r,s){i.resetLoader(r),a(i.createKeyLoadError(t,A.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,h,d)}))},i.resetLoader=function(e){var t=e.frag,i=e.keyInfo,r=e.url,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null);var n=ol(i.decryptdata)||r;delete this.keyIdToKeyInfo[n],s&&s.destroy()},t}(F);function ol(e){if(e.keyFormat!==pi){var t=e.keyId;if(t)return j(t)}return e.uri}function ll(e){switch(e.type){case k:return C;case D:return M;default:return w}}function hl(e,t){var i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}var ul=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){var e=this.hls;e.on(I.MANIFEST_LOADING,this.onManifestLoading,this),e.on(I.LEVEL_LOADING,this.onLevelLoading,this),e.on(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(I.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(I.MANIFEST_LOADING,this.onManifestLoading,this),e.off(I.LEVEL_LOADING,this.onLevelLoading,this),e.off(I.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(I.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(I.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.createInternalLoader=function(e){var t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var i=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:R,url:i,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var i=t.id,r=t.level,s=t.pathwayId,n=t.url,a=t.deliveryDirectives,o=t.levelInfo;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:P,url:n,deliveryDirectives:a,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var i=t.id,r=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:k,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onSubtitleTrackLoading=function(e,t){var i=t.id,r=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:D,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onLevelsUpdated=function(e,t){var i=this.loaders[P];if(i){var r=i.context;r&&!t.levels.some((function(e){return e===r.levelOrTrack}))&&(i.abort(),delete this.loaders[P])}},t.load=function(e){var t,i,r,s=this,a=this.hls.config,o=this.getInternalLoader(e);if(o){var l=this.hls.logger,h=o.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives))return void(h.url===e.url?l.log("[playlist-loader]: ignore "+e.url+" ongoing request"):l.log("[playlist-loader]: ignore "+e.url+" in favor of "+h.url));l.log("[playlist-loader]: aborting previous loader for type: "+e.type),o.abort()}if(i=e.type===R?a.manifestLoadPolicy.default:n({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),o=this.createInternalLoader(e),T(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===P&&null!==e.level?r=this.hls.levels[e.level].details:e.type===k&&null!==e.id?r=this.hls.audioTracks[e.id].details:e.type===D&&null!==e.id&&(r=this.hls.subtitleTracks[e.id].details),r)){var u=r.partTarget,d=r.targetduration;if(u&&d){var c=1e3*Math.max(3*u,.8*d);i=n({},i,{maxTimeToFirstByteMs:Math.min(c,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,i.maxTimeToFirstByteMs)})}}var f=i.errorRetry||i.timeoutRetry||{},g={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},p={onSuccess:function(e,t,i,r){var n=s.getInternalLoader(i);s.resetInternalLoader(i.type);var a=e.data;t.parsing.start=performance.now(),Di.isMediaPlaylist(a)||i.type!==R?s.handleTrackOrLevelPlaylist(e,t,i,r||null,n):s.handleMasterPlaylist(e,t,i,r)},onError:function(e,t,i,r){s.handleNetworkError(t,i,!1,e,r)},onTimeout:function(e,t,i){s.handleNetworkError(t,i,!0,void 0,e)}};o.load(e,g,p)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,i=t.autoStartLoad,r=t.startPosition,s=e.forceStartLoad;(i||s)&&(this.hls.logger.log((i?"auto":"force")+" startLoad with configured startPosition "+r),this.hls.startLoad(r))}},t.handleMasterPlaylist=function(e,t,i,r){var s=this,n=this.hls,a=e.data,o=hl(e,i),l=Di.parseMasterPlaylist(a,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);var h=l.contentSteering,u=l.levels,d=l.sessionData,c=l.sessionKeys,f=l.startTimeOffset,g=l.variableList;this.variableList=g,u.forEach((function(e){var t=e.unknownCodecs;if(t)for(var i=s.hls.config.preferManagedMediaSource,r=e.audioCodec,n=e.videoCodec,a=t.length;a--;){var o=t[a];we(o,"audio",i)?(e.audioCodec=r=r?r+","+o:o,ke.audio[r.substring(0,4)]=2,t.splice(a,1)):we(o,"video",i)&&(e.videoCodec=n=n?n+","+o:o,ke.video[n.substring(0,4)]=2,t.splice(a,1))}}));var p=Di.parseMasterPlaylistMedia(a,o,l),v=p.AUDIO,m=void 0===v?[]:v,y=p.SUBTITLES,E=p["CLOSED-CAPTIONS"];m.length&&(m.some((function(e){return!e.url}))||!u[0].audioCodec||u[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ti({}),bitrate:0,url:""}))),n.trigger(I.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:y,captions:E,contentSteering:h,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:c,startTimeOffset:f,variableList:g})},t.handleTrackOrLevelPlaylist=function(e,t,i,r,s){var n=this.hls,a=i.id,o=i.level,l=i.type,h=hl(e,i),u=T(o)?o:T(a)?a:0,d=ll(i),c=Di.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===R){var f={attrs:new ti({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=t.loading.start+Yi(c,0),n.trigger(I.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,e,t,i,r,s)},t.handleManifestParsingError=function(e,t,i,r,s){this.hls.trigger(I.ERROR,{type:b.NETWORK_ERROR,details:A.MANIFEST_PARSING_ERROR,fatal:t.type===R,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})},t.handleNetworkError=function(e,t,i,r,s){void 0===i&&(i=!1);var n="A network "+(i?"timeout":"error"+(r?" (status "+r.code+")":""))+" occurred while loading "+e.type;e.type===P?n+=": "+e.level+" id: "+e.id:e.type!==k&&e.type!==D||(n+=" id: "+e.id+' group-id: "'+e.groupId+'"');var a=new Error(n);this.hls.logger.warn("[playlist-loader]: "+n);var o=A.UNKNOWN,l=!1,h=this.getInternalLoader(e);switch(e.type){case R:o=i?A.MANIFEST_LOAD_TIMEOUT:A.MANIFEST_LOAD_ERROR,l=!0;break;case P:o=i?A.LEVEL_LOAD_TIMEOUT:A.LEVEL_LOAD_ERROR,l=!1;break;case k:o=i?A.AUDIO_TRACK_LOAD_TIMEOUT:A.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case D:o=i?A.SUBTITLE_TRACK_LOAD_TIMEOUT:A.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);var d={type:b.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(r){var c=(null==t?void 0:t.url)||e.url;d.response=u({url:c,data:void 0},r)}this.hls.trigger(I.ERROR,d)},t.handlePlaylistLoaded=function(e,t,i,r,s,n){var a=this.hls,o=r.type,l=r.level,h=r.levelOrTrack,u=r.id,d=r.groupId,c=r.deliveryDirectives,f=hl(t,r),g=ll(r),p="number"==typeof r.level&&g===w?l:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(v+" "+e.url),!a.config.ignorePlaylistParsingErrors)return void a.trigger(I.ERROR,{type:b.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:r,level:p,parent:g,networkDetails:s,stats:i});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case R:case P:if(p)if(h){if(h!==a.levels[p]){var m=a.levels.indexOf(h);m>-1&&(p=m)}}else p=0;a.trigger(I.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:p||0,id:u||0,stats:i,networkDetails:s,deliveryDirectives:c,withoutMultiVariant:o===R});break;case k:a.trigger(I.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:c});break;case D:a.trigger(I.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:c})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(I.ERROR,{type:b.NETWORK_ERROR,details:A.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:r,level:p,parent:g,networkDetails:s,stats:i})}},e}(),dl=function(){function e(t){void 0===t&&(t={}),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new y,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var i=this.logger=K(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=Wo(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var n=("level"===e?"playlist":e)+"LoadPolicy",a=void 0===t[n],o=[];s.forEach((function(i){var s=e+"Loading"+i,l=t[s];if(void 0!==l&&a){o.push(s);var h=r[n].default;switch(t[n]={default:h},i){case"TimeOut":h.maxLoadTimeMs=l,h.maxTimeToFirstByteMs=l;break;case"MaxRetry":h.errorRetry.maxNumRetry=l,h.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":h.errorRetry.retryDelayMs=l,h.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=l,h.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+n+'": '+it(t[n]))})),u(u({},r),t)}(e.DefaultConfig,t,i);this.userConfig=t,r.progressive&&function(e,t){var i=e.loader;i!==Uo&&i!==Vo?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=Uo,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(r,i);var s=r.abrController,n=r.bufferController,a=r.capLevelController,o=r.errorController,l=r.fpsController,h=new o(this),d=this.abrController=new s(this),c=new wt(this),f=r.interstitialsController,g=f?this.interstitialsController=new f(this,e):null,p=this.bufferController=new n(this,c),v=this.capLevelController=new a(this),m=new l(this),E=new ul(this),S=r.contentSteeringController,T=S?new S(this):null,_=this.levelController=new tl(this,T),L=new Zo(this),b=new al(this.config,this.logger),A=this.streamController=new nl(this,c,b),R=this.gapController=new qo(this,c);v.setStreamController(A),m.setStreamController(A);var P=[E,_,A];g&&P.splice(1,0,g),T&&P.splice(1,0,T),this.networkControllers=P;var k=[d,p,R,v,m,L,c];this.audioTrackController=this.createController(r.audioTrackController,P);var D=r.audioStreamController;D&&P.push(this.audioStreamController=new D(this,c,b)),this.subtitleTrackController=this.createController(r.subtitleTrackController,P);var w=r.subtitleStreamController;w&&P.push(this.subtititleStreamController=new w(this,c,b)),this.createController(r.timelineController,k),b.emeController=this.emeController=this.createController(r.emeController,k),this.cmcdController=this.createController(r.cmcdController,k),this.latencyController=this.createController(el,k),this.coreComponents=k,P.push(h);var C=h.onErrorOut;"function"==typeof C&&this.on(I.ERROR,C,h),this.on(I.MANIFEST_LOADED,E.onManifestLoaded,E)}e.isMSESupported=function(){return sl()},e.isSupported=function(){return function(){if(!sl())return!1;var e=$();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(t){return e.isTypeSupported(Me(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Me(t,"audio"))})))}()},e.getMediaSource=function(){return $()};var t=e.prototype;return t.createController=function(e,t){if(e){var i=new e(this);return t&&t.push(i),i}return null},t.on=function(e,t,i){void 0===i&&(i=this),this._emitter.on(e,t,i)},t.once=function(e,t,i){void 0===i&&(i=this),this._emitter.once(e,t,i)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,i,r){void 0===i&&(i=this),this._emitter.off(e,t,i,r)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,i){return this._emitter.emit(e,t,i)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var i=e===I.ERROR;this.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){this.logger.log("destroy"),this.trigger(I.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},t.attachMedia=function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument ("+e+")");this.trigger(I.ERROR,{type:b.OTHER_ERROR,details:A.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var i="media"in e,r=i?e.media:e,s=i?e:{media:r};this._media=r,this.trigger(I.MEDIA_ATTACHING,s)}},t.detachMedia=function(){this.logger.log("detachMedia"),this.trigger(I.MEDIA_DETACHING,{}),this._media=null},t.transferMedia=function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(I.MEDIA_DETACHING,{transferMedia:e}),e},t.loadSource=function(e){this.stopLoad();var t=this.media,i=this._url,r=this._url=S.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+r),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(I.MANIFEST_LOADING,{url:e})},t.startLoad=function(e,t){void 0===e&&(e=-1),this.logger.log("startLoad("+e+(t?", <skip seek to start>":"")+")"),this.started=!0,this.resumeBuffering();for(var i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);},t.stopLoad=function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);},t.resumeBuffering=function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((function(e){e.resumeBuffering&&e.resumeBuffering()})))},t.pauseBuffering=function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((function(e){e.pauseBuffering&&e.pauseBuffering()})))},t.swapAudioCodec=function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.recoverMediaError=function(){this.logger.log("recoverMediaError");var e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))},t.removeLevel=function(e){this.levelController.removeLevel(e)},t.setAudioOption=function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null},t.setSubtitleOption=function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null},t.getMediaDecodingInfo=function(e,t){return void 0===t&&(t=this.allAudioTracks),je(e,st(t),navigator.mediaCapabilities)},r(e,[{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"loadingEnabled",get:function(){return this.started}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"inFlightFragments",get:function(){var e,t=((e={})[w]=this.streamController.inFlightFrag,e);return this.audioStreamController&&(t[C]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[M]=this.subtititleStreamController.inFlightFrag),t}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(r){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(i+16*Math.random())%16|0;return i=Math.floor(i/16),("x"==e?t:3&t|8).toString(16)}))}}}()),e}},{key:"levels",get:function(){return this.levelController.levels||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return Xe.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var i=e.length,r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(var s=e;s--;){var n=t[s].attrs["HDCP-LEVEL"];if(n&&n<=r)return s}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency},set:function(e){this.latencyController.targetLatency=e}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}}],[{key:"version",get:function(){return Ks}},{key:"Events",get:function(){return I}},{key:"MetadataSchema",get:function(){return Or}},{key:"ErrorTypes",get:function(){return b}},{key:"ErrorDetails",get:function(){return A}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:$o},set:function(t){e.defaultConfig=t}}])}();return dl.defaultConfig=void 0,dl},e.exports=r()}(!1)},424:(e,t)=>{"use strict";t.h=s;var i=2147483647;function r(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return n(e,t,i)}function n(e,t,i){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var i=0|u(e,t),n=r(i),a=n.write(e,t);a!==i&&(n=n.slice(0,a));return n}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(m(e,ArrayBuffer)||e&&m(e.buffer,ArrayBuffer))return function(e,t,i){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(i||0))throw new RangeError('"length" is outside of buffer bounds');var r;r=void 0===t&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,t):new Uint8Array(e,t,i);return r.__proto__=s.prototype,r}(e,t,i);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return s.from(n,t,i);var a=function(e){if(s.isBuffer(e)){var t=0|h(e.length),i=r(t);return 0===i.length||e.copy(i,0,0,t),i}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?r(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function a(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function o(e){return a(e),r(e<0?0:0|h(e))}function l(e){for(var t=e.length<0?0:0|h(e.length),i=r(t),s=0;s<t;s+=1)i[s]=255&e[s];return i}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function u(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||m(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var i=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===i)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return v(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;default:if(n)return r?-1:v(e).length;t=(""+t).toLowerCase(),n=!0}}function d(e,t,i,r){i=Number(i)||0;const s=e.length-i;r?(r=Number(r))>s&&(r=s):r=s;const n=t.length;let a;for(r>n/2&&(r=n/2),a=0;a<r;++a){const r=parseInt(t.substr(2*a,2),16);if(y(r))return a;e[i+a]=r}return a}function c(e,t,i,r){return p(v(t,e.length-i),e,i,r)}function f(e,t,i,r){return p(function(e){const t=[];for(let i=0;i<e.length;++i)t.push(255&e.charCodeAt(i));return t}(t),e,i,r)}function g(e,t,i,r){return p(function(e,t){let i,r,s;const n=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)i=e.charCodeAt(a),r=i>>8,s=i%256,n.push(s),n.push(r);return n}(t,e.length-i),e,i,r)}function p(e,t,i,r){let s;for(s=0;s<r&&!(s+i>=t.length||s>=e.length);++s)t[s+i]=e[s];return s}function v(e,t){var i;t=t||1/0;for(var r=e.length,s=null,n=[],a=0;a<r;++a){if((i=e.charCodeAt(a))>55295&&i<57344){if(!s){if(i>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&n.push(239,191,189);continue}s=i;continue}if(i<56320){(t-=3)>-1&&n.push(239,191,189),s=i;continue}i=65536+(s-55296<<10|i-56320)}else s&&(t-=3)>-1&&n.push(239,191,189);if(s=null,i<128){if((t-=1)<0)break;n.push(i)}else if(i<2048){if((t-=2)<0)break;n.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;n.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return n}function m(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.from=function(e,t,i){return n(e,t,i)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,i){return function(e,t,i){return a(e),e<=0?r(e):void 0!==t?"string"==typeof i?r(e).fill(t,i):r(e).fill(t):r(e)}(e,t,i)},s.allocUnsafe=function(e){return o(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var i;if(void 0===t)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=s.allocUnsafe(t),n=0;for(i=0;i<e.length;++i){var a=e[i];if(m(a,Uint8Array)&&(a=s.from(a)),!s.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(r,n),n+=a.length}return r},s.byteLength=u,s.prototype._isBuffer=!0,s.prototype.copy=function(e,t,i,r){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var n=r-i;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,i,r);else if(this===e&&i<t&&t<r)for(var a=n-1;a>=0;--a)e[a+t]=this[a+i];else Uint8Array.prototype.set.call(e,this.subarray(i,r),t);return n},s.prototype.write=function(e,t,i,r){if(void 0===t)r="utf8",i=this.length,t=0;else if(void 0===i&&"string"==typeof t)r=t,i=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(i)?(i>>>=0,void 0===r&&(r="utf8")):(r=i,i=void 0)}const s=this.length-t;if((void 0===i||i>s)&&(i=s),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let n=!1;for(;;)switch(r){case"hex":return d(this,e,t,i);case"utf8":case"utf-8":return c(this,e,t,i);case"ascii":case"latin1":case"binary":return f(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,i);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),n=!0}}},832:function(e,t,i){var r;!function(s){"use strict";function n(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function a(e,t,i,r,s,a){return n((o=n(n(t,e),n(r,a)))<<(l=s)|o>>>32-l,i);var o,l}function o(e,t,i,r,s,n,o){return a(t&i|~t&r,e,t,s,n,o)}function l(e,t,i,r,s,n,o){return a(t&r|i&~r,e,t,s,n,o)}function h(e,t,i,r,s,n,o){return a(t^i^r,e,t,s,n,o)}function u(e,t,i,r,s,n,o){return a(i^(t|~r),e,t,s,n,o)}function d(e,t){var i,r,s,a,d;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var c=1732584193,f=-271733879,g=-1732584194,p=271733878;for(i=0;i<e.length;i+=16)r=c,s=f,a=g,d=p,c=o(c,f,g,p,e[i],7,-680876936),p=o(p,c,f,g,e[i+1],12,-389564586),g=o(g,p,c,f,e[i+2],17,606105819),f=o(f,g,p,c,e[i+3],22,-1044525330),c=o(c,f,g,p,e[i+4],7,-176418897),p=o(p,c,f,g,e[i+5],12,1200080426),g=o(g,p,c,f,e[i+6],17,-1473231341),f=o(f,g,p,c,e[i+7],22,-45705983),c=o(c,f,g,p,e[i+8],7,1770035416),p=o(p,c,f,g,e[i+9],12,-1958414417),g=o(g,p,c,f,e[i+10],17,-42063),f=o(f,g,p,c,e[i+11],22,-1990404162),c=o(c,f,g,p,e[i+12],7,1804603682),p=o(p,c,f,g,e[i+13],12,-40341101),g=o(g,p,c,f,e[i+14],17,-1502002290),c=l(c,f=o(f,g,p,c,e[i+15],22,1236535329),g,p,e[i+1],5,-165796510),p=l(p,c,f,g,e[i+6],9,-1069501632),g=l(g,p,c,f,e[i+11],14,643717713),f=l(f,g,p,c,e[i],20,-373897302),c=l(c,f,g,p,e[i+5],5,-701558691),p=l(p,c,f,g,e[i+10],9,38016083),g=l(g,p,c,f,e[i+15],14,-660478335),f=l(f,g,p,c,e[i+4],20,-405537848),c=l(c,f,g,p,e[i+9],5,568446438),p=l(p,c,f,g,e[i+14],9,-1019803690),g=l(g,p,c,f,e[i+3],14,-187363961),f=l(f,g,p,c,e[i+8],20,1163531501),c=l(c,f,g,p,e[i+13],5,-1444681467),p=l(p,c,f,g,e[i+2],9,-51403784),g=l(g,p,c,f,e[i+7],14,1735328473),c=h(c,f=l(f,g,p,c,e[i+12],20,-1926607734),g,p,e[i+5],4,-378558),p=h(p,c,f,g,e[i+8],11,-2022574463),g=h(g,p,c,f,e[i+11],16,1839030562),f=h(f,g,p,c,e[i+14],23,-35309556),c=h(c,f,g,p,e[i+1],4,-1530992060),p=h(p,c,f,g,e[i+4],11,1272893353),g=h(g,p,c,f,e[i+7],16,-155497632),f=h(f,g,p,c,e[i+10],23,-1094730640),c=h(c,f,g,p,e[i+13],4,681279174),p=h(p,c,f,g,e[i],11,-358537222),g=h(g,p,c,f,e[i+3],16,-722521979),f=h(f,g,p,c,e[i+6],23,76029189),c=h(c,f,g,p,e[i+9],4,-640364487),p=h(p,c,f,g,e[i+12],11,-421815835),g=h(g,p,c,f,e[i+15],16,530742520),c=u(c,f=h(f,g,p,c,e[i+2],23,-995338651),g,p,e[i],6,-198630844),p=u(p,c,f,g,e[i+7],10,1126891415),g=u(g,p,c,f,e[i+14],15,-1416354905),f=u(f,g,p,c,e[i+5],21,-57434055),c=u(c,f,g,p,e[i+12],6,1700485571),p=u(p,c,f,g,e[i+3],10,-1894986606),g=u(g,p,c,f,e[i+10],15,-1051523),f=u(f,g,p,c,e[i+1],21,-2054922799),c=u(c,f,g,p,e[i+8],6,1873313359),p=u(p,c,f,g,e[i+15],10,-30611744),g=u(g,p,c,f,e[i+6],15,-1560198380),f=u(f,g,p,c,e[i+13],21,1309151649),c=u(c,f,g,p,e[i+4],6,-145523070),p=u(p,c,f,g,e[i+11],10,-1120210379),g=u(g,p,c,f,e[i+2],15,718787259),f=u(f,g,p,c,e[i+9],21,-343485551),c=n(c,r),f=n(f,s),g=n(g,a),p=n(p,d);return[c,f,g,p]}function c(e){var t,i="",r=32*e.length;for(t=0;t<r;t+=8)i+=String.fromCharCode(e[t>>5]>>>t%32&255);return i}function f(e){var t,i=[];for(i[(e.length>>2)-1]=void 0,t=0;t<i.length;t+=1)i[t]=0;var r=8*e.length;for(t=0;t<r;t+=8)i[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return i}function g(e){var t,i,r="0123456789abcdef",s="";for(i=0;i<e.length;i+=1)t=e.charCodeAt(i),s+=r.charAt(t>>>4&15)+r.charAt(15&t);return s}function p(e){return unescape(encodeURIComponent(e))}function v(e){return function(e){return c(d(f(e),8*e.length))}(p(e))}function m(e,t){return function(e,t){var i,r,s=f(e),n=[],a=[];for(n[15]=a[15]=void 0,s.length>16&&(s=d(s,8*e.length)),i=0;i<16;i+=1)n[i]=909522486^s[i],a[i]=1549556828^s[i];return r=d(n.concat(f(t)),512+8*t.length),c(d(a.concat(r),640))}(p(e),p(t))}function y(e,t,i){return t?i?m(t,e):g(m(t,e)):i?v(e):g(v(e))}void 0===(r=function(){return y}.call(t,i,t,e))||(e.exports=r)}()},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var i={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(r())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return i.isAndroid()||i.isAndroidWebView()?t.ANDROID_WEB:i.isIOS()||i.isIpad()||i.isIOSWebView()?t.IOS_WEB:i.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(r())},isPC:function(){return!n(s("os "))&&!n(s("android[/ ]"))},isIOS:function(){return n(s("os "))},isIpad:function(){return r().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return n(s("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(r())},isMobile:function(){return i.isAndroid()||i.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(r())},isFirefox:function(){return/firefox/i.test(r())},isChrome:function(){return/chrome/i.test(r())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=r();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=r();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return i.isAndroidWebView()||i.isIOSWebView()},device:t,getBrowser:function(){return i.isX5()?"X5":i.isAndroidWebView()?"Android-WebView":i.isIOSWebView()?"iOS-WebView":i.isChrome()?"Chrome":i.isFirefox()?"Firefox":i.isIpadSafari()?"iPad-Safari":i.isIOSSafari()?"iPhone-Safari":i.isSafari()?"Mac-Safari":"Unknown"}};function r(){return navigator.userAgent.toLowerCase()}function s(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(r())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=i}},t={};function i(r){var s=t[r];if(void 0!==s)return s.exports;var n=t[r]={exports:{}};return e[r].call(n.exports,n,n.exports,i),n.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var r={};return(()=>{"use strict";i.d(r,{default:()=>Mi});const e={DC_SIGNAL:"SIGNAL",DC_SIGNAL_BATCH:"SIGNAL_BATCH",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_PIECE_CANCEL:"PIECE_CANCEL",DC_CLOSE:"CLOSE",DC_DISCONNECT:"DISCONNECT",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",BM_FATAL_ERROR:"BM_FATAL_ERROR",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PROGRESS:"SYN_PROGRESS",MEDIA_REBUFFER:"MEDIA_REBUFFER"},t={...e,SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_GET_MEDIA:"SW_GET_MEDIA",SW_DEBUG:"SW_DEBUG",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED"};var s=i(415),n=i.n(s),a=i(424),o=i(558),l=i.n(o);const h="__PROXY_IDENTIFIER__";const u=64e3;function d(){return!0}function c(e){return new URL(location.href).searchParams.get(e)}function f(e,t,i){const r=new URL(e);return r.searchParams.append(t,i),r.href}function g(){return Date.parse(new Date)/1e3}function p(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function v(e){return new Promise((t=>setTimeout(t,e)))}function m(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function y(e){const t=a.h.from(e),i=new a.h(e.byteLength);return t.copy(i),i}function E(){return location.protocol.startsWith("https")}function S(e,t,i){if(e.size<=t)return;const r=[...e.keys()];do{const t=r.shift();i&&i(e.get(t)),e.delete(t)}while(e.size>t)}function T(e,t){if(e.size<=t)return;const i=[...e.values()];do{e.delete(i.shift())}while(e.size>t)}function _(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function L(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const i=Number(t[0]),r=t[1]?Number(t[1]):-1;return{rangeStart:i,rangeEnd:r>=0?r+1:void 0}}function b(e){return e.split("?")[0]}function A(){let e=new Date,t=e.getHours(),i=e.getMinutes(),r=e.getSeconds(),s=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}.${s}`}function I(e){return e&&"function"==typeof e}function R(e,t,i,r,s,n){e.sendPartialBuffer(i,r,{from:s,incompletes:n})&&(r.length<i.attachments?function(e,t,i){e.addStreamListener(i,t.remotePeerId,((e,i,r,s,n)=>{r?t.sendMsgPieceAbort(s,i,!0):t.uploading&&t.send(s),n&&(t.uploading=!1)}))}(t,e,!!i.reverse):e.uploading=!1)}const P=e=>0===p(0,1)?[null,e]:[e,null];function k(e,t,i){return 1===e.length?t.length>=1&&i.length>=1?t[0].weight>i[0].weight?[t[0],e[0]]:[e[0],i[0]]:t.length>=1?[t[0],e[0]]:i.length>=1?[e[0],i[0]]:P(e[0]):[t.length>=1?t[0]:null,i.length>=1?i[0]:null]}function D(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}async function w(e){if(crypto.subtle)try{const t=await crypto.subtle.digest("SHA-256",e),i=String.fromCharCode.apply(null,new Uint8Array(t));return btoa(i)}catch(e){}}class C{constructor(e,t){this.target=t,this.type=e}}class M extends C{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class O extends C{constructor(e=1e3,t="",i){super("close",i),this.code=e,this.reason=t,this.wasClean=!0}}const x=()=>{if("undefined"!=typeof WebSocket)return WebSocket},F={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1};class N{constructor(e,t,i={}){this._listeners={error:[],message:[],open:[],close:[]},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._messageQueue=[],this._closeCalled=!1,this._connectLock=!1,this._shouldReconnect=!0,this._retryCount=-1,this._binaryType="blob",this._url=e,this._protocols=t,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect(),this._handleOpen=this._handleOpen.bind(this),this._handleClose=this._handleClose.bind(this),this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this)}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return N.CONNECTING}get OPEN(){return N.OPEN}get CLOSING(){return N.CLOSING}get CLOSED(){return N.CLOSED}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?N.CLOSED:N.CONNECTING}get url(){return this._ws?this._ws.url:""}close(e=1e3,t){this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws&&this._ws.readyState!==this.CLOSED&&this._ws.close(e,t)}reconnect(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._ws.send(e);else{const{maxEnqueuedMessages:t=F.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&this._messageQueue.push(e)}}addEventListener(e,t){this._listeners[e]&&this._listeners[e].push(t)}dispatchEvent(e){const t=this._listeners[e.type];if(t)for(const i of t)this._callEventListener(e,i);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=F.reconnectionDelayGrowFactor,minReconnectionDelay:t=F.minReconnectionDelay,maxReconnectionDelay:i=F.maxReconnectionDelay}=this._options;let r=0;return this._retryCount>0&&(r=t*Math.pow(e,this._retryCount-1),r>i&&(r=i)),r}_wait(){return new Promise((e=>{setTimeout(e,this._getNextDelay())}))}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:e=F.maxRetries,connectionTimeout:t=F.connectionTimeout,WebSocket:i=x()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(r=i)||!r||2!==r.CLOSING)throw Error("No valid WebSocket class provided");var r;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new i(e,this._protocols):new i(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout((()=>this._handleTimeout()),t))})).catch((e=>{this._connectLock=!1,this._handleError(new M(Error(e.message),this))}))}}_handleTimeout(){this._handleError(new M(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new O(e,t,this))}catch(e){}}}_acceptOpen(){this._retryCount=0}_callEventListener(e,t){"handleEvent"in t?t.handleEvent(e):t(e)}_handleOpen(e){const{minUptime:t=F.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout((()=>this._acceptOpen()),t),this._ws.binaryType=this._binaryType,this._messageQueue.forEach((e=>this._ws.send(e))),this._messageQueue=[],this.onopen&&this.onopen(e),this._listeners.open.forEach((t=>this._callEventListener(e,t)))}_handleMessage(e){this.onmessage&&this.onmessage(e),this._listeners.message.forEach((t=>this._callEventListener(e,t)))}_handleError(e){this._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),this.onerror&&this.onerror(e),this._listeners.error.forEach((t=>this._callEventListener(e,t))),this._connect()}_handleClose(e){this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this._listeners.close.forEach((t=>this._callEventListener(e,t)))}_removeListeners(){this._ws&&(this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const B={debug:3,info:4,warn:5,error:6};class U{constructor(e,t,i,r){this.wsAddr=`${e}?app=${t}&id=${i}&v=${r}`,this.destroyed=!1;try{this._ws=this._init()}catch(e){console.error(e)}}_init(){const e={maxRetries:3,minReconnectionDelay:p(5e3,15e3),maxReconnectionDelay:6e5,maxEnqueuedMessages:200};return new N(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const i=B[e];this._ws.send(JSON.stringify({records:[{level:i,text:`${A()}: ${t}`}]}))}sendBatch(e){const t=[];for(let i of e)t.push({level:B[i.levelKey],text:i.message});this._ws.send(JSON.stringify({records:t}))}destroy(){this._ws&&(this._ws.close(1e3),this._ws=null,this.destroyed=!0)}}const G=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}},H=(e,t,i)=>{((e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)})(e,{value:t,duration:i,startTime:Date.now()})},K={debug:0,info:1,warn:2,error:3,none:4};const V=class{constructor(e){this.logLevel=e,this.onlineDebug=!1,this.logCache=[];try{console.debug=console.log}catch(e){console.debug=console.info}"debug"!==e&&"info"!==e||(this.logLevel="error"),G("SW_DEBUG")&&(this.logLevel="debug"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in K||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in K)this[e]=console[e];this._hookLogFunc(((e,t)=>{this.logUploader&&this.logUploader.send(e,t)}))}enableReport(e){this.reportUrl=e,this._hookLogFunc(((e,t)=>{this.reportUrl?(this.logCache.push({levelKey:e,message:`${A()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,i,r,s=5e3){this.reportUrl&&!this.reporter&&(e&&this.logCache.unshift({levelKey:"info",message:e}),this.reporter=new U(this.reportUrl,t,i,r),this.reporter._ws.addEventListener("open",(()=>{this.reportUrl=void 0,this.reporter.sendBatch(this.logCache),setTimeout((()=>{this.reporter.destroy(),this.reporter=null}),s)}),{once:!0}))}_hookLogFunc(e){for(let t in K){const i=this[t];this[t]=r=>{e(t,r),i(r)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in K)K[e]<K[this.logLevel]?this[e]=d:this[e]=console[e]}get isDebugLevel(){return K[this.logLevel]<=2||this.onlineDebug}};let $;const W="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>($||($=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),q=65536;function j(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class Y extends(n()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||Y.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Y.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=m(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void W((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{e.debug=!0,this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var i;!t.address||t.address.endsWith(".local")?(i="Ignoring unsupported ICE candidate.",console.warn(i)):(e.debug=!0,this.destroy(e))}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,W((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,W((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=q),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{e.debug=!0,this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}get isBufferedAmountHigh(){return this._channel.bufferedAmount>q}write(e,t){if(this.destroyed)return t(new Error("cannot write after peer is destroyed"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(e)}this.isBufferedAmountHigh?this._cb=t:t(null)}else this._chunk=e,this._cb=t}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=j(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=j(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((i=>{const r=[];i.forEach((e=>{r.push(t(e))})),e(null,r)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((i=>{if(this.destroyed)return;const r=[];i.result().forEach((e=>{const i={};e.names().forEach((t=>{i[t]=e.stat(t)})),i.id=e.id,i.type=e.type,i.timestamp=e.timestamp,r.push(t(i))})),e(null,r)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,i)=>{if(this.destroyed)return;t&&(i=[]);const r={},s={},n={};let a=!1;i.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(r[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(s[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(n[e.id]=e)}));const o=e=>{a=!0;let t=s[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let i=r[e.remoteCandidateId];i&&(i.ip||i.address)?(this.remoteAddress=i.ip||i.address,this.remotePort=Number(i.port)):i&&i.ipAddress?(this.remoteAddress=i.ipAddress,this.remotePort=Number(i.portNumber)):"string"==typeof e.googRemoteAddress&&(i=e.googRemoteAddress.split(":"),this.remoteAddress=i[0],this.remotePort=Number(i[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(i.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(n[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(n).length&&!Object.keys(s).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect");for(let e of this._pendingData)this.emit("data",e);this._pendingData=[]}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>q||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=a.h.from(t)),this._connected?this.emit("data",t):this._pendingData.length<10&&this._pendingData.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}Y.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Y.channelConfig={};const z=Y;class X{constructor(e,t,i,r,s=0,n={}){this.sn=e,this.segId=t,this.data=i,this.fromPeerId=r,this.level=s,this.ext=n}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var Q=i(365),J=i.n(Q);class Z extends(n()){static get defaultPacketSize(){return u}static get VERSION(){return"8"}constructor(e,t,i,r,s,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=s,this.isInitiator=r,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,i),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=u,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.useBackupSignal=!1,this.gotPeersTS=0,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.incomingSignal=[],this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,i){this.remotePeerId=i,this.channelId=this.isInitiator?`${t}-${i}`:`${i}-${t}`,i&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(e.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=g(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:t,sentSignal:i,signalName:r}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${i} signalName ${r}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:i,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,i,r){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${r} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:i,seg_id:r}))))}addStreamListener(e,t,i){this.streamListeners.push({handler:i,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_initPeerChannel(){const t=new z({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let i=!0;(this.connected||this.notFatalClosed)&&(i=!1);let r=t.message;t.debug&&(r=`${r} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,i,r)})),t.on("signal",(t=>{t.candidate&&!t.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(t),this.sentSignal=!0,this.emit(e.DC_SIGNAL,t))}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.intermediator?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,this.incomingSignal=[],clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:i}=this;if("string"==typeof t){let r;try{r=JSON.parse(t)}catch(e){return void i.error(e)}if(!r)return void i.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(r);let s,n=r.event;switch(s=n!==e.DC_PLAYLIST&&n!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${n}`,i.debug(`datachannel receive ${s} from ${this.remotePeerId}`),n){case e.DC_HAVE:if(this.emit(r.event,r),!r.sn)return;this.config.live||(r.sn<this.startSN&&(this.startSN=r.sn),r.sn>this.endSN&&(this.endSN=r.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=g(),this.timeReceivePiece=performance.now(),this.pieceMsg=r,this._prepareForBinary(r.attachments,r.seg_id,r.sn,r.size),this.emit(r.event,r);break;case e.DC_PIECE_CANCEL:i.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(r.event,r),this.sendMsgPieceAbort("transfer canceled",r.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(r.event,r);break;case e.DC_REQUEST:this._handleRequestMsg(r);break;case e.DC_PIECE_ACK:this._handlePieceAck(r.seg_id,r.size,r.miss);break;case e.DC_STATS:this._handleStats(r);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(r);break;case e.DC_METADATA:this._handleMetadata(r);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,r)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:i.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:i.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(r.event,r.fatal||!1);break;default:this.emit(r.event,r)}}else{if(!t)return void i.error("datachannel on data is undefined!");if(!this.downloading){const r=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return i.warn(r),void this.emit(e.DC_ERROR,!1,r)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,i)=>{this.connected&&"disconnected"===t&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(e.DC_DISCONNECT))}))}sendJson(t){if(!this.remotePeerId)return!1;t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const i=JSON.stringify(t);return i.length>u?(this.logger.error("string to send is too large"),!1):this.send(i,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();t?("string"!=typeof t&&(this.bytesUploaded+=t.byteLength),this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,void this.emit(e.DC_ERROR,!1,t.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){const i=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,i)}return!1}sendMsgHave(t,i,r={}){const s=r.reverse||void 0;delete r.reverse,this.sendJson({event:s?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:i,...r})}sendPieceNotFound(t,i,r={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:i||void 0,sn:t,...r})}sendPeers(t){this.sendJson({event:e.DC_PEERS,peers:t})}sendPeersRequest(){this.sendJson({event:e.DC_GET_PEERS})}sendMsgStats(t,i={}){const r={event:e.DC_STATS,total_conns:t,...i};this.sendJson(r)}sendMsgPlaylist(t,i,r){const s=this.playlistMap.get(t);if(s&&s.seq>=r)return;const n={event:e.DC_PLAYLIST,url:t,data:i,seq:r};this.playlistMap.set(t,{data:i,seq:r}),this.sendJson(n)}sendMsgSignal(t,i,r){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:i,data:r})}sendMsgSignalReject(t,i,r,s=!1){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:i,reason:r,fatal:s})}sendMetaData(t,i,r,s,n=!1){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!J().isMobile(),mobile_net:n,channel:this.channel,version:"2.16.4",sequential:i,peers:r,region:s})}sendPartialBuffer(e,t,i={}){if(!this.sendMsgPiece(e,i))return!1;for(let e=0;e<t.length;e++)this.send(t[e]);return!0}sendMsgPiece(e,t={}){if(!this.uploading)return this.logger.info("not uploading, cancel send buffer"),!1;this.datasToSend=[],this.bytesUploaded=0,e.ext||(e.ext={}),e.ext.from&&t.from&&t.from.length<2500&&(t.from=`${e.ext.from}-${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const i={...e,ext:t};return this.sendJson(i)}sendBuffer(t,i,r,s={}){const n=s.reverse||void 0;if(delete s.reverse,!r)return void this.logger.error("sendBuffer payload is undefined!");let a=r.byteLength,o=0,l=0;a%this.packetSize==0?l=a/this.packetSize:(l=Math.floor(a/this.packetSize)+1,o=a%this.packetSize);let h={event:e.DC_PIECE,attachments:l,seg_id:i,sn:t,level:s.level,size:a,reverse:n};if(delete s.level,!this.sendMsgPiece(h,s))return;const u=function(e,t,i,r){let s=[];if(r){let n;for(let r=0;r<i-1;r++)n=e.slice(r*t,(r+1)*t),s.push(n);n=e.slice(e.byteLength-r,e.byteLength),s.push(n)}else{let r;for(let n=0;n<i;n++)r=e.slice(n*t,(n+1)*t),s.push(r)}return s}(r,this.packetSize,l,o);this._sendBufferArray(u,n),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}requestDataById(t,i,r=!1,s={}){const n={event:e.DC_REQUEST,seg_id:t,sn:i,...s,urgent:r};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${t} in queue`),r?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}requestDataBySN(t,i=!1,r={}){const s={event:e.DC_REQUEST,sn:t,...r,urgent:i};this.downloading?(this.logger.info(`add req ${t} in queue`),i?this.sendReqQueue.unshift(s):this.sendReqQueue.push(s)):this._realRequestData(s)}_sendBufferArray(e,t=!1){const i=t?e.reverse():e;for(let e=0;e<i.length;e++)this.send(i[e])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0,this._loadedBytes=0}shouldWaitForRemain(e){return 0!==this.bufArrSize&&(0!==this.timeReceivePiece&&this.currentLoadSpeed()>=this.minRequiredSpeed(e))}close(t){t||(this.notFatalClosed=!0),this.emit(e.DC_CLOSE,t)}receiveSignal(e,t){if("answer"===e.type){if(this.gotAnswer||this.gotOffer)return;this.gotAnswer=!0}else if("offer"===e.type){if(this.gotOffer||this.gotAnswer)return;this.gotOffer=!0}this.gotSignal=!0,t&&this.incomingSignal.push(t),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:i}=t;i(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(t=!0){this.logger.info(`destroy datachannel ${this.channelId}`),clearTimeout(this.chokeTimer),clearTimeout(this.connTimeout),this._notifyDownloadListenersAbort("upstream peer is closed");let i={event:e.DC_CLOSE,fatal:t};this.sendJson(i),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:i,reverse:r}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let s=r?this.remainAttachments+1:i-this.remainAttachments;const n=0===this.remainAttachments;if(this.emit(e.DC_PIECE_DATA,this.bufSN,this.segId,t,s,n,this.pieceMsg),this.streamListeners.length>0)for(let e of this.streamListeners){const{handler:i}=e;i(this.bufSN,this.segId,!1,t,n)}if(n){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:e.DC_PIECE_ACK,seg_id:this.segId,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(r)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:i,seq:r}=e;this.playlistMap.set(t,{data:i,seq:r})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const i=this.playlistMap.get(e);return i.seq<=t||i.seq>t+2?null:i}_handleMetadata(t){const{logger:i}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,i.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const r=t.channel;if(this.channel!==r){const t=`peer channel ${r} not matched!`;return i.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){i.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:r}=this.config;if(r&&t.token!==r)return void this.emit(e.DC_ERROR,!0,`super peer token ${t.token} not matched!`)}t.region&&(this.region=t.region);switch(t.platform){case e.DC_PLAT_ANDROID:this.platform=e.DC_PLAT_ANDROID;break;case e.DC_PLAT_IOS:this.platform=e.DC_PLAT_IOS;break;case e.DC_PLAT_WEB:this.platform=e.DC_PLAT_WEB}if(this.mobile=t.mobile||!1,this.mobileNet=t.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===e.DC_PLAT_WEB||!1,this.sequential=t.sequential,i.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,i.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(e.DC_METADATA,t),t.field&&!this.config.live&&t.sequential){const{field:e}=t;if(Array.isArray(e))this._handleField(e);else for(let t in e)this._handleField(e[t])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=g();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPos=e.pos)}_handleRequestMsg(t){if(this.dataExchangeTs=g(),this.uploading)return this.logger.warn(`${this.remotePeerId} is uploading when receive request`),void this.sendPieceNotFound(t.sn,t.seg_id,{level:t.level});this.uploading=!0,this.emit(e.DC_REQUEST,t)}_handlePieceAck(t,i,r){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(i/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),r>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${r}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:i})}_prepareForBinary(e,t,i,r){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=i,this.expectedSize=r}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let i=a.h.concat(this.bufArr);const r=i.byteLength;if(r===this.expectedSize){let t=i.buffer;const r=new X(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,r,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${r}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,i=performance.now()-this.timeSendRequest;if((e||!(i<1e3))&&(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>=3&&!this.choked)){this.choked=!0;const e=30*this.miss;e<=150?(t.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,t.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*e)):t.warn(`datachannel ${this.channelId} is choked permanently`)}}get bufArrSize(){return this.downloading?this.pieceMsg.attachments-this.remainAttachments:0}loadtimeout(){const{logger:e,pieceMsg:t}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded`),this.checkIfNeedChoke(),!0}sendMsgPieceAbort(t,i,r=!1){const s=this.datasToSend.length;if(!r&&!this.uploading&&0===s)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(i,this.bytesUploaded,0),this.bytesUploaded=0;const n={event:e.DC_PIECE_ABORT,reason:`${t}, remains ${s}`};return this.sendJson(n)}loadedBytes(){return this._loadedBytes}currentLoadSpeed(){return 0===this.timeReceivePiece?0:this.loadedBytes()/(performance.now()-this.timeReceivePiece)}minRequiredSpeed(e){return(this.pieceMsg.size-this.loadedBytes())/e}}const ee=Z,te={DPlayer:"dplayer",CBPlayer:"cbplayer",jwplayer:"jwplayer",videojs:"videojs",Clappr:"clappr",ckplayer:"ckplayer",MediaElementPlayer:"mediaelement",MediaElement:"mediaelement",TcPlayer:"tcplayer",flowplayer:"flowplayer",Chimee:"chimee",ChimeePlayer:"chimee",HlsJsPlayer:"xgplayer",fluidPlayer:"fluidplayer",OpenPlayer:"openplayer",Plyr:"plyr",Playerjs:"playerjs",Aliplayer:"aliplayer",shaka:"shakaplayer",RadiantMP:"rmp",bitmovin:"bitmovin"};const ie={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class re extends(n()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===c("_p2p")),e.tag&&e.tag.length>20)throw new Error("Tag is too long");if(e.appName&&e.appName.length>30)throw new Error("appName is too long");if(e.appId&&e.appId.length>30)throw new Error("appId is too long");if(e.token&&e.token.length>20)throw new Error("Token is too long");this.segmentLoadCount=0,this.rangeTested=!1,this.trackerTried=!1,this.playerName=function(){let e;for(let t in te)if(self[t]){e=te[t];break}return e}()}resumeTracker(){this.tracker&&!this.trackerTried&&!this.tracker.connected&&this.config.p2pEnabled&&(this.tracker.resumeP2P(),this.trackerTried=!0)}onTrackerResume(e){e.report_url&&this.logger.enableReport(e.report_url)}startRangeRequestTimer(){const{config:e,logger:t}=this;let i=0;const r=()=>{this.curTsUri&&function(e,t,i,r=2e3,s=!1){const n=new XMLHttpRequest;let a=e;return s&&(a=f(e,h,!0)),t=t||"bytes=0-0",new Promise(((s,o)=>{n.open("GET",a,!0),n.responseType="arraybuffer",n.timeout=r,n.onreadystatechange=e=>{if(4===n.readyState){const e=n.status;206===e?s(n.response):o(`status ${e} url ${a} range ${t}`)}},n.onerror=e=>{o("request error")},n.ontimeout=e=>{o("timeout")},n.setRequestHeader("Range",t),i&&i(n,e),n.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((s=>{e.httpRangeSupported=!1,t&&t.warn(s),i<3&&(this.rangeRequestTimer=setTimeout(r,6e4)),i++})).finally((()=>{t&&t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(r,0)}initLogger(){const{config:e}=this;e.showSlogan&&console.log(`%cLet the browsers become your unlimitedly scalable CDN!\n%c${self.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldA==")}`,"color: dodgerblue; padding:20px 0; font-size: x-large","font-size: medium; padding-bottom:15px");const t=new V(e.logLevel);return e.logger=this.logger=t,t}getExtraForStats(){return{}}getExtraForPeersRequest(){const e={};return e.num_want=this._getNumWant(),e}_getNumWant(){const{tracker:e}=this;if(!e.scheduler)return;const t=e.scheduler.peersNum;return t>0&&e.maxConnsActive-t>0?e.maxConnsActive-t:void 0}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return I(t)?(i,r)=>`${e}-${t(i,r)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,i=`wss://${self.atob(function(e){let t="c2lnbmFsY2xvdWQuc3dhcm1jbG91ZC5vcmc=";switch(e){case"hk":t="c2lnbmFsLnN3YXJtY2xvdWQub3Jn";break;case"us":t="b3BlbnNpZ25hbC5zd2FybWNsb3VkLm9yZw==";break;case"cn":t="Z3ouc3dhcm1jbG91ZC5uZXQ="}return t}(t.trackerZone))}`;t.signalConfig&&(t.wsSignalerAddr=t.signalConfig);const{wsSignalerAddr:r}=t;if(r){let s;"object"==typeof r?(r.main||(r.main=i),s=r.main):"string"==typeof r&&(s=r,t.wsSignalerAddr={main:s}),s===i&&(s=void 0),s&&!t.wsSignalerAddr.backup&&(e=l().parseURL(s).netLoc.substring(2))}else t.wsSignalerAddr={main:i,byDefault:!0};return e}get commonBrowserInfo(){const e=J().getPlatform(),t=J().getNetType()||"wifi";this.netType=t;const{main:i,backup:r,byDefault:s}=this.config.wsSignalerAddr||{};return{signal:i,custom_signal:!s||void 0,signal2:r,device:e,netType:t,player:this.playerName}}get isMobileNet(){return"wifi"!==this.netType&&"ethernet"!==this.netType}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",i=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,i)};e?self.removeEventListener(t,i):self.addEventListener(t,i)}destroy(){clearTimeout(this.rangeRequestTimer),this.disableP2P(!0),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return re.version}static isSupported(){const e=m();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,i){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${i}`);let r=4;return t<=2?r=1.5:t<=3?r=2:t<=4?r=2.5:t<=5?r=3:t<=6&&(r=3.5),r}emitEvent(e,...t){this.emit(e,...t);const i=ie[e];i&&I(this.config[i])&&this.config[i](...t)}}re.version="2.16.4",re.protocolVersion=ee.VERSION;const se=re;function ne(){if(!function(){if("object"==typeof self)return self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}())return!1;const e=self.SourceBuffer||self.WebKitSourceBuffer;return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function ae(e,t){let i;if(e&&("string"==typeof e?(i=document.querySelector(e),oe(i)||(i=function(e){const t=document.getElementById(e);if(oe(t))return t;if(!t)return null;const i=t.getElementsByTagName("*");for(let e=0;e<i.length;e++)if(oe(i[e]))return i[e];return null}(e))):e instanceof HTMLMediaElement&&(i=e)),!i){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?i=e[0]:(t&&(i=e.find((e=>e.src===t))),i||(i=e.find((e=>e.currentTime>0))))}return i}function oe(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function le(e,t,i,r=0,s=0){const n=u;let a=r,o=s||i-1;const l=Math.floor(i/n),h=i%n>0?l+1:l;if(e>=0&&(a+=(e+1)*n),t>=0&&t<h){o-=i%n+(h-t-1)*n}return{rangeStart:a,rangeEnd:o+1}}function he(e,t){return`${e}-${t}`}function ue(e,t,i,r){let s=i.split("?")[0];return s.startsWith("http")&&(s=s.split("://")[1]),r?`${s}|${r}`:`${s}`}function de(e,t){return"number"!=typeof t&&(t=Number(t)),`${t}-${e}`}let ce={wsMaxRetries:10,p2pEnabled:!0,signalCompact:!0,wifiOnly:!1,memoryCacheLimit:{pc:419430400,mobile:104857600},dcDownloadTimeout:25,logLevel:"error",webRTCConfig:{},token:void 0,appName:void 0,appId:void 0,prefetchNum:3,showSlogan:!1,trickleICE:!0,announceLocation:"eu",trackerZone:void 0,geoIpPreflight:!0,ICEPreflight:!0,useDiskCache:!0,startFromSegmentOffset:3,getStats:function(e,t,i){},getPeerId:function(e){},getPeersInfo:function(e){}};const fe={...ce,httpLoadTime:0,sharePlaylist:!1,useHttpRange:!0,hlsjsInstance:null,proxyOnly:!1,proxyFirst:!1,p2pBlackList:["vtt","webvtt","key"],live:!0,swFile:"./sw.js",swScope:"./",swAutoRegister:!0,mediaElem:void 0,httpStreamEnabled:!0,diskCacheLimit:{pc:1572864e3,mobile:1048576e3},strictSegmentId:!1,prefetchOnly:!1},ge=1e3;function pe(e){const t=new Promise(((t,i)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>i(e.error)})),i=(r=ge,s="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(s)}),r))));var r,s;return Promise.race([t,i])}const ve={};async function me(e,t,i=!0){const r=ve[e]||{};r.promise||(r.promise=new Promise((e=>r.resolve=e)),ve[e]=r,Ee(e,t,r.resolve,i));const s=await r.promise;return delete r.promise,s}const ye={};async function Ee(e,t,i,r){if(!ye[e]){const r=indexedDB.open(e);return r.onupgradeneeded=()=>{const e=r.result;t.forEach((t=>{e.createObjectStore(t)}))},void i(ye[e]=await pe(r))}if(r)try{t.forEach((t=>{ye[e].transaction(t)})),i(ye[e])}catch(s){console.error(`Could not open a transaction on "${e}" due to ${s.name} (${s.message}). Trying to reopen the connection...`),delete ye[e],Ee(e,t,i,r)}else i(ye[e])}let Se;function Te(){return Se||(Se=createStore("keyval-store","keyval")),Se}function _e(e,t=Te()){return t("readonly",(t=>pe(t.get(e))))}function Le(e,t,i=Te()){return i("readwrite",(i=>(i.put(t,e),pe(i.transaction))))}function be(e,t=Te()){return t("readwrite",(t=>(t.delete(e),pe(t.transaction))))}function Ae(e=Te()){return e("readwrite",(e=>(e.clear(),pe(e.transaction))))}function Ie(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},pe(e.transaction)}const Re="size";class Pe extends(n()){constructor(e,t){super(),this.name="SegmentStore",this.logger=t.logger,this.logger.info(`use ${this.name}`),this.engine=e,this.channel=e.channel;const i=e.browserInfo.device;this.isPC=i===J().device.PC_WEB||i===J().device.PC_NATIVE,this.maxBufSize=this.isPC?t.diskCacheLimit.pc:t.diskCacheLimit.mobile,this.overflowed=!1,this.countErrors=0,this.isCleared=!0,this.destroyed=!1}async setupStore(){if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate(),t=Math.floor(e.quota-e.usage);t<this.maxBufSize&&(this.maxBufSize=t-104857600)}return new Promise((async(e,t)=>{if(this.isPC&&this.maxBufSize<419430400||!this.isPC&&this.maxBufSize<104857600)return void t("disk storage not enough");const i=this.stores;let r;try{r=function(e,t){let i=me(e,t);return t.map((r=>(s,n)=>i.then((a=>{try{const e=a.transaction(r,s).objectStore(r);return n(e)}catch(a){i=me(e,t),i.then((e=>n(e.transaction(r,s).objectStore(r))))}}))))}(this.channel,i)}catch(e){return void t(e)}this._createStores(r),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return Le(Re,0,this.metaStore)}currBufSize(){return new Promise((async(t,i)=>{try{const r=await _e(Re,this.metaStore);if(isNaN(r))return this.engine.emit(e.BM_FATAL_ERROR),void i("size is NaN");t(r)}catch(e){i(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:i}=this;if(_(t.data))return new Promise((r=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),this.countErrors=0,r()})).catch((e=>{this._handleFataError(),e&&(i.warn(`putSeg ${e}`),("QuotaExceededError"===e.name||e.inner&&"QuotaExceededError"===e.inner.name)&&this.currBufSize().then((e=>{this._trimDisk(e,!0)})).catch((e=>{this.logger.error(`trimDisk ${e}`)}))),r()}))}));i.error(`putSeg ${t.segId} is not buffer`)}_handleFataError(){this.countErrors++,this.countErrors>=3&&(this.engine.emit(e.BM_FATAL_ERROR),this.countErrors=0)}_decreaseBufSize(e){this.currBufSize().then((t=>{t&&Le(Re,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(e){this.destroyed||this.currBufSize().then((t=>{Le(Re,t+e,this.metaStore),this._trimDisk(t+e)})).catch((e=>{this.logger.warn(`increaseBufSize ${e}`)}))}clear(e=!1){if(!this.isCleared){this.logger.warn("clear segment store");try{this._clearDisk(e)}catch(e){}this.isCleared=!0}}_clearDisk(e){Ae(this.segmentsStore),e?this._initMetaStore():Ae(this.metaStore),this.overflowed=!1}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}static toSegment(e){const t=new X(e.sn,e.segId,e.data,e.fromPeerId,e.level,e.ext);return t.from=e.from,t}}const ke=Pe;const De=class extends ke{constructor(e,t){super(e,t),this.loadingSN=-1,this.stores=["segments","id2Sn","metadata"]}_createStores(e){this.segmentsStore=e[0],this.id2SnStore=e[1],this.metaStore=e[2]}async hasSegOfId(e){if(!e)return Promise.resolve(!1);let t;try{t=await _e(e,this.id2SnStore)}catch(e){return Promise.resolve(!1)}return new Promise((i=>{void 0!==t?_e(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?i(!0):i(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),i(!1)})):i(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let i;try{i=await _e(e,this.id2SnStore)}catch(e){return null}return new Promise((r=>{void 0!==i?_e(i,this.segmentsStore).then((i=>{if(this.countErrors=0,i&&i.length>0){const s=i.find((t=>t.segId===e));if(!s)return void r(null);if(!_(s.data))return t.error(`getSegById ${s.sn} is not buffer`),void r(null);r(ke.toSegment(s))}else r(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),r(null)})):r(null)}))}getSegIdBySN(e){return new Promise((t=>{_e(e,this.segmentsStore).then((e=>{e&&e.length>0?t(e[0].segId):t(null)})).catch((e=>{this.logger.warn(`getSegIdBySN ${e}`),t(null)}))}))}_addSeg(e){const{segId:t,sn:i,size:r}=e;return Le(t,i,this.id2SnStore),new Promise(((s,n)=>{_e(i,this.segmentsStore).then((async a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(await this._segmentToCache(e)),Le(i,a,this.segmentsStore).then((()=>{this._increaseBufSize(r),s(e)})).catch((e=>{n(e)}))):s(e):Le(i,[await this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(r),s(e)})).catch((e=>{n(e)}))})).catch((e=>{n(e)}))}))}async _trimDisk(t,i=!1){if(this.isCleared||this.destroyed)return;let r=this.maxBufSize;const{logger:s}=this;i&&(r=t-104857600,r<0&&(r=0)),t<r||(s.warn(`_trimDisk currentSize ${t} upBound ${r}`),function(e=Te()){return e("readonly",(e=>{if(e.getAllKeys)return pe(e.getAllKeys());const t=[];return Ie(e,(e=>t.push(e.key))).then((()=>t))}))}(this.segmentsStore).then((async i=>{const n=i.sort(((e,t)=>e-t));let a=0;do{if(a++>10){s.warn("too much loops in SegmentStore");break}const i=n.shift();if(void 0===i){s.warn("lastSN not found");continue}if(i>=this.loadingSN){s.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const r=n[0],o=await _e(i,this.segmentsStore);if(!o){s.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),be(i,this.segmentsStore).then((()=>{this._decreaseBufSize(parseInt(l))})),o.forEach((t=>{be(t.segId,this.id2SnStore),s.info(`pop seg ${t.segId} size ${t.data.byteLength}`),this.emit(e.BM_LOST,{sn:i,segId:t.segId,next:r,level:t.level})})),t-=l,s.info(`pop sn ${i} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=r)})))}async _segmentToCache(e){const{ext:t={}}=e;let i=t.hash;i||(i=await w(e.data));const r={data:e.data,level:e.level,segId:e.segId,sn:e.sn,fromPeerId:e.fromPeerId,ext:{}};return i&&(r.ext.hash=i),r}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}Ae(this.id2SnStore).catch((e=>{}))}};class we extends(n()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const i=e.browserInfo.device;if(this.maxBufSize=i===J().device.PC_WEB||i===J().device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,this.isLive=t.live,this.isLive)this.maxBufSize=47185920;else{if(0===this.maxBufSize)throw new Error("cannot use SegmentCache");const e=function(){const{memory:e}=performance;return e?e.jsHeapSizeLimit-e.usedJSHeapSize:-1}();e>=0&&e<this.maxBufSize&&(this.maxBufSize=e-31457280)}this._segPool=new Map,this._currBufSize=0,this.overflowed=!1,this.isCleared=!0,this.destroyed=!1}get currBufSize(){return this._currBufSize}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}async putSeg(e){this.destroyed||(this.isCleared=!1,this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),_(e.data)?this._addSeg(e):this.logger.error(`putSeg ${e.segId} is not buffer`))}clear(){this.isCleared||(this.logger.warn("clear segment cache"),this._segPool.clear(),this._currBufSize=0,this.isCleared=!0,this.overflowed=!1)}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const Ce=we;const Me=class extends Ce{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,i)=>{const r=this.id2Sn.get(e);this._segPool.has(r)?t(this._segPool.get(r).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((i,r)=>{if(!this._segPool.has(t))return void i(null);const s=this._segPool.get(t).find((t=>t.segId===e));i(s||null)}))}getSegIdBySN(e){return new Promise(((t,i)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}async _addSeg(t){const{logger:i}=this,{segId:r,sn:s,size:n,ext:a={}}=t;if(this.id2Sn.set(r,s),a.hash||(a.hash=await w(t.data),t.ext=a),this._segPool.has(s)){this._segPool.get(s).push(t)}else this._segPool.set(s,[t]);this._currBufSize+=parseInt(n);const o=this._segPool.size;if(this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t),this._currBufSize<this.maxBufSize||o<=5)return;let l=Array.from(this._segPool.keys());this.isLive||(l=l.sort(((e,t)=>e-t)));let h=0;do{if(h++>10){i.error("too much loops in SegmentCache");break}const t=l.shift();if(void 0===t){i.error("lastSN not found");continue}const r=l[0],s=this._segPool.get(t);if(!s){i.error("lastSeg not found");continue}let n=0;s.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(t),s.forEach((i=>{this.id2Sn.delete(i.segId),this.emit(e.BM_LOST,{sn:t,segId:i.segId,next:r,level:i.level})})),i.info(`pop sn ${t} size ${n} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>5)}clear(){super.clear(),this.id2Sn.clear()}};var Oe=i(832),xe=i.n(Oe);function Fe(e,t){for(const i in t)Object.defineProperty(e,i,{value:t[i],enumerable:!0,configurable:!0});return e}const Ne=function(e,t,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof t&&(i=t,t=void 0),null!=t&&(i.code=t);try{return Fe(e,i)}catch(t){i.message=e.message,i.stack=e.stack;const r=function(){};return r.prototype=Object.create(Object.getPrototypeOf(e)),Fe(new r,i)}};class Be{constructor(){this.p2p=0,this.share=0,this.http=0}recordP2p(e){this.p2p+=e}recordShare(e){this.share+=e}recordHttp(e){this.http+=e}resetTraffic(){this.p2p=0,this.share=0,this.http=0}get healthRatio(){if(0===this.http)return 1e3;let e=Math.round((this.p2p+this.share)/this.http*100);return e<=0&&(e=1),e}}const Ue="SW_GEOIP_KEY",Ge=2592e5,He=432e5,Ke="TRACKER_EXPT",Ve="IPAPI_ERROR",$e="uY2R",We="LmNv",qe="uYnll",je="bQ==",Ye="Z3o",ze=Symbol("httpDownloaded"),Xe=Symbol("p2pDownloaded"),Qe=Symbol("p2pUploaded");class Je extends(n()){constructor(e,t,i,r,s){let n;super(),this.config=e.config;let a=this.config.announceLocation;switch(this.config.trackerZone&&(a=this.config.trackerZone),a){case"hk":n="aGsubWVzaGlmeS5jbG91ZA==";break;case"us":n="dXMubWVzaGlmeS5jbG91ZA==";break;case"cn":n=Ye+$e+qe+We+je;break;default:n="ZXUubWVzaGlmeS5jbG91ZA=="}this.engine=e,this.key=t||void 0,Array.isArray(r)&&(r=r[Math.floor(Math.random()*r.length)]),this.baseUrl=r||`https://${self.atob(n)}/v1`,this.channelId=self.btoa(i),this.timestamp=g(),this.health=new Be;const o=l().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,""),function(e,t){function i(e,t,i,r,s){return h(i-219,s)}var r,s,n=e();function a(e,t,i,r,s){return h(s- -994,e)}function o(e,t,i,r,s){return h(r-233,t)}function l(e,t,i,r,s){return h(s-305,i)}for(;;)try{if(156690===-parseInt(o(0,246,0,247))/1*(-parseInt(o(0,243,0,248))/2)+-parseInt(o(0,238,0,245))/3+parseInt(a(-1e3,0,0,0,-989))/4*(-parseInt(i(0,0,225,0,216))/5)+-parseInt((r=-180,s=-173,h(s- -181,r)))/6*(parseInt(l(0,0,324,0,324))/7)+-parseInt(a(-991,0,0,0,-990))/8*(parseInt(l(0,0,313,0,307))/9)+-parseInt(l(0,0,310,0,305))/10+-parseInt(a(-968,0,0,0,-974))/11*(-parseInt(i(0,0,226,0,216))/12))break;n.push(n.shift())}catch(e){n.push(n.shift())}}(d);function h(e,t){var i=d();return(h=function(e,t){return i[e-=0]})(e,t)}const u=function(e,t,i,r,s,n){let a=location.hostname;a===h(-922- -923,-915)&&n&&(a=n+"."+a);return 13,xe()(a+"2.16.4"+i+r+s,e).substr(0,8)}(this.timestamp,0,this.announce,this.channelId,s.type,this.key);function d(){var e=["13055AgbnUs","2739cfXSxI","CxYEuy093515".split("").reverse().join(""),"localhost","OCXDId9".split("").reverse().join(""),"yek".split("").reverse().join(""),"QyapiZ8635101".split("").reverse().join(""),"scRrUF02".split("").reverse().join(""),"bNcslL58187".split("").reverse().join(""),"QEbZrW65772".split("").reverse().join(""),"12gYmKGR","emantsoh".split("").reverse().join(""),"dIlennahc".split("").reverse().join(""),"pmatsemit".split("").reverse().join(""),"676614MZdLCs","type","hpNRbU1".split("").reverse().join(""),"133332xoUKrS","announce","lmia","substr"];return(d=function(){return e})()}h(895-878,886),this.native=!(!s.bundle||!window.electron&&!navigator.userAgent.toLowerCase().includes("electron")),this.announceInfo={...s,channel:this.channelId,ts:this.timestamp,version:"2.16.4",v:u,announce:this.announce,k:it(this.key)},this.announceURL=`${this.baseUrl}/channel`,this.reportFails=0,this.statsRequesting=!1,this.forbidden=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[ze]=0,this[Xe]=0,this[Qe]=0,this.speed=0,this.offline=!1,this.errsBufStalled=0,this.mediaRequests=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,i)=>{if((e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return!(!e.duration||!e.startTime)&&Date.now()-e.startTime<e.duration}catch(e){return!1}})(Ue)){const i=G(Ue);e.info("found local geo data"),t(i)}else fetch(self.atob("aHR0cHM6Ly9wcm8uaXAtYXBpLmNvbS9qc29uP2ZpZWxkcz0yMTgxODI2JmtleT1YT3BpYW5zUmdZeEdUaG8=")).then((e=>e.json())).then((e=>{if("success"!==e.status){const t=new Error(`preflight status ${e.status}`);throw Ne(t,Ve)}{const i=e.mobile?He:Ge;H(Ue,e,i),t(e)}})).catch((e=>{i(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(Ne(new Error("request timeout"),Ve))}),600)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(t.code!==Ke){const t=G(Ue);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:i,isp:r,as:s,mobile:n,countryCode:a,continentCode:o}=e;n&&(this.announceInfo.netType="cellular");const l=s.split(" ")[0].substr(2);this.announceInfo={...this.announceInfo,lat:t,lon:i,isp:r,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,i)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>{if(!e.ok){const t=e.status>=500&&e.status<600;throw Ne(new Error(`server response code is ${e.status}`),Ke,{retry:t})}return e.json()})).then((e=>{if(!this.engine)throw Ne(new Error("runtime error"),Ke,{retry:!1});const i=e.data;if(i.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:i}=e.data;throw Ne(new Error(i),Ke,{retry:t>=5e3})}if(i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),i.min_conns||(i.min_conns=8),(!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval&&i.peers){if(this.peerId=this.id=i.id,i.report_interval<20&&(i.report_interval=20),this.btStats(i.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,!this.announceInfo.asn&&i.asn){const{country:e,asn:t,mobile:r,isp:s,lat:n,lon:a}=i;this.announceInfo={...this.announceInfo,country:e,asn:t},H(Ue,{countryCode:e,as:`AS${t}`,mobile:r,isp:s,lat:n,lon:a,status:"success"},r?He:Ge)}t(i)}else this.engine&&(this.engine.p2pEnabled=!1)})).catch((t=>{e.error(`btAnnounce error ${t}`);const r=t.code||Ke,s=!t.code||t.retry;i(Ne(t,r,{retry:s}))}))}))}btStats(e=10){this.heartbeater=setInterval((()=>{this.postStats()}),1e3*e)}postStatsWithBeacon(){if(this.offline)return;this.offline=!0;let e={off:!0};this.statsRequesting||(e={...e,...this._makeStatsBody()}),this.statsURL&&navigator.sendBeacon&&navigator.sendBeacon(this.statsURL,JSON.stringify(e))}postStats(){const{logger:t}=this.engine;this.statsRequesting=!0,fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.statsRequesting=!1,this.reportFails=0,e.text()))).then((i=>{let r;if(r=i?JSON.parse(i):{ret:0,data:{}},-1===r.ret)clearInterval(this.heartbeater),t.error(`${r.data.msg} code ${r.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:i=0,failConns:r=0,rebuffers:s=0,requests:n=0,errsInternalExpt:a=0}=this.lastStats||{};this[ze]>=e&&(this[ze]-=e),this[Xe]>=t&&(this[Xe]-=t),this[Qe]>=i&&(this[Qe]-=i),this.failConns>=r&&(this.failConns-=r),this.errsBufStalled>=s&&(this.errsBufStalled-=s),this.mediaRequests>=n&&(this.mediaRequests-=n),this.errsInternalExpt>=a&&(this.errsInternalExpt-=a),this.exptMsg&&(this.exptMsg=void 0)}})).catch((e=>{t.error(`btStats error ${e}`),this.statsRequesting=!1,this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e,t=!1){const{logger:i}=this.engine,{asn:r,country:s}=this.announceInfo;let n={exclusions:e,asn:r,country:s,ratio:this.health.healthRatio,urgent:t||void 0},a={};return this.engine.getExtraForPeersRequest&&(a=this.engine.getExtraForPeersRequest()),n=Object.assign({},n,a),new Promise(((e,t)=>{this.reportFails>=3?t(new Error("reportFails >= 3")):fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(n)}).then((e=>e.json())).then((i=>{-1===i.ret?t(i.data.msg):e(i.data)})).catch((e=>{i.error(`btGetPeers error ${e}`),t(e)})).finally((()=>{this.health.resetTraffic()}))}))}increFailConns(){this.failConns++}increRebuffers(){this.engine.emitEvent("bufferStalled"),this.errsBufStalled++}increMediaRequests(){this.mediaRequests++,this.engine.emit(e.MEDIA_REBUFFER,this.errsBufStalled>=2)}reportFlow(e){const t=Math.round(e/1024);this.engine.emitEvent("httpDownloaded",t),this[ze]+=t,this.totalHTTPDownloaded+=t,this.health.recordHttp(t),this._emitStats()}reportDCTraffic(e,t){const i=Math.round(e/1024);this[Xe]+=i,this.totalP2PDownloaded+=i,this.health.recordP2p(i),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",i,this.speed),this._emitStats()}reportUploaded(e=0){const t=Math.round(e/1024);this.engine.emitEvent("p2pUploaded",t),this.totalP2PUploaded+=t,this.health.recordShare(t),this[Qe]+=t,this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),this.removeAllListeners(),clearInterval(this.heartbeater)}_emitStats(){const{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:i}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:i,p2pDownloadSpeed:this.speed});const{getStats:r}=this.config;I(r)&&r(t,i,e,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let i={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,rebuffers:this.errsBufStalled||void 0,requests:this.mediaRequests||void 0,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[ze])||0,p2p:Math.round(this[Xe])||0,share:Math.round(this[Qe])||0,asn:e,country:t},r={};this.engine.getExtraForStats&&(r=this.engine.getExtraForStats()),i=Object.assign({},i,r),this.lastStats=JSON.parse(JSON.stringify(i)),Object.keys(i).forEach((e=>{0===i[e]&&delete i[e]}));const{logger:s}=this.engine;return s.isDebugLevel&&s.info(`report ${JSON.stringify(i)}`),this.exptMsg&&(i.exptMsg="2.16.4 "+this.exptMsg),i}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":it(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const Ze=Je;function et(e,t){const i=tt();return(et=function(e,t){return i[e-=0]})(e,t)}function tt(){const e=["CsLPpZ8932212".split("").reverse().join(""),"htgnel".split("").reverse().join(""),"UZpUzY5895021".split("").reverse().join(""),"yJZuxA9452121".split("").reverse().join(""),"tAedoCrahc".split("").reverse().join(""),"btoa","q#<K@C".split("").reverse().join(""),"1164HyWkyu","4154136SJSwNe","IITNvu6344771".split("").reverse().join(""),"edoCrahCmorf".split("").reverse().join(""),"554Biqadw","oShtCc7412072".split("").reverse().join("")];return(tt=function(){return e})()}function it(e){if(!e)return;const t=et(-822- -830,-826);let i="".split("").reverse().join("");const r=t.length;for(let s=0;s<e.length;s++){const n=e.charCodeAt(s)^t.charCodeAt(s%r);i+=String.fromCharCode(n)}return self.btoa(i)}!function(e,t){const i=e();function r(e,t,i,r,s){return et(e-92,s)}function s(e,t,i,r,s){return et(s-930,i)}for(;;)try{if(377468===parseInt(s(0,0,944,0,939))/1*(parseInt(s(0,0,936,0,930))/2)+parseInt(s(0,0,929,0,935))/3+parseInt(s(0,0,939,0,941))/4+-parseInt((n=-995,a=-995,et(n- -999,a)))/5+parseInt(r(94,0,0,0,91))/6+-parseInt(r(93,0,0,0,92))/7+-parseInt(r(102,0,0,0,107))/8)break;i.push(i.shift())}catch(e){i.push(i.shift())}var n,a}(tt);class rt extends(n()){constructor(e,t){super(),this.logger=e,t.startsWith("wss")?this.addr=t.replace("wss","https"):t.startsWith("ws")&&(this.addr=t.replace("ws","http")),this.connected=!1,this.retryCount=0,this.closed=!1,this.msgQueue=[],this.posting=!1,this.pollingTs=0}start(){this.closed=!1,this._hello((()=>{this._longPolling()}))}_hello(e){fetch(this.addr+"&hello",{method:"POST"}).then((e=>{if(!e.ok)throw new Error("hello response was not ok");return e.json()})).then((t=>{this.connected=!0,e(),this.onopen&&this.onopen(t.ver)})).catch((e=>{this.closed=!0,this.onerror&&this.onerror(e)}))}send(e){this.msgQueue.push(e),this.posting||this._realSend([...this.msgQueue])}_realSend(e){0!==e.length&&(this.posting=!0,this.msgQueue=[],fetch(this.addr,{method:"POST",body:JSON.stringify(e)}).then((()=>{this.posting=!1,this.msgQueue.length>0&&this._realSend([...this.msgQueue])})).catch((e=>{this.logger.error(e),this.posting=!1})))}close(){this.connected&&(this.closed=!0,this.connected=!1,this.abortController&&(this.abortController.abort(),this.abortController=null),this.onclose&&this.onclose())}destroy(){this.close(),this.removeAllListeners()}_longPolling(){if(this.closed)return;this.pollingTs=g(),this.abortController=new AbortController;const e=this.abortController.signal;fetch(this.addr,{signal:e}).then((e=>{if(!e.ok)throw new Error("polling response was not ok");return e.text()})).then((async e=>{e&&this.onmessage&&this.onmessage(JSON.parse(e)),this.retryCount=0;const t=g()-this.pollingTs;JSON.stringify(e)===JSON.stringify(this.lastData)&&t<10&&(this.logger.warn(`wait ${10-t}s for next polling`),await v(1e3*(10-t))),this.lastData=e,this._longPolling()})).catch((e=>{this.connected&&(this.retryCount<=3?(this.retryCount++,this._longPolling()):(this.connected=!1,this.onerror&&this.onerror(e)))}))}}const st=class{constructor(e,t,i,r="main"){this.logger=e,this.config=t,this.wsAddr=i,this.serverVersion=0,this.pingInterval=95e3,this.name=r,this.normalClosed=!1,this.lastSendTs=performance.now(),this.pollingClient=new rt(e,i);try{this._ws=this._init()}catch(t){e.error(t),this._startPolling()}}get batchSupported(){return this.serverVersion>=50}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:p(15e3,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20,connectionTimeout:7e3};let t=new N(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.normalClosed=!1,this.pollingClient.connected?this.pollingClient.close():this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{this.lastSendTs=performance.now();let i=JSON.stringify(e);t.push(i)},t.addEventListener("message",(e=>{let t=e.data;const i=JSON.parse(t),r=i.action;if("pong"!==r){if("ver"!==r)return"close"===r?(this.logger.warn(`server close signal ${this.name} reason ${i.reason}`),void this.close()):void("signals"!==r?this.onmessage&&this.onmessage(i,this.name):this._onSignalBatch(i.data));this.serverVersion=i.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),e.code>=5e3||e.code<4e3?(this.onclose&&this.onclose(),this._stopPing()):this.close()})),t.addEventListener("error",(e=>{this._stopPing(),this.onerror&&this.onerror(e),this._startPolling()})),t}forcePolling(){this.pollingClient.connected||(this.close(),this.pollingClient=new rt(this.logger,this.wsAddr),this._startPolling())}_startPolling(){this.pollingClient.connected||(this.logger.info(`${this.name} start polling`),this.pollingClient.start(),this._setupPolling(this.pollingClient))}sendDebug(e,t,i){this._send({action:"debug",details:t,ping:i||void 0,to:e})}sendSignal(e,t){const i={action:"signal",to:e,data:t};this._send(i)}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let i of t)this.sendSignal(e,i)}sendReject(e,t,i){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const r={action:"reject",to:e,reason:t,fatal:i};this._send(r)}_send(e){this.pollingClient.connected?this.pollingClient.send(e):this._ws&&this._ws.send(e)}_startPing(e){this.connected&&(this.pingTimer=setTimeout((()=>{const e=95e3-(performance.now()-this.lastSendTs);if(e>=0)return this._startPing(e);const t={action:"ping"};this._ws&&this._ws.push(JSON.stringify(t)),this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),15e3),this._startPing(this.pingInterval)}),e))}_stopPing(){clearTimeout(this.pingTimer),clearTimeout(this.pongTimer)}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3)})(),this.pollingClient.close(),this.normalClosed=!0}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.pollingClient.destroy()}get connected(){return!!this.pollingClient.connected||this._connected}get _connected(){return!!this._ws&&this._ws.readyState===N.OPEN}_setupPolling(e){e.onopen=e=>{e&&(this.serverVersion=e),this.logger.info(`${this.name} polling opened`),this.onopen&&this.onopen()},e.onerror=e=>{this._connected||this.onerror&&this.onerror(e)},e.onclose=()=>{this._connected||this.onclose&&this.onclose()},e.onmessage=e=>{if(this.onmessage)for(let t of e)"signals"===t.action?this._onSignalBatch(t.data):this.onmessage(t,this.name)}}_onSignalBatch(e){if(this.onmessage)for(let t of e)t.action||(t.action="signal"),this.onmessage(t,this.name)}},nt=class{constructor(e,t,i,r){this.logger=e,this.config=t,this.mainAddr=i,this.backupAddr=r,this.mainWS=this._init(i),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(r,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let i=new st(this.logger,this.config,e,t);return i.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},i.onmessage=e=>{this.onmessage&&this.onmessage(e,i.name)},i.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},i.onerror=e=>{this.onerror&&this.onerror(e)},i}sendSignalBatch(e,t,i){if(i){const r=this._getWSByName(i);r&&r.sendSignalBatch(e,t)}else this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected&&this.backupWS.sendSignalBatch(e,t)}sendSignal(e,t,i){this.sendSignalBatch(e,[t],i)}sendReject(e,t,i,r){if(r){const s=this._getWSByName(r);if(s)return void s.sendReject(e,t,i)}this.mainConnected?this.mainWS.sendReject(e,t,i):this.backupConnected?this.backupWS.sendReject(e,t,i):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,i){this.mainConnected&&this.mainWS.sendDebug(e,t,i)}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close(),this.normalClosed=!0}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(e){this.mainWS&&"backup"!==e&&this.mainWS.reconnect(),this.backupWS&&"main"!==e&&this.backupWS.reconnect()}forcePolling(e){this.mainWS&&"backup"!==e&&this.mainWS.forcePolling(),this.backupWS&&"main"!==e&&this.backupWS.forcePolling()}destroy(){this.close(),clearTimeout(this.backupTimer),this.mainWS=null,this.backupWS=null,this.destroyed=!0}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}};const at=function(e,t,i=40){var r=null,s=!1,n=i;return function(i=!1){if(i)return clearTimeout(r),void(s=!1);s||(s=!0,r=setTimeout((function(){e.call(t,n),s=!1,r=null}),1e3*n),n*=1.1)}};class ot{constructor(e,t,i=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=i,this.pool=[],t.ICEPreflight&&this.reset(),this.trickle=!1}reset(){this.destroy();for(let e=0;e<this.poolSize;e++)this.pool.push(this._createPeer())}_createPeer(){return new ee(this.engine,void 0,void 0,!0,this.config,{trickle:this.trickle})}get available(){return 0!==this.pool.length&&this.pool[0].signalMsgs.length>0}getPeer(){if(0===this.pool.length)return this._createPeer();const e=this.pool.shift();return this.pool.length<5&&this.pool.push(this._createPeer()),e}destroy(){for(let e of this.pool)e.destroy(!0);this.pool=[]}}const lt=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,i=0,r="";for(const s of e){if("="===s)break;const e=this.CHARSET.indexOf(s);for(t=t<<this.BITS_PER_BASE64_CHAR|e,i+=this.BITS_PER_BASE64_CHAR;i>=this.BITS_PER_BYTE;){i-=this.BITS_PER_BYTE;r+=(t>>i&(1<<this.BITS_PER_BYTE)-1).toString(16).padStart(2,"0").toUpperCase()}}let s="";for(let e=0;e<r.length;e++)s+=r[e],e%2==1&&e!==r.length-1&&(s+=":");return s}},ht="typ host",ut="generation 0",dt="network-cost",ct="rport",ft="0.0.0.0",gt={V:"v=",O:"o=",S:"s=",C:"c=",A:"a=",M:"m=",T:"t="},pt={U:"ice-ufrag:",P:"ice-pwd:",F:"fingerprint:",C:"candidate:",S:"sctp-port:",M:"max-message-size:"},vt={1:"sha-1",2:"sha-224",3:"sha-256",4:"sha-384",5:"sha-512",6:"md5",7:"md2",8:"token"},mt={P:`${ht} ${ut} ${dt} 999`,W:`${ct} 0 ${ut} ${dt} 999`,H:ht,S:"typ srflx",R:ct,A:"raddr",V:ft,F:"ufrag",G:`${ct} 0 ${ut}`,N:dt,E:"network-id",C:"tcptype active",Q:`${ut}`,U:"udp",T:"tcp"},yt={P:"application",U:"UDP/DTLS/SCTP",S:"DTLS/SCTP",D:"webrtc-datachannel"},Et={4:"IP4",6:"IP6"},St={0:ft},Tt=e=>(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in mt&&(e=mt[e]),e))).join(" "));function _t(e,t){let i=e.split("~"),r=[];i=i.map((e=>{let t=e.slice(0,1),i=e.slice(1);if(t in gt&&(t=gt[t]),"a="===t){let e=i.slice(0,1);const t=i.slice(1);e in pt&&(e=pt[e],i=e+t)}return t+i})),r.push("v=0"),r.push("s=-"),r.push("t=0 0"),r.push("a=msid-semantic: WMS");let s=0;i.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),i=[];i.push("-");const s=t.shift();if(s&&i.push(s),0===t.length)i.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&i.push(e),0===t.length)i.push("IN IP4 127.0.0.1");else{i.push("IN");const e=t.shift();e&&i.push(e);const r=t.shift();r&&i.push(r)}}r.splice(1,0,`o=${i.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(Lt,(e=>yt[e]))}(e),r.push(e),r.push("a=setup:"+(t?"actpass":"active")),r.push(`a=mid:${s}`),void s++;if(e.startsWith("a=candidate:"))return e=Tt(e),void r.push(e);if(e.startsWith("a=fingerprint:")){let[t,i]=e.slice(14).split(" ");return t in vt&&(t=vt[t]),i=lt.decode(i),void r.push(`a=fingerprint:${t} ${i}`)}if(e.startsWith("c=")){let[t,i]=e.slice(2).split(" ");return t in Et&&(t=Et[t]),i in St&&(i=St[i]),void r.push(`c=IN ${t} ${i}`)}"I"!==e?"Z"!==e?"B"!==e?r.push(e):r.push("a=sendrecv"):r.push("a=ice-options:ice2,trickle"):r.push("a=ice-options:trickle")}}));const n=r.length-1;return r.splice(n,0,`a=group:BUNDLE ${Array.from(Array(s).keys()).join(" ")}`),r.join("\r\n")}const Lt=new RegExp(Object.keys(yt).join("|"),"g");class bt extends(n()){constructor(e,t,i,r){super(),this.engine=e,this.logger=e.logger,this.config=r,this.connected=!1,this.scheduler=i,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set;const s=J().isMobile();this.peerPool=new ot(e,r,15),this.signalerWs=null,this.fetcher=t,this.peers=[],this.requestPeersQueue=[],this.minConns=5,this.stuns=[],this.requestMorePeers=at(this._requestMorePeers,this,p(35,45)),this.maxConns=s?15:22,this.maxConnsActive=s?10:13,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.requestPeersWaitCount=0,this.gotSignalFails={main:0,backup:0,limit:5},this.fuseRate=-1,this.overloaded=!1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:t,config:i,fetcher:r}=this,{btAnnounce:s,btAnnouncePreflight:n}=r,{wsSignalerAddr:a,wifiOnly:o,geoIpPreflight:l}=i;(l?n:s).call(r).then((e=>{const{scheduler:i}=this;if(!i)return;t.peerId=this.peerId=e.id,this.minConns=e.min_conns,i.minConns=this.minConns;const s=e.peers;i.notifyPeersLoaded(s.length),s.length>this.gotSignalFails.limit&&(this.gotSignalFails.limit=s.length),t.netType=r.announceInfo.netType,(e.wifi_only||o)&&t.isMobileNet&&(i.downloadOnly=!0,this.logger.info("downloadOnly mode"));const n=a.main;let l=a.backup;e.signal&&!e.signal2&&(l=void 0),this.signalerWs=this._initSignalerWs(e.signal||n,e.signal2||l,e.token,e.token2),0===s.length?this.requestMorePeers():this.peers=this._filterPeers(s),t.emitEvent("peerId",this.peerId),e.stun&&e.stun.length>0&&(this.stuns=e.stun),e.debug&&(this.logger.enableDebug(),e.log_url&&(this.logUploader=new U(e.log_url,this.fetcher.key||location.hostname,this.peerId,"2.16.4"),this.logger.setUploader(this.logUploader))),t.onTrackerResume&&t.onTrackerResume(e),e.fuse_rate&&(this.fuseRate=e.fuse_rate),e.overload&&(this.overloaded=!0,this.logger.warn("server overloaded, degrade signaling")),this.logger.info(`announce request response ${JSON.stringify(e,null,2)}`),/^.\d{2}/.test(this.peerId)||(this.maxConnsActive=1,this.maxConns=2)})).catch((i=>{if(this.scheduler&&("TRACKER_EXPT"===i.code&&t.emitEvent(e.EXCEPTION,i),this.scheduler.notifyPeersLoaded(0),i.retry)){const e=p(15e3,4e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.postStatsWithBeacon(),this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.peerPool.destroy(),this.peerPool=null,this.failedDCMap.clear(),this.notFoundDCSet.clear(),this.logUploader&&(this.logUploader.destroy(),this.logUploader=null),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer),clearTimeout(this.requestPeersTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}isPeerConnectedOrFailed(e){return!e||(this.DCMap.has(e)||this.failedDCMap.has(e)||e===this.peerId)}_filterPeers(e){const t=[];return e.filter((e=>!this.isPeerConnectedOrFailed(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator})})),t}_tryConnectToAllPeers(){const{logger:e}=this;if(0!==this.peers.length)for(this._checkDCMap(),e.info(`try connect to ${this.peers.length} peers, map size ${this.DCMap.size} limit ${this.maxConnsActive} peersNum ${this.scheduler.peersNum}`);this.peers.length>0&&!(this.DCMap.size>=this.maxConnsActive);){let t=this.peers.shift();if(this.isPeerConnectedOrFailed(t.id))continue;const i=t.intermediator;this.signalerWs.connected||i&&this.DCMap.has(i)?(e.debug(`create DataChannel ${t.id} intermediator ${i}`),this._createDatachannel(t.id,!0,i)):e.info(`skip peer ${t.id} without intermediator`)}else e.info("no peers after filter")}_handleSendSignal(e,t){const i=e.remotePeerId;if(e.intermediator){const r=this.DCMap.get(e.intermediator);if(r){let s=!0;for(let e of t)r.sendMsgSignal(i,this.peerId,e)||(s=!1);if(s)return;this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,this.signalerWs.sendSignalBatch(i,t,e.signalName)}_setupDC(t){t.on(e.DC_SIGNAL,(e=>{this._handleSendSignal(t,[e])})).on(e.DC_SIGNAL_BATCH,(e=>{this._handleSendSignal(t,e)})).on(e.DC_PEER_SIGNAL,(e=>{const i=e.to_peer_id||e.to,r=e.from_peer_id||e.from,s=e.action;if(i&&r&&s)if(i!==this.peerId){this.logger.info(`relay signal for ${r}`);const n=this.DCMap.get(i);if(n){if("signal"!==s)return void n.sendMsgSignalReject(i,r,e.reason,e.fatal);if(n.sendMsgSignal(i,r,e.data))return}t.sendMsgSignal(r,i)}else"signal"===s?this._handleSignalMsg(r,e,t.remotePeerId):this._handSignalRejected(r,e)})).on(e.DC_GET_PEERS,(()=>{const e=g(),i=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?15:22)&&!e.super));if(i&&i.length>0){const r=[];i.forEach((i=>{if(i.remotePeerId===t.remotePeerId||i.remotePeerId===this.peerId)return;if(!this.config.live&&(i.currentPos-t.currentPos>600||i.currentPos<t.currentPos))return;e-i.timeJoin>50&&r.push({id:i.remotePeerId,...i.region})})),this.logger.info(`send ${r.length} peers to ${t.remotePeerId}`),t.sendPeers(r)}})).on(e.DC_PEERS,(e=>{const i=e.peers;this.logger.info(`receive ${i.length} peers from ${t.remotePeerId}`),i&&i.length>0&&(i.forEach((e=>{e.intermediator=t.remotePeerId,e.region||(e.region={})})),this.requestPeersQueue.push(...i)),this.requestPeersWaitCount--,this.requestPeersWaitCount<=0&&this._handleRequestedPeers()})).once(e.DC_ERROR,((e,i)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${i}`),this.scheduler&&(this.scheduler.deletePeer(t),this._destroyAndDeletePeer(t.remotePeerId,e),this.fetcher&&(t.connected||e&&this.fetcher.increFailConns(),e&&this.failedDCMap.set(t.remotePeerId,`DC_FAILED ${i}`),this._doSignalFusing(this.scheduler.peersNum),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:i,data:r})=>{const{logger:s,signalerWs:n,gotSignalFails:a}=this,{remotePeerId:o,useBackupSignal:l,isInitiator:h}=t,u=l?"backup":"main";if(e?a[u]=0:(a[u]++,a[u]>=a.limit&&(a[u]=0,s.warn("gotSignalFails many, forcePolling"),n.forcePolling(u))),i&&e&&h&&(this.failedDCMap.set(o,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!e&&h&&!l&&this._tryBackupSignal(t,o,r))return t._startTimer(),void s.warn(`${o} conn timeout, try backup signal`);this._destroyAndDeletePeer(o,!1),this._doPeersRequest()})).once(e.DC_CLOSE,(e=>{this.logger.info(`datachannel ${t.channelId} closed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(t.remotePeerId,e),e&&this.failedDCMap.set(t.remotePeerId,"DC_CLOSE"),this._doPeersRequest()})).once(e.DC_OPEN,(()=>{t.isInitiator&&this.scheduler.handshakePeer(t)})).once(e.DC_METADATA,(e=>{const{scheduler:i}=this;t.isInitiator||i.handshakePeer(t),i.handleMetaData(t,e);const r=this.DCMap.size>=this.maxConnsActive;this.requestMorePeers(r),t.intermediator&&this.peersIncrement++,this._doSignalFusing(i.peersNum)}))}_doPeersRequest(){const e=this.scheduler.peersNum;!this.signalerWs.connected||this.overloaded&&e>this.minConns?this._requestPeersFromPeers(e):this.requestMorePeers(),this._tryConnectToAllPeers()}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e<=this.minConns&&this.signalerWs.normalClosed&&(this.logger.warn(`low conns ${e}, reconnect signaler`),this.signalerWs.reconnect())}_initSignalerWs(t,i,r,s){const n=(e,t)=>{let i=`${e}?id=${this.peerId}&p=web&v=2.16.4&b=1`;return this.config.signalCompact&&(i=`${i}&c=1`),t&&(i=`${i}&token=${t}`),i};let a,o=n(t,r);if(i&&i!==t){let e=n(i,s);a=new nt(this.logger,this.config,o,e)}else a=new st(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this.engine.emitEvent("serverConnected",!0),this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let i=e.action;const r=e.from_peer_id||e.from;if(r)switch(i){case"signal":this._handleSignalMsg(r,e,null,t);break;case"reject":this._handSignalRejected(r,e);break;default:this.logger.warn(`Signal websocket unknown action ${i}`)}else this.logger.warn("fromPeerId is missed")},a.onclose=()=>{this.connected=!1,this.engine.emitEvent("serverConnected",!1)},a.onerror=t=>{t.message&&this.logger.warn(`signal err: ${t.message}`),t.message&&this.engine.emitEvent(e.EXCEPTION,Ne(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const i=`signaling ${e} rejected`;this.logger.warn(`${i}, reason ${t.reason}`);const r=this.DCMap.get(e);r&&!r.connected&&(r.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,i),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,i,r="main"){return!(!(this.signalerWs.backupConnected&&e&&i.length>0&&"main"===r)||e.useBackupSignal)&&(e.useBackupSignal=!0,e.signalName="backup",e.intermediator=void 0,this.signalerWs.sendSignalBatch(t,i,"backup"),!0)}_handleSignalMsg(e,t,i,r){if(!this.scheduler)return;const{logger:s}=this;if(t.data){if(this.failedDCMap.has(e))return void this._sendSignalReject(e,`${e} ${this.failedDCMap.get(e)||"unknown"}`,i,r,!0);this._handleSignal(e,t.data,i,r)}else{const t=this.DCMap.get(e);if(!t)return;if(this._tryBackupSignal(t,e,t.signalMsgs,r))return void this.logger.warn(`${e} not found from main, try backup signal`);if(t.useBackupSignal)return;this._destroyAndDeletePeer(e),s.info(`signaling ${e} not found`);const{scheduler:n}=this;n.waitForPeer&&(n.waitingPeers--,0===n.waitingPeers&&n.notifyPeersLoaded(0)),this.requestMorePeers(),this._tryConnectToAllPeers(),i||this.notFoundDCSet.add(e)}}_handleSignal(e,t,i,r){let s=t;"string"==typeof s?s=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:Tt(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),i="O"===e[0];return{type:i?"offer":"answer",sdp:_t(t,i)}})(s):t=void 0;const n=s.type,{logger:a}=this;let o=this.DCMap.get(e);if(o){if(o.connected)return void a.info("datachannel had connected, signal ignored");if("offer"===n&&o.isInitiator){if(!(this.peerId>e))return void a.warn(`${e} signal type wrong ${n}, ignored`);a.warn(`${e} signal type wrong ${n}, convert to non initiator`),this._destroyAndDeletePeer(e,!1),o=this._createDatachannel(e,!1,i)}}else{if("answer"===n){const t=`${e} type wrong ${n}`;return a.warn(t),this._sendSignalReject(e,t,i,r),void this._destroyAndDeletePeer(e,!1)}if(a.debug(`receive node ${e} connection request`),this.DCMap.size>=this.maxConns){const t=`reach limit ${this.maxConns}`;return a.warn(t),void this._sendSignalReject(e,t,i,r,!0)}o=this._createDatachannel(e,!1,i)}o&&(r&&(o.signalName=r),o.receiveSignal(s,t))}_createDatachannel(e,t,i){if(!this.fetcher)return;let r;if(t&&this.peerPool.available)r=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${r.signalMsgs.length}`),r.intermediator=i,r.assignPeerId(this.peerId,e);else{let s=this.config.trickleICE;this.overloaded&&(s=!1),r=new ee(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:i,trickle:!i&&s})}return this.DCMap.set(e,r),this._setupDC(r),r}_sendSignalReject(e,t,i,r,s){if(i){const r=this.DCMap.get(i);if(r&&r.sendMsgSignalReject(e,this.peerId,t,s))return}this.signalerWs.sendReject(e,t,s,r)}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this,i=this.scheduler.peersNum;i>=this.maxConnsActive||(t.info(`requestMorePeers after delay ${e}, peersIncrement ${this.peersIncrement}`),i<3||i<this.minConns&&this.peersIncrement<=3&&!this.gotPeersFromTracker?this._requestPeersFromServer(i):this._requestPeersFromPeers(i)||this._requestPeersFromServer(i),this.peersIncrement=0)}_requestPeersFromServer(e){const{logger:t}=this;this.failedDCMap.size>50&&(this.failedDCMap=new Map([...this.failedDCMap].slice(-50))),this.notFoundDCSet.size>20&&(this.notFoundDCSet=new Set([...this.notFoundDCSet].slice(-20))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCMap.keys(),...this.notFoundDCSet.keys()],0===e).then((e=>{e&&e.peers&&(t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=this._filterPeers(e.peers),this._tryConnectToAllPeers())})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0}_requestPeersFromPeers(e){return!!this.requestPeersTimer||(e>=this.maxConnsActive||(this.requestPeersWaitCount=this.scheduler.requestPeers(),0!==this.requestPeersWaitCount&&(this.gotPeersFromTracker=!1,this.requestPeersTimer=setTimeout((()=>{this.logger.warn("requestPeersTimer timeout"),this._handleRequestedPeers()}),1e4),!0)))}_handleRequestedPeers(){if(clearTimeout(this.requestPeersTimer),this.requestPeersTimer=void 0,this.fetcher){if(this.requestPeersQueue.length>0){const e=function(e,t){const i=[],r=new Set;for(let t of e)r.has(t.id)||(r.add(t.id),i.push(t));const{asn:s,country:n}=t;if(!s||!n||i.length<2)return i;const a=i.filter((e=>!e.asn&&!e.country)),o=i.filter((e=>e.country===n&&e.asn!==s)),l=i.filter((e=>e.asn===s&&e.country===n)),h=i.filter((e=>!a.includes(e)&&!l.includes(e)&&!o.includes(e)));return l.concat(o).concat(a).concat(h)}(this.requestPeersQueue,this.fetcher.announceInfo);this.peers=this._filterPeers(e),this.requestPeersQueue=[]}this._tryConnectToAllPeers()}}_destroyAndDeletePeer(e,t=!0){const i=this.DCMap.get(e);return!!i&&(i.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=g();for(let t of this.DCMap.values()){const i=e-t.timeJoin;e-t.timeJoin>30&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${i} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}}const At=bt;class It extends se{constructor(e={},t=null){if(super(e),e.validateSegment||(e.validateSegment=function(e,t){return!0}),this.hlsjs=t,this.config=Object.assign({useDiskCache:!e.live},fe,e),t){this.HLSEvents=t.constructor.Events;const e=t.constructor.version;this.hlsjsVersion=e,this.config.isHlsV0=e&&"0"===e.split(".")[0]}this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t}=this.config,i=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(i=this.makeChannelId(e,t));return{channelIdMaker:i,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo}}}setupElectron(){this.browserInfo.device===Q.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e=super.getExtraForStats();return!this.config.live&&this.media&&(e.pos=Math.round(this.media.currentTime)),this.multiBitrate&&this.currentLevel!==this.lastLevel&&(e.level=this.currentLevel+"",this.lastLevel=this.currentLevel),e}getExtraForPeersRequest(){const e=super.getExtraForPeersRequest();return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){super.destroy()}async initSegmentManager(e){const{logger:i,config:r}=this;if(self.indexedDB&&r.useDiskCache&&!r.live){const e=new De(this,r);try{await e.setupStore(),this.bufMgr=e}catch(e){i.warn(e),this.bufMgr=new Me(this,r)}}else this.bufMgr=new Me(this,r);if(this.bufMgr.maxBufSize<=0)throw new Error("bufMgr state is invalid");"SegmentStore"===this.bufMgr.name&&(this.removeAllListeners(t.BM_FATAL_ERROR),this.once(t.BM_FATAL_ERROR,(()=>{i.warn("SegmentStoreFatalError, switch to SegmentCache"),this.bufMgr.destroy(),this.bufMgr=new Me(this,r),e&&e(this.bufMgr)})))}generateTag(){let e=(0,Q.getBrowser)();return e.includes("iPhone")&&"HlsSwP2pEngine"===this.engineName&&(e=`${e}_p`),this.playerName&&(e=`${e}_${this.playerName}`),e}async _init(e,t,i){const{logger:r,config:s}=this;if(!se.isSupported())throw new Error("webrtc is not supported");await this.initSegmentManager((e=>{if(this.tracker){const{scheduler:t}=this.tracker;t.bufferManager=e,t.bitset.clear()}})),i.live||this.media&&(i.pos=Math.round(this.media.currentTime)),i.tag=void 0===s.tag?this.generateTag():s.tag;let n=new Ze(this,s.token,encodeURIComponent(e),s.announce||"",i);this.fetcher=n,this.tracker=new At(this,n,t,s),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?ue:he)}_onHlsError(e,i){if(!i||!this.hlsjs)return;const{logger:r,tracker:s,config:n}=this;if(!r)return;const a=`${i.type} fatal ${i.fatal} details ${i.details} reason ${i.reason}`;if(i.fatal?r.error(a):r.warn(a),"networkError"===i.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:o}=this.browserInfo,l=`${o||""} hlsjs ${this.hlsjsVersion} ${location.href}`,h=this.hlsjs.constructor.ErrorDetails;switch(i.details){case h.BUFFER_STALLED_ERROR:if("HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),s&&s.scheduler){const e=s.scheduler;r.warn(`buffered: ${1e3*e.getBufferedDuration()} fragLoading ${e.fragLoading} isCritical ${e.isCritical()}`)}break;case h.INTERNAL_EXCEPTION:if(i.event&&"demuxerWorker"!==i.event){i.error||(i.error={});const e=`${i.error.message} event ${i.event} ${l}`;this.fetcher&&i.fatal&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=e),r.error(`INTERNAL_EXCEPTION event ${i.event} err ${i.error.message}`),this.emitEvent(t.EXCEPTION,Ne(i.error,"HLSJS_EXPT")),r.report(e,i.event,this.peerId,"2.16.4")}break;default:const e=i.details===h.FRAG_PARSING_ERROR;if(i.fatal||e){"mediaError"===i.type&&s&&s.scheduler&&s.scheduler.disconnectLoadingPeer(void 0,this.peerId).then((e=>{e&&s.scheduler.clearCache()}));const e=`${i.type} ${i.details} ${i.err||""} ${l}`;r.report(e,i.details,this.peerId,"2.16.4")}}}}class Rt{constructor(){this.method=null,this.key=null,this.iv=null,this._uri=null}get uri(){return!this._uri&&this.reluri&&(this._uri=o.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}class Pt{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[Pt.ElementaryStreamTypes.AUDIO]:!1,[Pt.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=o.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url}set url(e){this._url=e}get byteRange(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;let e=[];if(this.rawByteRange){const t=this.rawByteRange.split("@",2);if(1===t.length){const t=this.lastByteRangeEndOffset;e[0]=t||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get decryptdata(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}get endProgramDateTime(){if(!Number.isFinite(this.programDateTime))return null;let e=Number.isFinite(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}addElementaryStream(e){this._elementaryStreams[e]=!0}hasElementaryStream(e){return!0===this._elementaryStreams[e]}createInitializationVector(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let i=e;return e&&e.method&&e.uri&&!e.iv&&(i=new Rt,i.method=e.method,i.baseuri=e.baseuri,i.reluri=e.reluri,i.iv=this.createInitializationVector(t)),i}}class kt{constructor(e){this.endCC=0,this.endSN=0,this.fragments=[],this.initSegment=null,this.live=!0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=e,this.version=null}get hasProgramDateTime(){return!(!this.fragments[0]||!Number.isFinite(this.fragments[0].programDateTime))}}const Dt=/^(\d+)x(\d+)$/,wt=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class Ct{constructor(e){"string"==typeof e&&(e=Ct.parseAttrList(e));for(let t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}decimalInteger(e){const 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=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}enumeratedString(e){return this[e]}decimalResolution(e){const t=Dt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,i={};for(wt.lastIndex=0;null!==(t=wt.exec(e));){let e=t[2],r='"';0===e.indexOf(r)&&e.lastIndexOf(r)===e.length-1&&(e=e.slice(1,-1)),i[t[1]]=e}return i}}const Mt=Ct,Ot={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}};const xt=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Ft=/#EXT-X-MEDIA:(.*)/g,Nt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),Bt=/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/,Ut=/\.(mp4|m4s|m4v|m4a)$/i;class Gt{static findGroup(e,t){if(!e)return null;let i=null;for(let r=0;r<e.length;r++){const s=e[r];s.id===t&&(i=s)}return i}static convertAVC1ToAVCOTI(e){let t,i=e.split(".");return i.length>2?(t=i.shift()+".",t+=parseInt(i.shift()).toString(16),t+=("000"+parseInt(i.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let i,r=[];function s(e,t){["video","audio"].forEach((i=>{const r=e.filter((e=>function(e,t){const i=Ot[t];return!!i&&!0===i[e.slice(0,4)]}(e,i)));if(r.length){const s=r.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${i}Codec`]=s.length>0?s[0]:r[0],e=e.filter((e=>-1===r.indexOf(e)))}})),t.unknownCodecs=e}for(xt.lastIndex=0;null!=(i=xt.exec(e));){const e={},n=e.attrs=new Mt(i[1]);e.url=Gt.resolve(i[2],t);const a=n.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=n.decimalInteger("AVERAGE-BANDWIDTH")||n.decimalInteger("BANDWIDTH"),e.name=n.NAME,s([].concat((n.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=Gt.convertAVC1ToAVCOTI(e.videoCodec)),r.push(e)}return r}static parseMasterPlaylistMedia(e,t,i,r=[]){let s,n=[],a=0;for(Ft.lastIndex=0;null!==(s=Ft.exec(e));){const e={},o=new Mt(s[1]);if(o.TYPE===i){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=i,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=Gt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),r.length){const t=Gt.findGroup(r,e.groupId);e.audioCodec=t?t.codec:r[0].codec}e.id=a++,n.push(e)}}return n}static parseLevelPlaylist(e,t){let i,r,s=0,n=0,a=new kt(t),o=new Rt,l=0,h=null,u=new Pt,d=null;for(Nt.lastIndex=0;null!==(i=Nt.exec(e));){const e=i[1];if(e){u.duration=parseFloat(e);const t=(" "+i[2]).slice(1);u.title=t||null,u.tagList.push(t?["INF",e,t]:["INF",e])}else if(i[3]){if(Number.isFinite(u.duration)){const e=s++;u.start=n,u.levelkey=o,u.sn=e,u.cc=l,u.baseurl=t,u.relurl=(" "+i[3]).slice(1),Ht(u,h),a.fragments.push(u),h=u,n+=u.duration,u=new Pt}}else if(i[4]){if(u.rawByteRange=(" "+i[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(u.lastByteRangeEndOffset=e)}}else if(i[5])u.rawProgramDateTime=(" "+i[5]).slice(1),u.tagList.push(["PROGRAM-DATE-TIME",u.rawProgramDateTime]),null===d&&(d=a.fragments.length);else{for(i=i[0].match(Bt),r=1;r<i.length&&void 0===i[r];r++);const e=(" "+i[r+1]).slice(1),n=(" "+i[r+2]).slice(1);switch(i[r]){case"#":u.tagList.push(n?[e,n]:[e]);break;case"PLAYLIST-TYPE":a.type=e.toUpperCase();break;case"MEDIA-SEQUENCE":s=a.startSN=parseInt(e);break;case"TARGETDURATION":a.targetduration=parseFloat(e);break;case"VERSION":a.version=parseInt(e);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"DIS":l++,u.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":l=parseInt(e);break;case"KEY":var c=new Mt(e),f=c.enumeratedString("METHOD"),g=c.URI,p=c.hexadecimalInteger("IV");f&&(o=new Rt,g&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(f)>=0&&(o.method=f,o.baseuri=t,o.reluri=g,o.key=null,o.iv=p));break;case"START":let r=new Mt(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(r)&&(a.startTimeOffset=r);break;case"MAP":let h=new Mt(e);u.relurl=h.URI,u.rawByteRange=h.BYTERANGE,u.baseurl=t,u.sn="initSegment",a.initSegment=u,u=new Pt,u.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${i}`)}}}return u=h,u&&!u.relurl&&(a.fragments.pop(),n-=u.duration),a.totalduration=n,a.averagetargetduration=n/a.fragments.length,a.endSN=s-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>Ut.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),u=new Pt,u.relurl=a.fragments[0].relurl,u.baseurl=t,u.level=id,u.sn="initSegment",a.initSegment=u,a.needSidxRanges=!0),d&&function(e,t){let i=e[t];for(let r=t-1;r>=0;r--){const t=e[r];t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(a.fragments,d),a}}function Ht(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Number.isFinite(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}const Kt={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},Vt=(e,t,i,r,s=!1)=>{const[n,a,o]=$t(e,t,i,r);return s&&n.length>=1?P(n[0]):n.length>=2?[n[0],n[1]]:k(n,a,o)},$t=(e,t,i,r)=>{const s=[],{COMPLETE:n,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=Kt;return[n,a,o].forEach((n=>{s.push(Wt(e,n,t,i,r))})),s},Wt=(e,t,i,r,s)=>e.filter((e=>e.bitset.hasWithId(i,r,s,t)));class qt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const i=Number(e);if(i<0)continue;const r=new Map;if(t[e])for(let i of t[e])r.set(i,{state:Kt.COMPLETE,segId:void 0,size:void 0});this.levelMap.set(i,r)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,i,r=Kt.ANY){if(t<0)return!1;const s=this._createOrGetSet(t).get(e);return!!s&&((!i||!s.segId||s.segId===i)&&(r===Kt.ANY||s.state===r))}has(e,t,i=Kt.ANY){return this.hasWithId(e,t,void 0,i)}hasCompleteOr(e,t,i=Kt.COMPLETE){const r=this._createOrGetSet(t).get(e);return!!r&&(r.state===Kt.COMPLETE||r.state===i)}getObj(e,t){let i=this._createOrGetSet(t).get(e);return i||(i={}),i}getSegId(e,t){return this.getObj(e,t).segId}getSize(e,t){return this.getObj(e,t).size}getState(e,t){return this.getObj(e,t).state}delete(e,t){return this._createOrGetSet(t).delete(e)}add(e,t,i,r,s){if("number"!=typeof(n=e)||n%1!=0)return;var n;this._createOrGetSet(t).set(e,{state:r,segId:i,size:s}),this.isLive&&this._trimBitset(e)}array(e){const t=this._createOrGetSet(e);return this._keysForStateComplete(t)}allArray(){let e={};return this.levelMap.forEach(((t,i)=>{e[i]=this._keysForStateComplete(t)})),e}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetSet(e).size}_createOrGetSet(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}_trimBitset(e){const t=e-20;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[i,r]of e)r.state===Kt.COMPLETE&&t.push(i);return t}}class jt{constructor(){this.levelMap=new Map}totalLevels(){return this.levelMap.size}has(e,t){return this._createOrGetMap(t).has(e)}delete(e,t){return this._createOrGetMap(t).delete(e)}decre(e,t){const i=this._createOrGetMap(t);if(i.has(e)){let t=i.get(e);1===t?i.delete(e):i.set(e,t-1)}}incre(e,t){const i=this._createOrGetMap(t);if(i.has(e)){let t=i.get(e);i.set(e,t+1)}else i.set(e,1)}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetMap(e).size}_createOrGetMap(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}}const Yt=class{constructor(){this.peerMap=new Map}isEmpty(){return 0===this.peerMap.size}size(){return this.peerMap.size}clear(){this.peerMap.clear()}getPeers(){return[...this.peerMap.values()]}getPeerValues(){return this.peerMap.values()}hasPeer(e){return this.peerMap.has(e)}addPeer(e,t){this.peerMap.set(e,t)}getPeerIds(){return[...this.peerMap.keys()]}removePeer(e){this.peerMap.delete(e)}getPeersOrderByWeight(){const e=this.getAvailablePeers();return e.sort(((e,t)=>0===t.weight?1:0===e.weight?-1:t.weight-e.weight)),e}getPeer(e){return this.peerMap.get(e)}getAvailablePeers(){return this.getPeers().filter((e=>e.isAvailableUrgently))}},zt=Symbol("shareOnly");class Xt extends(n()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Yt,this.fragLoading=!1,this._setupEngine&&this._setupEngine(),this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[zt]=!1,this.downloadOnly=!1,this.loadedPeerNum=0,this.minConns=5}get isMobileNet(){return this.engine.isMobileNet}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const e=this.getStatsForPeer();let t=this.peersNum;const i=g();this.getPeers().forEach((r=>{t>this.minConns+1&&(i-r.dataExchangeTs>120||i-r.gotStatsTs>=83)?(this.logger.warn(`close dead peer ${r.remotePeerId} level ${r.currentLevel}`),r.close(!1),t--):r.connected&&r.sendMsgStats(t,e)}))}),4e4)}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}requestPeers(){const e=g();let t=0;for(let i of this.getPeers())i.mobileNet||i.super||(e-i.gotPeersTS<60?this.logger.warn(`${i.remotePeerId} just got peers, ignored`):(i.sendPeersRequest(),i.gotPeersTS=e,t++));return t}chokePeerRequest(t){const i={event:e.DC_CHOKE};t?t.sendJson(i):this._broadcastToPeers(i)}unchokePeerRequest(t){const i={event:e.DC_UNCHOKE};t?t.sendJson(i):this._broadcastToPeers(i)}stopRequestFromPeers(){for(let e of this.getPeers())e.choked=!0}resumeRequestFromPeers(){for(let e of this.getPeers())e.choked=!1}setShareOnly(){this[zt]=!0}deletePeer(e){e.downloading&&this._handlePieceAborted(e.remotePeerId),this.peerManager.hasPeer(e.remotePeerId)&&this.peerManager.removePeer(e.remotePeerId),this._peersStats(this.peerManager.getPeerIds())}getPeers(){return[...this.peerManager.getPeerValues()]}addPeer(e){const{logger:t}=this;this.peerManager.addPeer(e.remotePeerId,e),this[zt]&&(e.choked=!0);const i=this.peerManager.getPeerIds();this._peersStats(i);const{asn:r,country:s}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${s||""} asn ${r||""}, now has ${i.length} peers`)}hasPeer(e){return this.peerManager.hasPeer(e)}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const{logger:e}=this,t=this.getIdlePeer().length;if(e.info(`peers: ${this.peersNum} idle peers: ${t}`),t<this.peersNum){const t=this.peerManager.getPeers(),i=t.filter((e=>e.downloading));e.warn(`downloading: ${i.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of i)e.warn(`${t.remotePeerId} loading ${t.segId} remains ${t.remainAttachments} total ${t.pieceMsg.attachments}`)}return t>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(t){this.bufMgr=t,t.on(e.BM_LOST,(({sn:e,segId:t,next:i,level:r})=>{this._broadcastLost(e,t,r),this.onBufferManagerLost(e,t,i,r)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,i,r,s){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:i||void 0,level:r},s)}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),clearTimeout(this.checkTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(t){const{logger:i}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),i.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{i.warn(`peer ${t.remotePeerId} download aborted, reason ${e.reason}`),this._handlePieceAborted(t.remotePeerId),this.config.live&&this.checkPeers&&this.checkPeers()})).on(e.DC_DISCONNECT,(()=>{this.peersNum>=this.minConns&&(this.logger.warn(`close disconnected peer ${t.remotePeerId}`),t.close(!1))}))}_broadcastToPeers(e,t){for(let i of this.getPeers())t&&i===t||i.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;I(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(i=this.loadedPeerNum)?3:.5*i+1.67);var i;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const i=this.requestingMap.get(e);if(i)return void i.removeStreamListener(t);const r=this.segmentBuilderMap.get(e);r&&r.removeStreamListener(t)}setTargetPeersFromGroup(e,t,i,r){if(e.hasReversePeer){if((i=t.concat(i)).length>0)return this.targetPeers.forwardPeer=i[0],!0}else if(e.hasForwardPeer&&(r=t.concat(r)).length>0)return this.targetPeers.reversePeer=r[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=k(t,i,r),this.targetPeers.some((e=>!!e)))}}const Qt=Xt;class Jt extends(n()){constructor(){super(),this.internalMap=new Map}has(e){return this.internalMap.has(e)}set(e,t){this.internalMap.set(e,t),S(this.internalMap,13,(e=>{e&&e.destroy()}))}get(e){return this.internalMap.get(e)}delete(e){const t=this.internalMap.get(e);t&&(t.destroy(),this.internalMap.delete(e))}get size(){return this.internalMap.size}clear(){this.internalMap.clear(),this.removeAllListeners()}get activePeers(){let e=0;return[...this.internalMap.values()].forEach((t=>{t.hasForwardPeer&&!t.forwardCanceled&&(e+=1),t.hasReversePeer&&!t.reverseCanceled&&(e+=1)})),e}}const Zt=0,ei=1,ti=2,ii=3;class ri extends(n()){constructor(){super(),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.timeout=0,this.withCredentials=!1,this.status=0,this.readyState=this.UNSENT,this.headers=new Map,this.responseHeaders=null,this.on("load",(e=>{this.onload&&this.onload(e)})),this.on("abort",(e=>{this.onabort&&this.onabort(e)})),this.on("error",(e=>{this.onerror&&this.onerror(e)})),this.on("loadstart",(e=>{this.onloadstart&&this.onloadstart(e)})),this.on("progress",(e=>{this.onprogress&&this.onprogress(e)})),this.on("timeout",(e=>{this.ontimeout&&this.ontimeout(e)})),this.on("loadend",(e=>{this.onloadend&&this.onloadend(e)})),this.on("readystatechange",(()=>{this.onreadystatechange&&this.onreadystatechange()}))}setRequestHeader(e,t){this.headers.set(e,t)}addEventListener(e,t){this.addListener(e,t)}removeEventListener(e,t){this.removeListener(e,t)}overrideMimeType(){}getAllResponseHeaders(){if(!this.responseHeaders)return null;let e="";return this.responseHeaders.forEach(((t,i)=>{e+=`${i}: ${t}\n`})),e}getResponseHeader(e){return this.responseHeaders?this.responseHeaders.get(e):null}open(){this.readyState=this.OPENED,this.emit("loadstart")}abort(){this.readyState=this.DONE,this.status=0,this.emit("loadend")}send(){}_emitEvent(e){this.emit(e,{type:e,target:this})}}const si=/(\d+)-(\d+)\/(\d+)/;function ni(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class ai{constructor(e){this.fetchSetup=e.fetchSetup||oi,this.xhrSetup=e.xhrSetup,this.controller=new self.AbortController,this.stats=D(),this.packetSize=u,this.fakeXhr=new ri}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.xhrSetup=this.fakeXhr=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.callbacks&&this.callbacks.onUpdate&&this.callbacks.onUpdate(void 0,!1,!0),this.controller.abort())}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;r.trequest=r.loading.start;let s=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal);const n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l=2e4}=t.loadPolicy||{},h=i.onUpdate,u=i.onBodyStart;this.context=e,this.config=t,this.callbacks=i,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),s=function(e,t){e.withCredentials&&(t.credentials="include");for(let[i,r]of e.headers)t.headers.set(i,r);return t}(this.fakeXhr,s)),this.request=this.fetchSetup(e,s),clearTimeout(this.requestTimeout),t.timeout=o&&Number.isFinite(o)?o:l,this.requestTimeout=setTimeout((()=>{this.abortInternal(),this.fakeXhr._emitEvent("timeout"),this.fakeXhr._emitEvent("loadend"),i.onTimeout&&i.onTimeout(r,e,this.response)}),this.fakeXhr.timeout||t.timeout);const d="then"in(c=this.request)&&c.then instanceof Function?this.request.then(self.fetch):self.fetch(this.request);var c;const{fakeXhr:f}=this;f.readyState=f.OPENED,f.emit("readystatechange"),f._emitEvent("loadstart"),d.then((s=>{this.response=this.loader=s;const a=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout&&i.onTimeout(r,e,this.response)}),l-(a-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new li(t||"fetch, bad network response",e,s)}r.tfirst=r.loading.first=a,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=si.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Number.isFinite(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||r.total;let o=0;try{const e=s.headers.get("Content-Range").split("/");2===e.length&&(o=parseInt(e[1],10))}catch(e){}const{fakeXhr:d}=this;return d.readyState=d.HEADERS_RECEIVED,d.responseHeaders=s.headers,d.emit("readystatechange"),h&&"0"!==r.total?(u&&u(r.total,o),this.loadProgressively(s,r,e,h)):(d.emit("progress",new ProgressEvent("progress",{lengthComputable:!1})),n?s.arrayBuffer():"json"===e.responseType?s.json():s.text())})).then((t=>{const{response:s}=this;clearTimeout(this.requestTimeout),r.tload=r.loading.end=Math.max(performance.now(),r.loading.first);const n=t[a];n&&(r.loaded=r.total=n);const o={url:s.url,data:t,code:s.status};i.onProgress&&i.onProgress(r,e,t,s),i.onSuccess&&i.onSuccess(o,r,e,s)})).catch((t=>{if(clearTimeout(this.requestTimeout),r.aborted)return;const s=t&&t.code||0,n=t?t.message:null;i.onError&&i.onError({code:s,text:n},e,t?t.details:null,r)}))}loadProgressively(e,t,i,r){const s=e.body.getReader();let n=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>s.read().then((({value:i,done:s})=>{const{fakeXhr:c}=this;if(c.readyState!==c.LOADING&&(c.readyState=c.LOADING,c.emit("readystatechange")),i&&(n+=i.length),s){if(l.byteLength>0)if(n<=this.packetSize){const e=(0,a.h)(n);l.copy(e,0,o*this.packetSize,l.byteLength),r(e,!0)}else{const e=function(e,t){const i=e.byteLength-t,r=[];let s=t,n=Math.floor(i/u),o=i%u;for(let t=0;t<n;t++){const t=(0,a.h)(u);e.copy(t,0,s,s+u),r.push(t),s+=u}if(o>0){const t=(0,a.h)(o);e.copy(t,0,s,s+o),r.push(t)}return r}(l,o*this.packetSize);for(let t=0;t<e.length;t++)r(e[t],t===e.length-1)}const t=l.buffer,{fakeXhr:i}=this,{status:s,statusText:h,url:d}=e;return i.readyState=i.DONE,i.responseText=s,i.status=h,i.responseURL=d,i.responseType="arraybuffer",i.response=t,i.emit("readystatechange"),i._emitEvent("load"),i._emitEvent("loadend"),Promise.resolve(t)}if(t.loaded+=i.length,c.emit("progress",new ProgressEvent("progress",{lengthComputable:!0,loaded:t.loaded,total:t.total})),this.callbacks.onLoaded&&this.callbacks.onLoaded({total:t.total,loaded:t.loaded,first:!h},this.context),h=!0,l=a.h.concat([l,i]),n>=this.packetSize){n-=this.packetSize;const e=(0,a.h)(this.packetSize);l.copy(e,0,o*this.packetSize,(o+1)*this.packetSize),o++,r(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function oi(e,t){return new self.Request(e.url,t)}class li extends Error{constructor(e,t,i){super(e),this.code=t,this.details=i}}class hi extends(n()){constructor(e,t,i=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=i,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=2e3,this.proxied=!1,this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.forwardBufList=[],this.reverseBufList=[],this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.rangeRequesting=!1,this.waitingRemain=!1,this.httpLoaded=0,this.p2pLoaded=0,this.deadline=0,this.forwardCanceled=!1,this.reverseCanceled=!1,this.firstReceived=!1,this.alreadyOutput=!1,this.pieceMsg={}}get isDownloading(){return this.timeReceivePiece>0}get isAlmostDeadline(){return this.rangeRequesting||this.alreadyOutput}hasPeer(e){return!!e&&(e===this.forwardPeer||e===this.reversePeer)}get streamListeners(){return[...this.reverseStreamListeners,...this.forwardStreamListeners].length}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg,i=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let r of i){const{handler:i}=r;i(e,t,!0,"aborted by synthesizer")}this._resetStreamListeners()}_resetStreamListeners(){this.reverseStreamListeners.length=0,this.forwardStreamListeners.length=0}_notifyStreamListenersRemain(){if(this.forwardStreamListeners.length>0){for(let e=this.forwardOffset+1;e<this.bufArr.length;e++)this._notifyStreamListeners(!1,this.bufArr[e],e);this.forwardStreamListeners=[]}if(this.reverseStreamListeners.length>0){for(let e=this.reverseOffset-1;e>=0;e--)this._notifyStreamListeners(!0,this.bufArr[e],e);this.reverseStreamListeners=[]}}addStreamListener(e,t,i){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:i,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:i}=this.pieceMsg,r=r=>r.filter((r=>r.peerId!==e||(r.handler(t,i,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=r(this.forwardStreamListeners),this.reverseStreamListeners=r(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let i=performance.now();e<=0?setTimeout((()=>{this._handleTimeout(!1,!1)}),0):(this.firstPieceTimer=setTimeout((()=>{if(this.firstReceived)return;const e=()=>{this.logger.warn(`switch to http, firstReceived ${this.firstReceived}`),this._handleTimeout(!1)};if(this.timeReceivePiece>0){const t=(this.timeReceivePiece-i)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=i+e,this._startTimer(e,t))}setExtra(e={}){e.url&&(this.url=e.url),e.rangeStart&&(this.rangeStart=e.rangeStart),e.rangeEnd&&(this.rangeEnd=e.rangeEnd),e.httpLoadTime&&(this.httpLoadTime=e.httpLoadTime),e.proxied&&(this.proxied=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup),e.headers&&(this.headers=e.headers),e.segId&&!this.pieceMsg.seg_id&&(this.pieceMsg.seg_id=e.segId)}get hasForwardPeer(){return!!this.forwardPeer}get hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}get isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}get isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1,t),!0))}setReversePeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0,t),!0))}setPeer(e,t,i){return t?this.setReversePeer(e,i):this.setForwardPeer(e,i)}deletePeer(e){const t=e===this.reversePeer;this._detachPeer(e),t?this.reversePeer=null:this.forwardPeer=null,(this.isEmpty||this.deadline>0)&&this._handleTimeout(!1,!1)}terminate(){this._handleTimeout(!1,!1)}get hasPartialBuffer(){return this.hasForwardBuffer||this.hasReverseBuffer}get hasForwardBuffer(){return this.forwardOffset>=0}get hasReverseBuffer(){return this.pieceMsg&&this.reverseOffset<this.pieceMsg.attachments}get isForwardBufferFull(){return this.pieceMsg&&this.forwardOffset>=this.pieceMsg.attachments-1}get isReverseBufferFull(){return this.reverseOffset<=0}_cancelP2p(e=!1){const{seg_id:t,sn:i,level:r}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(i,r,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(i,r,t),this.reverseCanceled=!0)}detachPeers(){this._detachPeer(this.forwardPeer),this._detachPeer(this.reversePeer)}destroy(){this._notifyStreamListenersAbort(),this.removeAllListeners(),this.destroyed=!0,this._detachPeer(this.forwardPeer),this.forwardPeer=null,this.forwardOffset=-1,this._detachPeer(this.reversePeer),this.reversePeer=null,this.reverseOffset=1e4,this.bufArr=[],this.forwardStreamListeners=[],this.reverseStreamListeners=[],this._abortLoading()}_abortLoading(){clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._cancelP2p(),this.httpLoader&&(this.logger.warn("abort syn httpLoader"),this.httpLoader.abort(),this.httpLoader=void 0)}_detachPeer(t){if(!t)return;const i=t===this.reversePeer?this.reverseEvents:this.forwardEvents;i&&i&&t.off(e.DC_PIECE_DATA,i.onPieceData).off(e.DC_PIECE,i.onPiece).off(e.DC_PIECE_NOT_FOUND,i.onPieceNotFound).off(e.DC_PIECE_ABORT,i.onPieceAbort)}_receivePacket(t,i,r,s=!0){const{seg_id:n,sn:o,level:l,size:h,ext:u}=this.pieceMsg,d=i-1;if(this.bufArr[d]?(this.logger.warn(`syn bufArr ${n} already has ${d} size ${r.byteLength}`),this.bufArr[d]=r):(s?this.p2pLoaded+=r.byteLength:this.httpLoaded+=r.byteLength,this.emit(e.SYN_PROGRESS,{total:h,loaded:this.p2pLoaded+this.httpLoaded,first:!this.firstReceived,segId:n,sn:o}),this.firstReceived=!0,this.bufArr[d]=r,t?this.reverseOffset=d:this.forwardOffset=d,this._notifyStreamListeners(t,r,d)),this.forwardOffset!==this.reverseOffset-1)return!0;this.rangeRequesting||(this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0)),clearTimeout(this.timer),this._notifyStreamListenersRemain();const c=performance.now()-this.timeStart,f=h/c;let g=a.h.concat(this.bufArr);const p=g.byteLength;if(p===h){if(this.alreadyOutput)return!1;this.alreadyOutput=!0,this._abortLoading();let t=g.buffer;const i=new X(o,n,t,this.getFromPeerId(),l,u);this.emit(e.SYN_OUTPUT,i,{speed:f,time:c,p2p:this.p2pLoaded,http:this.httpLoaded})}else{this.logger.error(`${n} expectedSize ${h} != byteLength ${p} forward ${this.forwardOffset} reverse ${this.reverseOffset}`);for(let e=0;e<this.bufArr.length;e++)this.logger.error(`piece ${e} size ${this.bufArr[e].byteLength}`);this.emit(e.SYN_ERROR,this.pieceMsg,Zt),this._disconnectPeers()}}_disconnectPeers(){[this.forwardPeer,this.reversePeer].forEach((t=>{t&&t.emit(e.DC_ERROR,!0)}))}_checkPieceSize(e){const{size:t,seg_id:i,sn:r}=this.pieceMsg;return!e||!t||e===t||(this.logger.warn(`checkPieceSize ${i||r} size not match ${t} ${e}`),!1)}_setupPeer(t,i,r){const{logger:s}=this;0===this.timeStart&&(this.timeStart=performance.now()),r&&!this.pieceMsg.size&&(this.pieceMsg.size=r);const n=(i,r,n,a,o,l)=>{if(this.destroyed)return;if(!this._validateMsg(i,l.level,r))return void s.error(`onPieceData ${r||i} size ${n.byteLength} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(a<this.pieceMsg.attachments&&n.byteLength!==u)return s.error(`${r} dataSn ${a} size is ${n.byteLength}`),this.emit(e.SYN_ERROR,this.pieceMsg,Zt),void this._disconnectPeers();const{reverse:h}=l;this._receivePacket(h,a,n)&&!this.waitingRemain&&!this.rangeRequesting&&this.deadline>0&&this._shouldSwitch()&&(s.warn("should switch to http"),clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._handleTimeout(!1,!1))},a=e=>{if(this.destroyed)return;const{attachments:i,size:r,sn:n,level:a,seg_id:o,ext:l={}}=e;let h=!0;(r<=999||!this._validateMsg(n,a,o))&&(s.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),h=!1),this._checkPieceSize(r)||(h=!1);const{ext:u}=this.pieceMsg;if(u&&l.hash&&u.hash&&l.hash!==u.hash&&(this.logger.warn(`syn ${o||n} hash not match ${l.hash} ${u.hash}`),h=!1),!h)return t.cancelDownload(n,a,o),void this.deletePeer(t);0===this.bufArr.length?(this.pieceMsg={...this.pieceMsg,seg_id:o,size:r,attachments:i,ext:l},this.reverseOffset=i,this.bufArr=new Array(i),this.timeReceivePiece=performance.now()):!this.pieceMsg.ext.hash&&l.hash&&(this.pieceMsg.ext.hash=l.hash)},o=e=>{this.destroyed||this.deletePeer(t)},l=()=>{this.destroyed||this.deletePeer(t)},h={onPieceData:n,onPiece:a,onPieceNotFound:o,onPieceAbort:l};i?this.reverseEvents=h:this.forwardEvents=h,t.on(e.DC_PIECE_DATA,n).once(e.DC_PIECE,a).once(e.DC_PIECE_NOT_FOUND,o).once(e.DC_PIECE_ABORT,l)}_shouldSwitch(){const e=u,t=this.pieceMsg.size-e*this.loadedPackets;return this.coordinator.shouldSwitchToHttp(t,this.deadline,this.p2pSpeed,e,this.httpLoadTime)}_startTimer(e,t=!0){this.timer=setTimeout(this._handleTimeout.bind(this,t),e)}get loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(t=!1,i=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:r,size:s,attachments:n}=this.pieceMsg;if(!s||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${r} url ${this.url}`),void this.emit(e.SYN_ERROR,this.pieceMsg,Zt);if(t&&this.timeReceivePiece>0&&n){this.logger.warn(`syn ${this.loadedPackets} of ${n} packets loaded`);const e=this.httpLoadTime>3e3?3e3:this.httpLoadTime;if(this.shouldWaitForRemain(e))return this.waitingRemain=!0,this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}if(i){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const i=e.currentLoadSpeed(),r=t.currentLoadSpeed();return i===r?e.timeSendRequest-t.timeSendRequest:i-r})).shift();e&&e.loadtimeout()}if((this.rangeSupported||!this.hasPartialBuffer)&&this.url)return this._cancelP2p(!0),this._loadRemainBufferByHttp();this._notifyStreamListenersAbort(),this.emit(e.SYN_ERROR,this.pieceMsg,ii)}shouldWaitForRemain(e){return!this.isEmpty&&this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed,i=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${i}`),t>=i}minRequiredSpeed(e){let t=0;return[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(t+=e.loadedBytes())})),(this.pieceMsg.size-t)/e}get p2pSpeed(){let e=0;return[this.forwardPeer,this.reversePeer].forEach((t=>{t&&(e+=t.currentLoadSpeed())})),e}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull&&e!==t?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}getStreamInfo(e){const t=e?this.reverseBufList:this.forwardBufList;let i,r;return t.length<this.pieceMsg.attachments?(i=this.isFull?"WaitPartialDouble":"WaitPartialSingle",r=1):(i=this.isFull?"SynFullDouble":"SynFullSingle",r=0),{from:i,incompletes:r,bufferList:t}}_loadRemainBufferByHttp(){if(this.rangeRequesting||this.alreadyOutput)return;const{size:t,seg_id:i}=this.pieceMsg,{logger:r}=this,s=this.rangeEnd>0?this.rangeEnd-1:0;let n=this.forwardOffset;const a=performance.now();this.rangeRequesting=!0;let o=le(n,this.reverseOffset,t,this.rangeStart,s);const l=o.rangeEnd-o.rangeStart;r.info(`listeners ${this.streamListeners} continue download ${i} from ${this.url} range: ${o.rangeStart}-${o.rangeEnd}`),this.hasPartialBuffer||(o={});const u=new ai({xhrSetup:this.xhrSetup});this.httpLoader=u;let d={url:this.proxied?f(this.url,h,!0):this.url,...o};let c,g=n+1;const p={onUpdate:(t,i,s)=>{if(!this.destroyed){if(s)return r.warn("httpLoader aborted"),void(this.alreadyOutput||this.emit(e.SYN_ERROR,this.pieceMsg,ei));if(i){const e=c/(performance.now()-a);this.coordinator.addHttpSpeed(e),this.httpLoader=void 0}this.bufArr[g]||this._receivePacket(!1,g+1,t,!1),g++}},onBodyStart:(t,s)=>{if(0===s&&r.warn(`range request fileSize ${s}`),this.destroyed)return;const{size:n}=this.pieceMsg;if(c=t,t!==n||0!==s&&s!==n){let i=!1;s>0&&s!==n?(r.error(`onBodyStart fileSize ${s} != ${n}`),i=!0):t!==l&&(r.error(`onBodyStart size ${t} != expectedSize ${l}`),i=!0),i&&"{}"!==JSON.stringify(o)&&this.emit(e.SYN_ERROR,this.pieceMsg,ei)}else r.warn(`syn range request ${i} resp whole ts`),g=0},onError:t=>{this.destroyed||(r.error(`httpLoader error ${t.text}`),this.emit(e.SYN_ERROR,this.pieceMsg,ei))},onTimeout:()=>{this.destroyed||(r.warn("httpLoader timeout"),this.emit(e.SYN_ERROR,this.pieceMsg,ti))}};u.load(d,{timeout:15e3},p)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class ui extends hi{constructor(e,i,r,s,n,a=!1,o){super(e,i,a,o),this.pieceMsg={event:t.DC_PIECE,sn:r,level:s,seg_id:n},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,i){const{sn:r,seg_id:s,attachments:n}=this.pieceMsg,a=e&&0===i||!e&&i===n-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;e?this.reverseBufList.push(t):this.forwardBufList.push(t),a&&(this.forwardBufList.push([...this.reverseBufList].reverse()),this.reverseBufList.push([...this.forwardBufList].reverse()));for(let e of o){const{handler:i}=e;i(r,s,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,i){return(!this.pieceMsg.seg_id||i===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}}class di{constructor(){this.meanHttpSpeed=0,this.loaderHttpSpeed=0}addHttpSpeed(e){this.meanHttpSpeed=this._cal(this.meanHttpSpeed,e)}addLoaderHttpSpeed(e,t){t&&e&&(this.loaderHttpSpeed=this._cal(this.loaderHttpSpeed,t/e))}getMeanTimeToLoaded(e){return this.loaderHttpSpeed?e/this.loaderHttpSpeed:500}shouldSwitchToHttp(e,t,i,r,s){if(this.meanHttpSpeed<=0)return!1;if(i>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*s>=e)return!1;return((s+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-i)*i<r}_cal(e,t){return.4*e+.6*t}}class ci extends Qt{constructor(e,t){super(e,t),this.prefetchOnly=t.prefetchOnly,this.bitset=new qt(t.live||!1),this.bitCounts=new jt,this.requestingMap=new Jt,this.segmentBuilderMap=new Jt,this.allowP2pLimit=t.httpLoadTime+1.5,this.playlistInfo=new Map,this.gotPlaylist=!1,this.targetPeers={},this.sequential=!0,this.coordinator=new di,this.loadingSegId="",this.loadingSN=0,this.currPlaySN=0,this.currLostSN=-1,this.nextLostSN=-1,this.config.live?this.maxPrefetchCount=10:(this.maxPrefetchCount=150,this.startCheckPeersTimer())}handshakePeer(e){this._setupDC(e);const{asn:t,country:i}=this.engine.fetcher.announceInfo;e.sendMetaData(this.bitset.allArray(),!0,this.peersNum,{asn:t,country:i},this.isMobileNet)}_receiveDCHave(e,t,i,r){this.bitset.has(e,t)||this.bitCounts.incre(e,t)}_setupDC(e){super._setupDC(e),e.on(t.DC_HAVE,(t=>{if(e.bitset&&t.sn>=0){const{sn:i,level:r,complete:s,seg_id:n,size:a}=t,o=s?Kt.COMPLETE:Kt.PARTIAL_FORWARD;e.bitset.add(i,r,n,o,a),this._receiveDCHave(i,r,n,e),e.isAvailableUrgently&&this._handleDCHave(e,i,r,n,a,o)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:i,level:r,seg_id:s,size:n}=t;e.bitset.hasCompleteOr(i,r,Kt.PARTIAL_REVERSE)||e.bitset.add(i,r,s,Kt.PARTIAL_REVERSE,n),this._receiveDCHave(i,r,s,e),e.isAvailableUrgently&&this._handleDCHave(e,i,r,s,n,Kt.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:i,level:r}=t;e.bitset.has(i,r)&&(e.bitset.delete(i,r),this.bitCounts.decre(i,r))})).on(t.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=7||this.requestingMap.has(de(e.sn,e.level))&&this.notifyAllPeers(e.sn,e.level,e.seg_id,e.size,e.reverse?Kt.PARTIAL_REVERSE:Kt.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:i,level:r}=t,s=de(i,r);this.removeStreamListener(s,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:i,level:r}=t;e.bitset.delete(i,r),this.bitCounts.decre(i,r),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:i}=this,{sn:r,level:s,reverse:n}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(r));const o=()=>{this.bitset.delete(r,s),e.sendPieceNotFound(r,a,{level:s}),this._broadcastLost(r,a,s,e)},l=await this.bufMgr.getSegById(a),h=de(r,s),u=this.requestingMap.get(h);let d=!1;u&&u.isDownloading&&(d=!0);const c=this.segmentBuilderMap.get(h);if(l)if(i.info(`found seg ${a} from bufMgr`),l.level===s){let t="SegmentStore"===this.bufMgr.name?"Disk":"Cache";l.ext.from&&l.ext.from.length<2500&&(t=`${l.ext.from}-${t}`),e.sendBuffer(l.sn,l.segId,l.data,{from:t,level:l.level,reverse:n,hash:l.ext.hash})}else o();else if(!n&&c)i.info(`peer request ${r} wait from builder, sent ${c.bufferList.length}`),R(e,c,c.pieceMsg,c.bufferList,c.source,1);else if(d){i.info(`syn had ${u.loadedPackets} packets, wait remain from upstream ${u.getFromPeerId()}`);const t={...u.pieceMsg,reverse:n},{from:r,incompletes:s,bufferList:a}=u.getStreamInfo(n);R(e,u,t,a,r,s)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new qt(this.config.live,t.field);for(let e in t.field){const i=Number(e);if(i<0)continue;t.field[i].forEach((e=>{this.bitset.has(e,i)||this.bitCounts.incre(e,i)}))}this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e)}}peersHas(e,t){return this.bitCounts.has(e,t)}deletePeer(e){if(this.peerManager.hasPeer(e.remotePeerId)&&e.bitset){const t=e.bitset.allArray();for(let e in t){const i=Number(e),r=t[i];r&&r.forEach((e=>{this.bitCounts.decre(e,i)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,i,r){const{logger:s,config:n}=this;let a=1e3*(r-n.httpLoadTime);this.allowP2pLimit=n.httpLoadTime+1.5,s.info(`bufferedDuration ${1e3*r} remainLoadTime ${a} allowP2pLimit ${1e3*this.allowP2pLimit}`);const o=de(e,t),l=this.requestingMap.get(o);if(l){const n=l.segId;if(n&&n!==i)return s.warn(`syn segId ${n} not match ${i}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,i,r);if(!l.shouldWaitForRemain(a)){if(s.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const r=this.peerManager.getPeersOrderByWeight();let[n,o,h]=$t(r,e,t,i);return!!this.setTargetPeersFromGroup(l,n,o,h)||(l.hasReversePeer||l.hasPartialBuffer||a>1e3*(this.allowP2pLimit+1))&&this.httpRangeSupported}return s.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t,i,r)}_searchAvailablePeers(e,t,i,r){if(r<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const s=this.peerManager.getPeersOrderByWeight(),[n,a]=Vt(s,e,t,i);return this.targetPeers={forwardPeer:n,reversePeer:a},[n,a].some((e=>!!e))}reportTraffic(e,t,i){const{fetcher:r}=this.engine;r&&(e>0&&r.reportFlow(e),t>0&&r.reportDCTraffic(t,i))}notifyAllPeers(e,t,i,r,s=Kt.COMPLETE){if(!i)return void this.logger.error("segId is required");if(this.downloadOnly)return;const{live:n}=this.config;if(this.bitset.has(e,t,s))return;const a=((e,t,i)=>`${e}-${t}-${i}`)(e,t,s);let o;s!==Kt.PARTIAL_REVERSE&&(o=s===Kt.COMPLETE);const l=this.requestingMap.get(de(e,t));for(let h of this.getPeers())l&&l.hasPeer(h)||h.notifySet.has(a)||h.bitset.hasCompleteOr(e,t,s)||h.uploading||(h.sendMsgHave(e,i,{level:t,reverse:s===Kt.PARTIAL_REVERSE,complete:o,size:r}),h.notifySet.add(a),n&&T(h.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:i}=this;if(!this.hasPeers)return;const r=t.live;if(this.fragLoading)return void e.info("loading urgently, skip prefetch");const{currentLevel:s}=i;if(0===this.bitCounts.size(s))return;if(!r&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;let n=this.peerManager.getPeersOrderByWeight();if(0===n.length)return;let a=0,{prefetchNum:o,endSN:l,startSN:h}=t;if(!r){const t=this.requestingMap.size,i=this.requestingMap.activePeers;if(i>=o)return void e.warn(`requestingMap size ${t} activePeers ${i}`);o-=i}if(this.getBufferedDuration()<this.allowP2pLimit){if(!r)return;o=1}let u=0,d=this.loadingSN+1;if(this.prefetchOnly&&(d+=2),!r)if(this.loadingSN>=l&&!this.bufMgr.overflowed)d=h;else{const e=Math.min(...n.filter((e=>e.endSN>=d)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;d<e&&(d=e)}for(;a<o&&u<this.maxPrefetchCount&&(r||!(d>l))&&!(r&&d>this.loadingSN+2);){if(this.bitset.has(d,s)){d++;continue}const t=de(d,s),i=this.requestingMap.get(t);if(this.bitCounts.has(d,s)){if(i){for(let e of n)if(e.bitset.has(d,s)){const{state:t,segId:r,size:n}=e.bitset.getObj(d,s);if(this._trySetPeerForSyn(i,e,r,d,s,n,t))break}}else{let i=[null,null];if(r)i=Vt(n,d,s,void 0,!0);else for(let e of n)if(e.bitset.has(d,s)){const t=e.bitset.getState(d,s);let r;r=t===Kt.COMPLETE?0===p(0,1):t===Kt.PARTIAL_REVERSE,i[r?1:0]=e;break}if(i.some((e=>!!e))){const r=new ui(this.coordinator,this.logger,d,s,void 0,this.httpRangeSupported);this._setupSynthesizer(r),this.requestingMap.set(t,r),i.forEach(((t,i)=>{if(t&&a<o){const n=1===i,o=t.bitset.getSize(d,s);r.setPeer(t,n,o)&&(a++,t.requestDataBySN(d,!1,{level:s,reverse:n}),e.info(`request prefetch ${d} level ${s} from peer ${t.remotePeerId} downloadNum ${t.downloadNum} reverse ${n}`))}}))}}n=this.peerManager.getPeersOrderByWeight()}if(u++,d++,0===n.length)break}this.loadedPeerNum=a}onBufferManagerLost(e,t,i,r){this.currLostSN=e,i&&(this.nextLostSN=i),this.bitset.delete(e,r),this.bitCounts.delete(e,r)}onBufferManagerSegAdded(e){const{sn:t,segId:i,level:r,size:s}=e;this.notifyAllPeers(t,r,i,s),this.updateLoaded(t,r,i)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[i,r]of this.requestingMap.internalMap){const s=i.split("-"),n=Number(s[1]),a=Number(s[0]);r.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),r.deletePeer(t),this.bitCounts.decre(n,a),t.bitset.delete(n,a))}}updateLoaded(e,t,i){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,i,Kt.COMPLETE),this.bitCounts.delete(e,t),this.requestingMap.delete(de(e,t)),this.config.live&&this.checkPeers())}broadcastPlaylist(e,t){if(!this.config.live)return;const i=function(e){const t=e.split("\n");let i=0,r=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){i=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&r++;return i+r-1}(t);if(!this.isMobileNet)for(let r of this.getPeers())r.sendMsgPlaylist(e,t,i);this.playlistInfo.set(e,{seq:i,data:t})}async getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t,data:i}=this.playlistInfo.get(e),r=()=>{for(let i of this.getPeers()){const r=i.getLatestPlaylist(e,t);if(r)return this.playlistInfo.set(e,r),this.gotPlaylist=!0,r}return null};let s=r();return!s&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await v(240),this.gotPlaylist=!1,s=r()),s}getBufferedDuration(){const{config:e}=this;let{media:t,currentSrc:i}=this.engine;if(!t||t.src!==i&&0===t.currentTime){if(this.logger.info("try get video element"),t=ae(this.config.mediaElem,i),!t)return 4;this.engine.media=t}let r=function(e){let t=0,i=e.currentTime,r=e.buffered;for(let e=r.length-1;e>=0;e--)if(i>=r.start(e)&&i<=r.end(e)){t=r.end(e)-i;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return r}destroy(){super.destroy(),this.requestingMap.clear(),this.segmentBuilderMap.clear(),this.engine.removeAllListeners(t.MEDIA_REBUFFER)}clearCache(){"SegmentStore"===this.bufMgr.name?this.engine.emit(t.BM_FATAL_ERROR):this.bufMgr.clear(),this.bitset.clear()}async _handleSynOutput(e,t,i,r,s,n){if(this.logger.info(`syn output ${e} http ${t} p2p ${i} time ${r}`),!this.config.validateSegment(e,new Uint8Array(s)))return!1;if(n){const t=await w(s);if(t&&t!==n)return this.logger.warn(`${e} computedHash ${t} != hash ${n}`),!1}return!0}_handleSynError(e,t,i,r){const{logger:s,config:n}=this;s.warn(`SYN_ERROR ${t}-${i} code ${r}`),r!==Zt&&e.hasPartialBuffer&&i>this.loadingSN?s.warn(`syn abort ${i} with partial buffer`):this.requestingMap.delete(de(i,t)),n.live&&this.checkPeers()}_notifySynthesizer(e,t,i,r,s,n,a=!0){const o=this.requestingMap.get(de(i,r));o&&this._trySetPeerForSyn(o,e,t,i,r,s,n,a)}_trySetPeerForSyn(e,t,i,r,s,n,a,o=!1){const{logger:l}=this,h=e.segId;if(i&&h&&i!==h)return l.warn(`notifySynthesizer segId ${i} not match ${h}`),!1;if(e.isFull)return!0;if(e.isAlmostDeadline)return!0;if(e.isEmpty){if(e.hasForwardBuffer&&c()){if(e.setReversePeer(t,n))return u(!0,o),!0}else if(e.hasReverseBuffer&&d()&&e.setForwardPeer(t,n))return u(!1,o),!0}else if(!e.hasForwardPeer&&d()){if(e.setForwardPeer(t,n))return u(!1,o),!0}else if(!e.hasReversePeer&&c()&&e.setReversePeer(t,n))return u(!0,o),!0;function u(e,n){n?t.requestDataById(i,r,!0,{level:s,reverse:e}):t.requestDataBySN(r,!1,{level:s,reverse:e})}function d(){return a===Kt.PARTIAL_FORWARD||a===Kt.COMPLETE}function c(){return a===Kt.PARTIAL_REVERSE||a===Kt.COMPLETE}return!1}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:i}=this.config;t||i||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,i={level:e};if(t&&!this.config.live){const{currentTime:e}=t;i.pos=Math.round(e)}return i}checkSynthesizer(e,t){const i=de(e,t),r=this.requestingMap.get(i);r&&(0===r.streamListeners?(this.logger.info(`destroy syn ${i} without listeners`),this.requestingMap.delete(i)):this.logger.info(`keep syn ${i} with listeners`))}setupSynForLoad(e,t,i,r,s){const{forwardPeer:n,reversePeer:a}=this.targetPeers,o=de(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(r):(l=new ui(this.coordinator,this.logger,e,t,i,this.httpRangeSupported,r),this._setupSynthesizer(l),this.requestingMap.set(o,l)),l.prefetchTimeout&&s<1e3*this.allowP2pLimit&&!n&&!a)return l.setTimeout(0);s>700&&(n&&l.setForwardPeer(n)&&n.requestDataById(i,e,!0,{level:t}),a&&l.setReversePeer(a)&&a.requestDataById(i,e,!0,{level:t,reverse:!0})),l.setTimeout(l.isEmpty?0:s,!0)}async disconnectLoadingPeer(e,t){let i=e;if(!i){const e=await this.bufMgr.getSegById(this.loadingSegId);e&&e.fromPeerId&&(i=e.fromPeerId)}let r=!1;return i&&(this.logger.warn(`disconnect loading peer ${i}`),i.split(":").forEach((e=>{if(t&&e===t)return;r=!0;const i=this.peerManager.getPeer(e);i&&i.close(!0)}))),r}}class fi{constructor(t,i,r,s){this.bufferList=[],this.streamListeners=[],this.finished=!1,this.packetSize=u,this.attachments=s%this.packetSize==0?s/this.packetSize:Math.floor(s/this.packetSize)+1,this.pieceMsg={event:e.DC_PIECE,attachments:this.attachments,seg_id:r,sn:t,level:i,size:s,reverse:!1},this.sink=(0,a.h)(0),this.source="HttpStream"}receiveBytes(e,t){e.byteLength&&(this.sink=a.h.concat([this.sink,e]),this.bufferList.push(e),t&&(this.finished=!0),this._notifyStreamListeners(e))}getCompleteBuffer(){return this.sink.buffer}destroy(){this.finished||this._notifyStreamListenersAbort()}addStreamListener(e,t,i){this.streamListeners.push({handler:i,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:i}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((r=>r.peerId!==e||(r.handler(t,i,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let i of this.streamListeners){const{handler:r}=i;r(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:i}=this.pieceMsg;for(let r of this.streamListeners){const{handler:s}=r;s(t,i,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const gi=/^age:\s*[\d.]+\s*$/im;function pi(e,t,i,r){if(!e)return!1;const s=r&&r.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}const vi=class{constructor(e){this.xhrSetup=e&&e.xhrSetup||null,this.stats=D(),this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.loader=null}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);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=s&&Number.isFinite(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.tfirst=i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,n="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){const s=n||t.response;if(null!=s){i.tload=i.loading.end=Math.max(self.performance.now(),i.loading.first);const n="arraybuffer"===t.responseType?s.byteLength:s.length;if(i.loaded=i.total=n,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(i,e,s,t),!this.callbacks)return;const o={url:t.responseURL,data:s,code:r};return void this.callbacks.onSuccess(o,i,e,t)}}const a=s.loadPolicy.errorRetry;pi(a,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(a):this.callbacks.onError({code:r,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(pi(e,this.stats.retry,!0))this.retry(e);else{const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=function(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}(e,i.retry),i.retry++,this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&gi.test(this.loader.getAllResponseHeaders())){const 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}};const mi=class extends ci{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=I(t.segmentBypass)?t.segmentBypass:()=>!1,!0===t.httpStreamEnabled?this.streamEnabled=ni():this.streamEnabled=!1}async handleGetMediaData(e,i){const{logger:r,engine:s,config:n}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return r.warn(`cannot get frag ${a}`),i.postMessage({action:t.SW_GET_MEDIA});s.currentLevelIndex=l.level;const{sn:h,level:u}=l,d=this.config.segmentId(String(u),h,a,o);if(s.segmentLoadCount++,this.segmentBypass(a,l.tagList))return r.info(`bypass frag ${a}`),i.postMessage({action:t.SW_GET_MEDIA});if(s.segmentLoadCount<n.startFromSegmentOffset)return this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout,!1);const c=d===this.loadingSegId;if(c&&(r.warn(`duplicate request ${d}`),this.prefetchOnly))return i.postMessage({action:t.SW_GET_MEDIA});this.loadingSN=h,s.bufMgr&&(s.bufMgr.loadingSN=h),this.loadingSegId=d;const f=await this.bufMgr.getSegById(d);if(f)return l.loaded=f.size,l.fromPeerId=f.fromPeerId,r.info(`bufMgr found seg sn ${h} segId ${d} size ${l.loaded}`),s.emit(t.FRAG_LOADED,{url:a,sn:h,level:u,segId:d,loaded:l.loaded,duration:l.duration,byP2p:!0,fromPeerId:f.fromPeerId}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:f.data}});if(this.fragLoading=!0,this.prefetchOnly)return r.info(`prefetchOnly, skip p2p load ${d}`),this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout);let g=this.getBufferedDuration();g>this.fragloadTimeout&&(g=this.fragloadTimeout),r.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const v=de(h,u);if(this.resolveMap.has(h)||c){let e=this.requestingMap.get(v);if(e||c){e&&this.httpRangeSupported&&(r.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let s=setTimeout((()=>{r.info(`notify seg ${h} timeout`),s=-1,i.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{s<0||e&&e.level===u&&(clearTimeout(s),r.info(`notify seg ${e.sn}`),i.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else r.warn(`${h} is requesting, fallback`),i.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,u,d,g)){await this._loadFragByP2p(l,i,h,d,a,u,o,p)||(r.warn(`p2p timeout switch to http load ${d}`),this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,i,r,s,n,a,o=!0){const{sn:l,level:u}=e,d=de(l,u),c=f(s,h,!0),g={},p=this.streamEnabled&&o?new ai(g):new vi(g);let v={url:c,responseType:"arraybuffer",...L(n)};const m={timeout:a,loadPolicy:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4}},E={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,i.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,i.postMessage({action:t.SW_GET_MEDIA})},onSuccess:async(n,a)=>{this.fragLoading=!1;const{data:o}=n;let h=a.loading.end-a.loading.start;if(this.logger.info(`HTTP loaded ${r} time ${h} speed ${o.byteLength/h}`),!await this.bufMgr.hasSegOfId(r)){const e=y(o).buffer,t=new X(l,r,e,"",u);await this.bufMgr.putSeg(t),this.reportTraffic(o.byteLength,0,0)}this.segmentBuilderMap.delete(d),e.segId=r,e.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:s,sn:l,level:u,segId:r,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:o}})}};if(this.streamEnabled&&o){let e;E.onBodyStart=t=>{!e&&t>0&&(this.notifyAllPeers(l,u,r,t,Kt.PARTIAL_FORWARD),e=new fi(l,u,r,t),this.segmentBuilderMap.has(d)||this.segmentBuilderMap.set(d,e))},E.onUpdate=(t,i,s)=>{if(s)return this.logger.warn(`loadFragByHttp ${r} aborted`),void this.segmentBuilderMap.delete(d);e&&e.receiveBytes(t,i)}}p.load(v,m,E)}async _loadFragByP2p(e,i,r,s,n,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${r} segId ${s} level ${a}`);const u=await this.load(r,s,a,n,o,l);if(u&&u.data){const{data:o,fromPeerId:l,size:d}=u;if(h.info(`p2p loaded segId ${s} level ${a} size ${o.byteLength}`),!await this.bufMgr.hasSegOfId(s)){const e=new X(r,s,o,l,a,u.ext);h.info(`bufMgr putSeg ${r} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:n,sn:r,level:a,segId:s,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:o,size:d}}),!0}h.warn(`P2P timeout load segId ${s}`);const d=await this.bufMgr.getSegById(s);return!!d&&(this.fragLoading=!1,h.info(`already loaded seg sn ${r} segId ${s}`),i.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:d.data}}),!0)}notifySWMessage(e,i,r){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(i,r);else this.logger.warn(`unknown action ${e}`)}_getFrag(e,t){return t&&(e=`${e}|${t}`),this.fragMap.get(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(){if(!this.engine)return;const{media:e,targetDuration:t}=this.engine;!this.config.live&&e&&t&&(this.currPlaySN=Math.ceil(e.currentTime/t))}load(e,t,i,r,s,n){const{logger:a,config:o}=this;let l={...L(s),proxied:!0,url:r,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,i,t,l,n);const h=new Promise((r=>{const s={resolve:r,sn:e,level:i,segId:t};this.resolveMap.set(e,s)}));return this.targetPeers={},h}isCritical(){return this.resolveMap.has(this.loadingSN)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,i)=>{const{config:r,logger:s}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:u,time:d,http:c,p2p:f}=i,g=this.resolveMap.has(a);g&&(this.fragLoading=!1);const p=await this._handleSynOutput(n,c,f,d,o,h.hash),v=e.getFromPeerId();if(p)if(this.bitset.has(a,l)||this.reportTraffic(c,f,u),g){s.info(`receive criticalSeg seg_id ${n}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:f>0?v:void 0,ext:h})}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t));else{if(s.error(`segment ${n} validate failed`),g){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(de(a,l)),this.disconnectLoadingPeer(v)}})).on(t.SYN_ERROR,((t,i)=>{const{sn:r,level:s}=t;if(this.resolveMap.has(r)){const e=this.resolveMap.get(r);this.resolveMap.delete(r),e.resolve()}this._handleSynError(e,s,r,i)}))}_handleDCHave(e,t,i,r,s,n){this._notifySynthesizer(e,r,t,i,s,n,this.resolveMap.has(t)),this.config.live&&W((()=>{this.checkPeers()}))}},yi="2.13.0";class Ei extends It{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},i=null){super(e,i),this.swSupported=self.isSecureContext,this.levels=[],this.bypassLevels=[],this.currentLevelIndex=0,this.currentSrc="",this.swVersion="",this.media=ae(this.config.mediaElem),this.workerKeepAliveInterval=null,this.fragMap=new Map,this.engineName=Ei.name,Ei.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),i&&(i.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),i.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:r,signalId:s,browserInfo:n}=this.setup();if(this.onLevelLoaded=e=>{const{config:i}=this,a=e.live;i.live=a,this.segmentLoadCount=0,this.targetDuration=e.averagetargetduration,this.browserInfo={...n,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${r(this.currentSrc)}|${s}[${ee.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsSwP2pEngine"),o.info(`engine version: ${se.version} hls-proxy version: ${this.swVersion}`),o.info(`channel ${this.channel}`),a||(i.startSN=e.startSN,i.endSN=e.endSN,o.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(t.LEVEL_LOADED,this.onLevelLoaded)},0===this.config.httpLoadTime&&(this.config.live?this.on(t.LEVEL_LOADED,(e=>{const{fragments:t,averagetargetduration:i,startSN:r}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,i,r)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,i)=>{this.multiBitrate=e.length>1,this.currentSrc=i,this.off(t.MANIFEST_PARSED,this.onManifestParsed)},this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{this.curTsUri=e;const{config:t}=this;!this.rangeTested&&t.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,t.logger&&t.logger.info(JSON.stringify({engine:this.engineName,...this.browserInfo}))),this.segmentLoadCount>=t.startFromSegmentOffset&&this.resumeTracker()},this.on(t.FRAG_LOADED,this.onFragLoaded),this.swSupported){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:i,data:r}=e.data;if(!i)return;if(i===t.SW_DEBUG){const{level:e,text:t}=r;return void(this.logger&&this.logger[e](`hls-proxy ${this.swVersion}: ${t}`))}const s=e.ports[0];if(s){if(this.logger&&this.logger.info(`engine onmessage action ${i}`),s.postMessage({action:i,pong:!0}),!this.p2pEnabled||!r)return s.postMessage({action:i});if(i===t.SW_GET_PLAYLIST)this.handleGetPlaylist(r,s);else{if(!this.scheduler)return s.postMessage({action:i});this.scheduler.notifySWMessage(i,r,s)}}else this.logger&&this.logger.error(`sender not found in action ${i}`)}}this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}watchRebuffering(e){this.offEventRebuffer=function(e,t){let i=null;const r=()=>{i||(i=setTimeout((()=>{t()}),2500))},s=()=>{null!=i&&(clearTimeout(i),i=null)};return e.addEventListener("waiting",r),e.addEventListener("playing",s),()=>{e.removeEventListener("waiting",r),e.removeEventListener("playing",s)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,i,r=!1){const{config:s,logger:n}=this,{url:a,redirectedUrl:o,text:l,ver:u}=e;return this.swVersion=u,-1===function(e,t){for(var i=e.split("."),r=t.split("."),s=0;s<Math.max(i.length,r.length);s++){var n=parseInt(i[s]||0),a=parseInt(r[s]||0);if(n<a)return-1;if(n>a)return 1}return 0}(u,yi)?(console.warn(`hls-proxy.js version should >= ${yi}`),i.postMessage({action:t.SW_GET_PLAYLIST})):this.bypassLevels.indexOf(b(a))>=0?(console.warn("bypass audio track"),n&&n.warn("bypass audio track"),i.postMessage({action:t.SW_GET_PLAYLIST})):(i.postMessage({action:t.SW_GET_PLAYLIST,data:{active:!0,debug:n&&n.isDebugLevel,text:l,redirectedUrl:o}}),this._parsePlaylist(l,b(a),o,r),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!s.live&&t()){const i=new URL(e.scope);this.pathname=i.pathname+h;const r=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;n&&(n.error(t),n.report(t,"SWKeepAlive",this.peerId,"2.16.4"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,i)=>{fetch(`${e}/keepalive/`).then((e=>{if(e.ok)return e.text();throw new Error("keepalive failed")})).then((e=>{if(""!==e.trim())throw new Error("not valid keepalive response");t()})).catch((e=>{i(e)}))}))).catch((e=>{r(e)})):r("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,i,r,s=!1){const n=i;r&&(i=r);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let r=0;const o=Gt.parseLevelPlaylist(e,i);this.levels.length>0?(r=this.levels.indexOf(b(o.url)),-1===r?(this.restartP2p(),this.currentSrc=n,r=0):this.currentLevelIndex=r):(""!==this.currentSrc&&n!==this.currentSrc&&this.restartP2p(),this.currentSrc=n,this.levels=[b(i)]),this.emit(t.LEVEL_LOADED,o),a.live&&S(this.fragMap,200),o.fragments.forEach((e=>{e.level=r;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const i=e.byteRange;2===i.length&&(t=`${t}|bytes=${i[0]}-${i[1]-1}`),this.fragMap.set(t,e)})),!s&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(b(i),e)}else{const r=Gt.parseMasterPlaylist(e,i);""!==this.currentSrc&&this.restartP2p(),r.length>0&&(r.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=r.map((e=>b(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{Gt.parseMasterPlaylistMedia(e,i,t).forEach((e=>{e.url&&this.bypassLevels.push(b(e.url))}))}))),this.emit(t.MANIFEST_PARSED,r,n)}this._setupSegmentId()}async handleGetPlaylist(e,i){const{config:r,logger:s,scheduler:n}=this,{url:a}=e,o=b(a);if(n&&n.playlistInfo.has(o)){const t=await n.getPlaylistFromPeer(o);if(t&&t.data){const{data:r,seq:n}=t;return s&&s.info(`got playlist from peer seq ${n}`),void this.handlePlaylist({text:r,...e},i,!0)}}try{const{text:r,redirectedUrl:n}=await this._loadPlaylistByHttp(a);if(!function(e){return 0===e.indexOf("#EXTM3U")}(r))return s&&s.warn(`not m3u8: ${r}`),i.postMessage({action:t.SW_GET_PLAYLIST});this.handlePlaylist({text:r,redirectedUrl:n,...e},i)}catch(e){i.postMessage({action:t.SW_GET_PLAYLIST})}}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let e="sw is not supported";return E||(e="https is required when using ServiceWorker",console.warn(e)),Promise.reject(e)}return this.media=ae(t.mediaElem),this.media||e&&e.warn("no video element found"),Ri.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,i)=>{const{serviceWorker:r}=navigator;r||i(e),r.getRegistration().then((r=>{r?r.unregister().then(t).catch(i):i(e)}))}))}async _init(e,t){const{logger:i,config:r}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.mediaTimer=setInterval((()=>{const e=()=>this.hlsjs&&this.hlsjs.media;if(this.media){const t=e();t&&this.media!==t&&(this.media=t),clearInterval(this.mediaTimer),this.rubufferTimer=setTimeout((()=>{this.watchRebuffering(this.media)}),15e3)}else this.media=e()||ae(r.mediaElem)}),3e3);let s=new mi(this,r);s.fragMap=this.fragMap;try{await super._init(e,s,t)}catch(e){return void(i&&i.error(e))}s.server=this.fetcher,this.scheduler=s}restartP2p(){this.logger&&this.logger.warn("restart P2P"),this.disableP2P(),this.enableP2P(),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.on(t.FRAG_LOADED,this.onFragLoaded)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this)}disableP2P(){this.logger&&this.logger.warn("disable P2P"),clearInterval(this.mediaTimer),clearTimeout(this.rubufferTimer),this.offEventRebuffer&&this.offEventRebuffer(),this.p2pEnabled&&(this.config.p2pEnabled=this.p2pEnabled=!1,this.tracker&&this.tracker instanceof At&&(this.tracker.stopP2P(),this.tracker=null,this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.trackerTried=!1)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(t.MANIFEST_PARSED),this.removeAllListeners(t.LEVEL_LOADED),this.removeAllListeners(t.FRAG_LOADED),clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null}destroy(){this.swSupported&&(navigator.serviceWorker.onmessage=void 0),super.destroy()}async _loadPlaylistByHttp(e){const t=f(e,h,!0),i=await fetch(t);return{text:await i.text(),redirectedUrl:i.redirected?i.url:void 0}}}const Si=Ei;function Ti(e,t,i="main"){return"main"!==i}function _i(e,t,i){let r,s,n;const a=performance.now();n=a,s=i?n-i.getMeanTimeToLoaded(t):a-200,r=s-100,e.trequest=r,e.tfirst=s,e.tload=n,e.loading={first:r,start:s,end:n},e.loaded=t,e.total=t}const Li=class extends ci{constructor(e,t){super(e,t),this.isHlsjs=!0,this.waitingPeers=0,this.waitingSeg={},this.requestedSet=new Set}updatePlaySN(e){this.currPlaySN=e}load(e,t,i){const{logger:r,config:s}=this;this.context=e;const{rangeStart:n,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:u,level:d}=l;this.callbacks=i,this.criticalSeg={sn:u,level:d,segId:h};let c=e.defaultTimeout-1e3*s.httpLoadTime;const f={rangeStart:Number(n),rangeEnd:Number(a),url:o,httpLoadTime:1e3*s.httpLoadTime,xhrSetup:s.xhrSetup,segId:h,headers:Object.keys(e.headers||{}).length>0?e.headers:void 0};this.setupSynForLoad(u,d,h,f,c),this.targetPeers={}}isCritical(){return!(!this.criticalSeg||this.criticalSeg.segId!==this.loadingSegId)}addPeer(e){super.addPeer(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler")}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,i)=>{const{config:r,logger:s}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:u,time:d,http:c,p2p:f}=i,g=this.criticalSeg&&this.criticalSeg.segId===n,p=await this._handleSynOutput(n,c,f,d,o,h.hash),v=e.getFromPeerId();if(p)if(this.bitset.has(a,l)||this.reportTraffic(c,f,u),g&&this.callbacks){s.info(`receive criticalSeg seg_id ${n}`),this.criticalSeg=null;const{frag:e}=this.context;f>0&&(e.fromPeerId=v,e.loadByP2P=!0),this.callbacks.onSuccess({data:o,url:this.context.url},{},{...this.context,ext:h}),this.callbacks=void 0}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t));else s.error(`segment ${n} validate failed`),g&&this.callbacks.onTimeout({},this.context,null),this.requestingMap.delete(de(a,l)),this.disconnectLoadingPeer(v)})).on(t.SYN_ERROR,((t,i)=>{const{sn:r,level:s}=t;this.criticalSeg&&this.criticalSeg.sn===r&&(this.criticalSeg=null,this.callbacks.onTimeout({},this.context,null)),this._handleSynError(e,s,r,i)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:i,segId:r})=>{this.criticalSeg&&this.criticalSeg.segId===r&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:i},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:i,level:r})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,i&&this.checkSynthesizer(e,r)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:i,level:r})=>{this.fragLoading=!1,i||this.checkSynthesizer(e,r)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,i,r,s,n){this._notifySynthesizer(e,r,t,i,s,n,this.criticalSeg&&this.criticalSeg.segId===r),this.config.live&&W((()=>{this.checkPeers()}))}};class bi extends It{static get name(){return"HlsjsP2pEngine"}constructor(e,t={}){if(super(t,e),!e)throw new TypeError("hlsjs instance is null");"serviceWorker"in navigator&&this._setupSW(),this.config.xhrSetup=e.config.xhrSetup,this.engineName=bi.name,this._onFragLoading=this._onFragLoading.bind(this),this._onFragLoaded=this._onFragLoaded.bind(this),this._onFragChanged=this._onFragChanged.bind(this),this._onHlsError=this._onHlsError.bind(this),this._onLevelUpdated=this._onLevelUpdated.bind(this);const{channelIdMaker:i,signalId:r,browserInfo:s}=this.setup(),n=(t,a)=>{if(!a)return;const{config:o}=this,l=a.details,h=l.live;this._startEngine(this.hlsjs.url,h,s,i,r,l),e.off(this.HLSEvents.LEVEL_LOADED,n)};this._updateHlsEventsHandlers(),e.on(this.HLSEvents.LEVEL_LOADED,n);const a=(e,t)=>{if(!t)return;const{config:i}=this,{fragments:r,averagetargetduration:s,startSN:n}=t.details;i.httpLoadTime=this.determineHttpLoadTime(r,s,n)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,i)=>{this._setupSegmentId();const r=i.levels.length;this.multiBitrate=r>1,e.off(this.HLSEvents.MANIFEST_PARSED,o)};e.on(this.HLSEvents.MANIFEST_PARSED,o),e.on(this.HLSEvents.DESTROYING,(()=>{e.off(this.HLSEvents.LEVEL_LOADED,a),this.destroy()}))}_startEngine(e,t,i,r,s,n={}){const{config:a}=this;a.live=t,this.browserInfo={...i,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${r(e)}|${s}[${ee.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsjsP2pEngine"),this.logger=o,o.info(`channel ${this.channel}`),t||(a.startSN=n.startSN,a.endSN=n.endSN,o.info(`startSN ${n.startSN} endSN ${n.endSN}`)),this._init(this.channel,this.browserInfo)}async _init(e,t){const{logger:i,config:r}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const s=new Li(this,r);try{await super._init(e,s,t)}catch(e){return void i.error(e)}this.hlsjs.config.fLoader=function(e,t,i,r){const s=r.httpStreamEnabled&&ni();return class extends(n()){constructor(n){super(),this.logger=i,this.isHlsV0=r.isHlsV0,this.bufMgr=e.bufMgr,this.httpLoader=s||this.isHlsV0?new ai(n):new vi(n),this.originalLoader=n.loader,this.p2pEnabled=r.p2pEnabled,this.isLive=r.live,this.scheduler=e,this.fetcher=t,this.segmentId=r.segmentId,this.blockTypes=r.p2pBlackList,this.stats=this.httpLoader.stats||D(),this.segmentBypass=I(r.segmentBypass)?r.segmentBypass:()=>!1,this.prefetchOnly=r.prefetchOnly,this.startFromSegmentOffset=r.startFromSegmentOffset}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,i){const{logger:r,scheduler:s}=this,{url:n,frag:a}=e;this.isHlsV0||(a.stats=this.stats);const{level:o,sn:l,type:h,tagList:u}=a;let d=a.segId;if(!d){let t;e.rangeEnd&&(t="bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),d=a.segId=this.segmentId(String(o),l,n,t)}const c=()=>(a.loadByHTTP=!0,new this.originalLoader(t).load(e,t,i));if(!n||!Number.isInteger(l)||Ti(0,this.blockTypes,h)||this.segmentBypass(n,u))return r.info(`HTTP load blockType ${n}`),c();if(this.fetcher.increMediaRequests(),this.isLive&&s.requestedSet.has(d))return r.warn(`HTTP load duplicated ${n}`),c();if(s.engine.segmentLoadCount<this.startFromSegmentOffset)return c();t.maxRetry=2;const f=s.getBufferedDuration(),g=await this.bufMgr.getSegById(d);if(this.p2pEnabled&&g){r.info(`bufMgr found seg sn ${l} segId ${d} level ${o} size ${g.size}`);let t=y(g.data).buffer,n={url:e.url,data:t};return _i(this.stats,g.size,s.coordinator),a.loaded=g.size,a.loadByP2P=!0,a.fromPeerId=g.fromPeerId,void W((()=>{!this.isHlsV0&&i.onProgress&&i.onProgress(this.stats,e,n.data),i.onSuccess(n,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&s.hasAndSetTargetPeer(l,o,d,f)?this.loadFragByP2p(e,t,i,d,f):(r.info(`fragLoader load ${d} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,i,d))}loadFragByHttp(e,t,i,r){const{logger:n,scheduler:a}=this,{segmentBuilderMap:o}=a,l=e.frag,{sn:h,level:u}=l,d=de(h,u);if(s){let e;i.onUpdate=(t,i,s)=>{if(s)return n.warn(`loadFragByHttp ${r} aborted`),void o.delete(d);e&&e.receiveBytes(t,i)},i.onBodyStart=t=>{!e&&t>0&&(e=new fi(h,u,r,t),o.has(d)||o.set(d,e),a.notifyAllPeers(h,u,r,t,Kt.PARTIAL_FORWARD))}}const c=i.onSuccess;i.onSuccess=async(e,t,i)=>{a.coordinator.addLoaderHttpSpeed(t.tload-t.tfirst,t.loaded);const{data:s}=e;let f=t.tload-t.trequest;if(n.info(`HTTP loaded ${r} time ${f} speed ${t.total/f}`),l.loaded=t.total,!await this.bufMgr.hasSegOfId(r)){const e=y(s).buffer,t=new X(h,r,e,this.fetcher.peerId,u);await this.bufMgr.putSeg(t)}o.delete(d),this.fetcher.reportFlow(t.total),c(e,t,i)},e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,i)}loadFragByP2p(t,i,r,s,n){const{logger:a}=this,o=t.frag;let l;l=i.loadPolicy?i.loadPolicy.maxTimeToFirstByteMs:i.timeout,(!l||l>1e3*n)&&(l=1e3*n),t.defaultTimeout=l,this.scheduler.load(t,i,r);const h=r.onSuccess,u=r.onTimeout;r.onTimeout=(e,t)=>{a.warn(`P2P timeout switched to HTTP load ${o.relurl} at ${o.sn}`),r.onSuccess=h,this.loadFragByHttp(t,i,r,s),r.onTimeout=u},r.onSuccess=async(t,i,n)=>{const{data:l}=t;if(_i(i=this.stats,l.byteLength,e.coordinator),!await this.bufMgr.hasSegOfId(s)){const e=y(l).buffer,t=new X(o.sn,s,e,o.fromPeerId||this.fetcher.peerId,o.level,n.ext);await this.bufMgr.putSeg(t)}o.loadByP2P||this.fetcher.reportFlow(i.total),o.loaded=i.loaded,a.info(`${o.loadByP2P?"P2P":"HTTP"} loaded segment id ${s}`),!this.isHlsV0&&r.onProgress&&r.onProgress(i,n,l),h(t,i,n)}}}}(s,this.fetcher,i,r),r.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,i){return class extends(n()){constructor(r){super(),this.logger=t,this.xhrLoader=new r.loader(r),this.p2pEnabled=i.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||D()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,i){const{logger:r}=this,{url:s}=e,n=b(s),a=i.onSuccess;if(i.onSuccess=(e,t,i)=>{this.scheduler&&!i.loadedByPeer&&this.scheduler.broadcastPlaylist(n,e.data),a(e,t,i)},this.scheduler&&this.scheduler.playlistInfo.has(n)){const t=await this.scheduler.getPlaylistFromPeer(n);if(t&&t.data){const{data:n,seq:a}=t;r.info(`got playlist from peer seq ${a}`),_i(this.stats,n.length);let o={url:s,data:n};return e.loadedByPeer=!0,void W((()=>{i.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,i)}}}(s,i,r))}_onFragLoading(e,i){const r=i.frag;let{sn:s,level:n,segId:a}=r;if(!Ti(r.url,this.config.p2pBlackList,r.type)&&Number.isInteger(s)){if(this.logger&&this.logger.info("loading frag "+s),this.bufMgr&&(this.bufMgr.loadingSN=s),!a){let e;r._byteRange&&(e="bytes="+r._byteRange[0]+"-"+r._byteRange[1]);let t=r.url;this._setupSegmentId(),a=r.segId=this.config.segmentId(String(n),r.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:s,segId:a,byHttp:r.loadByHTTP,level:n})}}_onLevelUpdated(e,t){const{details:i}=t,{hlsjs:r,config:s}=this,{targetduration:n,live:a,fragments:o}=i,l=o.length;if(a&&r&&"main"===o[0].type&&!(l<=4)&&(s.isHlsV0||!r.userConfig.liveSyncDuration&&!r.userConfig.liveSyncDurationCount)){const e=l<=9?l-1:l-2;r.config.liveSyncDurationCount!==e&&(r.config.liveSyncDurationCount=e)}}_onFragLoaded(e,i){if(this.segmentLoadCount++,!this.p2pEnabled)return;const{frag:r}=i;this.curTsUri=r.url;const{sn:s,segId:n,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:u,url:d}=r,{config:c,logger:f}=this;this.tracker&&this.tracker.scheduler&&(T(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(n)),Ti(r.url,c.p2pBlackList,r.type)||(this.bufMgr&&this.bufMgr.loadingSN>=0&&this.emit(t.FRAG_LOADED,{url:d,sn:s,level:l,segId:n,loaded:a,duration:o,byP2p:!!u,fromPeerId:h}),!this.rangeTested&&c.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,f&&f.info(JSON.stringify({engine:this.engineName,hlsjs:this.hlsjsVersion,...this.browserInfo})))),this.segmentLoadCount>=c.startFromSegmentOffset&&this.resumeTracker()}_onFragChanged(e,i){const{frag:r}=i;if(!Ti(r.url,this.config.p2pBlackList,r.type)){this.logger&&this.logger.info("frag changed: "+r.sn);const{sn:e,duration:i}=r;this.emit(t.FRAG_CHANGED,{sn:e,duration:i})}}get currentLevel(){const{currentLevel:e}=this.hlsjs;return e>=0?e:0}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}_updateHlsEventsHandlers(e=!1){const t=this.hlsjs;if(!t)return;const i=e?"off":"on";t[i](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[i](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[i](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[i](this.HLSEvents.ERROR,this._onHlsError),t[i](this.HLSEvents.LEVEL_UPDATED,this._onLevelUpdated)}destroy(){this._updateHlsEventsHandlers(!0),super.destroy()}_setupSW(){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:t}=e.data,i=e.ports[0];if(i)return i.postMessage({action:t,pong:!0}),i.postMessage({action:t,data:{bypass:!0}})}}}const Ai=bi;class Ii{static get Events(){return t}static get TrackerZone(){return se.TrackerZone}static isSupported(){return se.isSupported()&&(ne()||Si.isServiceWorkerSupported())}static isServiceWorkerSupported(){return Si.isServiceWorkerSupported()}static isMSESupported(){return ne()}static getBrowser(){return J().getBrowser()}static get ServiceWorkerEngine(){return Si}static get HlsjsEngine(){return Ai}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return Ii.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:i}={}){const{serviceWorker:r}=navigator;return!r||i?Promise.resolve():r.getRegistration().then((i=>i||Promise.race([r.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,i)=>{const r=e.installing||e.waiting||e.active,s=()=>"activated"===r.state&&(r.removeEventListener("statechange",s),t(e),!0);s()||r.addEventListener("statechange",s)}))}(e))).catch((()=>{Promise.resolve()})),v(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const i=()=>{this._realEngine=new Ai(t,e)},r=()=>{this._realEngine=new Si(e,t)};"1"!==c("_sw")?e.proxyFirst&&t?Si.isServiceWorkerSupported()?r():i():!e.proxyOnly&&ne()&&t?i():r():r()}get realEngine(){return this._realEngine}get engineName(){return this._realEngine.constructor.name}once(e,t){return this._realEngine.once(e,t)}on(e,t){return this._realEngine.on(e,t)}off(e,t){return this._realEngine.off(e,t)}removeListener(e,t){return this._realEngine.removeListener(e,t)}removeAllListeners(e){return this._realEngine.removeAllListeners(e)}set p2pEnabled(e){this._realEngine.p2pEnabled=e}get p2pEnabled(){return this._realEngine.p2pEnabled}enableP2P(){this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}async registerServiceWorker(){return I(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return I(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return se.version}}Ii.version=se.version,Ii.protocolVersion=ee.VERSION,"object"==typeof self&&(self.P2PEngineHls=Ii);const Ri=Ii;var Pi=i(251),ki=i.n(Pi);const Di={maxBufferLength:12},wi={maxBufferLength:40};class Ci extends(ki()){static get P2PEvents(){return Ri.Events}static get P2pEngine(){return Ri}constructor(e={}){let t=e.p2pConfig||{};const i=!1===t.live?wi:Di;let r=JSON.parse(JSON.stringify(i));r.maxBufferSize=0,r.enableWorker=!1;for(let t in e)"p2pConfig"!==t&&(r[t]=e[t]);super(r),this._restartEvent=()=>{this.restartP2P()},Ri.isSupported()&&(this._p2pEngine=new Ri({...t,hlsjsInstance:this}),this._p2pEngine.on(Ri.Events.RESTART_P2P,this._restartEvent)),this.on(ki().Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(Ri.Events.RESTART_P2P,this._restartEvent),this._p2pEngine.hlsjs=null,this._p2pEngine=null)}))}get p2pEngine(){return this._p2pEngine}enableP2P(){this._p2pEngine&&(this._p2pEngine=this._p2pEngine.enableP2P())}disableP2P(){this._p2pEngine&&this._p2pEngine.disableP2P()}restartP2P(){this._p2pEngine&&(this._p2pEngine.disableP2P(),setTimeout((()=>{this.enableP2P()}),2e3),this._p2pEngine.removeListener(Ri.Events.RESTART_P2P,this._restartEvent))}}Ci.engineVersion=Ri.version,Ci.protocolVersion=Ri.protocolVersion,Ci.WEBRTC_SUPPORT=Ri.isSupported();const Mi=Ci})(),r=r.default})()));
|