@swarmcloud/hls 2.15.5 → 2.15.8

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.light.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,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.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(r,i){function s(r){e.removeListener(t,n),i(r)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",s),r([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&p(e,"error",t,r)}(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,r,i){var s,n,a,h;if(o(r),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),a=n[t]),void 0===a)a=n[t]=r,++e._eventsCount;else if("function"==typeof a?a=n[t]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),(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,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},s=u.bind(i);return s.listener=r,i.wrapFn=s,s}function c(e,t,r){var i=e._events;if(void 0===i)return[];var s=i[t];return void 0===s?[]:"function"==typeof s?r?[s.listener||s]:[s]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(s):g(s,s.length)}function f(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function g(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function p(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);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){i.once&&e.removeEventListener(t,s),r(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=[],r=1;r<arguments.length;r++)t.push(arguments[r]);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)i(l,this,t);else{var h=l.length,u=g(l,h);for(r=0;r<h;++r)i(u[r],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 r,i,s,n,a;if(o(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length-1;n>=0;n--)if(r[n]===t||r[n].listener===t){a=r[n].listener,s=n;break}if(s<0)return this;0===s?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,s),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var s,n=Object.keys(r);for(i=0;i<n.length;++i)"removeListener"!==(s=n[i])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);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 r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.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 r.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=i.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=r.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=r.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}()},917:e=>{!function t(r){var i;i=function(){"use strict";function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,c(i.key),i)}}function i(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function s(e,t,r){return(t=c(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}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 r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function u(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?h(Object(r),!0).forEach((function(t){s(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):h(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,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 r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=typeof i)return i;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,r)}function r(){return function(e,t,r){if(l())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var s=new(e.bind.apply(e,i));return r&&d(s,r.prototype),s}(e,arguments,a(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),d(r,e)},f(e)}function g(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var p,m,v={exports:{}},y=(p||(p=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new s(i,n||e,a),l=r?r+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 i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,s=[];if(0===this._eventsCount)return s;for(i in e=this._events)t.call(e,i)&&s.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,n=i.length,a=new Array(n);s<n;s++)a[s]=i[s].fn;return a},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,s,n,a){var o=r?r+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,i),!0;case 4:return u.fn.call(u.context,t,i,s),!0;case 5:return u.fn.call(u.context,t,i,s,n),!0;case 6:return u.fn.call(u.context,t,i,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,i);break;case 4:u[h].fn.call(u[h].context,t,i,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,r){return n(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return n(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,s){var n=r?r+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||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],u=o.length;l<u;l++)(o[l].fn!==t||s&&!o[l].once||i&&o[l].context!==i)&&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=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(v)),v.exports),E=g(y),S={exports:{}},T=(m||(m=1,function(e,t){var r,i,s,n,a;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.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 r.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=i.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=r.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=r.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}(S)),S.exports),_=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=b},b=Number.MAX_SAFE_INTEGER||9007199254740991,R=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}({}),P=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}({}),w="manifest",I="level",D="audioTrack",C="subtitleTrack",k="main",M="audio",x="subtitle",O=function(){function e(e,t,r){void 0===t&&(t=0),void 0===r&&(r=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_=r}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*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}(),N=function(){function e(e,t,r,i){void 0===i&&(i=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_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new O(e),this.fast_=new O(t),this.defaultTTFB_=i,this.ttfb_=new O(e)}var t=e.prototype;return t.update=function(e,t){var r=this.slow_,i=this.fast_,s=this.ttfb_;r.halfLife!==e&&(this.slow_=new O(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new O(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new O(e,s.getEstimate(),s.getTotalWeight()))},t.sample=function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},t.sampleTTFB=function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,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(){},i(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 r="["+e+"]:";this.trace=B,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)},B=function(){},U={trace:B,debug:B,log:B,warn:B,info:B,error:B};function G(){return n({},U)}function $(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):B}(e,r)}var H=G();function W(e,t,r){var i=G();if("object"==typeof console&&!0===e||"object"==typeof e){var s=["debug","log","info","warn","error"];s.forEach((function(t){i[t]=$(t,e,r)}));try{i.log('Debug logs enabled for "'+t+'" in hls.js version 1.6.2')}catch(e){return G()}s.forEach((function(t){H[t]=$(t,e)}))}else n(H,i);return i}var V,q,j=H,z=q?V:(q=1,V=void 0),K=g(z);function Y(e,t){if(void 0===t&&(t=!1),"undefined"!=typeof TextDecoder){var r=new TextDecoder("utf-8").decode(e);if(t){var i=r.indexOf("\0");return-1!==i?r.substring(0,i):r}return r.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}var X=function(e){for(var t="",r=0;r<e.length;r++){var i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t},Q=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}},J="audio",Z="video",ee="audiovideo",te=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=ne(this,"stats"))&&(t.enumerable=!0,Object.defineProperty(this,"stats",t))}var t=e.prototype;return t.setByteRange=function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]},t.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[J]=null,e[Z]=null,e[ee]=null},i(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={})[J]=null,e[Z]=null,e[ee]=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 Q),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=T.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}])}();function re(e){return"initSegment"!==e.sn}var ie=function(e){function t(t,r){var i;return(i=e.call(this,r)||this)._decryptdata=null,i._programDateTime=null,i._ref=null,i._bitrate=void 0,i.rawProgramDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.playlistOffset=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=t,i}o(t,e);var r=t.prototype;return r.addStart=function(e){this.setStart(this.start+e)},r.setStart=function(e){this.start=e,this._ref&&(this._ref.start=e)},r.setDuration=function(e){this.duration=e,this._ref&&(this._ref.duration=e)},r.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},r.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},r.setElementaryStreamInfo=function(e,t,r,i,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,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:s,partial:n}},i(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange){var t=this.byteRange[0],r=this.byteRange[1];if(_(t)&&_(r))return r-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)return this._decryptdata=this.levelkeys[t[0]].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=_(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=Object.keys(this.levelkeys),r=t.length;if(r>1||1===r&&this.levelkeys[t[0]].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){_(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return re(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(te),se=function(e){function t(t,r,i,s,n){var a;(a=e.call(this,i)||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=r,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),i(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)}}])}(te);function ne(e,t){var r=Object.getPrototypeOf(e);if(r)return Object.getOwnPropertyDescriptor(r,t)||ne(r,t)}var ae=Math.pow(2,32)-1,oe=[].push,le={video:1,audio:2,id3:3,text:4};function he(e){return String.fromCharCode.apply(null,e)}function ue(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function de(e,t){var r=fe(e,t);return r<0?4294967296+r:r}function ce(e,t){var r=de(e,t);return(r*=Math.pow(2,32))+de(e,t+4)}function fe(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ge(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function pe(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,s=0;s<i;){var n=de(e,s),a=n>1?s+n:i;if(he(e.subarray(s+4,s+8))===t[0])if(1===t.length)r.push(e.subarray(s+8,a));else{var o=pe(e.subarray(s+8,a),t.slice(1));o.length&&oe.apply(r,o)}s=a}return r}function me(e){var t=[],r=e[0],i=8,s=de(e,i);i+=4;var n=0,a=0;0===r?(n=de(e,i),a=de(e,i+4),i+=8):(n=ce(e,i),a=ce(e,i+8),i+=16),i+=2;var o=e.length+a,l=ue(e,i);i+=2;for(var h=0;h<l;h++){var u=i,d=de(e,u);u+=4;var c=2147483647&d;if(1==(2147483648&d)>>>31)return j.warn("SIDX has hierarchical references (not supported)"),null;var f=de(e,u);u+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+c-1}}),o+=c,i=u+=4}return{earliestPresentationTime:n,timescale:s,version:r,referencesCount:l,references:t}}function ve(e){for(var t=[],r=pe(e,["moov","trak"]),i=0;i<r.length;i++){var s=r[i],n=pe(s,["tkhd"])[0];if(n){var a=n[0],o=de(n,0===a?12:20),l=pe(s,["mdia","mdhd"])[0];if(l){var h=de(l,0===(a=l[0])?12:20),d=pe(s,["mdia","hdlr"])[0];if(d){var c=he(d.subarray(8,12)),f={soun:J,vide:Z}[c],g=ye(pe(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 pe(e,["moov","mvex","trex"]).forEach((function(e){var r=de(e,4),i=t[r];i&&(i.default={duration:de(e,12),flags:de(e,20)})})),t}function ye(e){var t,r=e.subarray(8),i=r.subarray(86),s=he(r.subarray(4,8)),n=s,a="enca"===s||"encv"===s;if(a){var o=pe(r,[s])[0];pe(o.subarray("enca"===s?28:78),["sinf"]).forEach((function(e){var t=pe(e,["schm"])[0];if(t){var r=he(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=pe(e,["frma"])[0];i&&(n=he(i))}}}))}var l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":var h=pe(i,["avcC"])[0];h&&h.length>3&&(n+="."+Te(h[1])+Te(h[2])+Te(h[3]),t=Ee("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var u=pe(r,[s])[0],d=pe(u.subarray(28),["esds"])[0];if(d&&d.length>7){var c=4;if(3!==d[c++])break;c=Se(d,c),c+=2;var f=d[c++];if(128&f&&(c+=2),64&f&&(c+=d[c++]),4!==d[c++])break;c=Se(d,c);var g=d[c++];if(64!==g)break;if(n+="."+Te(g),c+=12,5!==d[c++])break;c=Se(d,c);var p=d[c++],m=(248&p)>>3;31===m&&(m+=1+((7&p)<<3)+((224&d[c])>>5)),n+="."+m}break;case"hvc1":case"hev1":var v=pe(i,["hvcC"])[0];if(v&&v.length>12){var y=v[1],E=["","A","B","C"][y>>6],S=31&y,T=de(v,2),_=(32&y)>>5?"H":"L",L=v[12],b=v.subarray(6,12);n+="."+E+S,n+="."+T.toString(16).toUpperCase(),n+="."+_+L;for(var R="",A=b.length;A--;){var P=b[A];(P||R)&&(R="."+P.toString(16).toUpperCase()+R)}n+=R}t=Ee("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Ee(n,i)||n;break;case"vp09":var w=pe(i,["vpcC"])[0];if(w&&w.length>6){var I=w[4],D=w[5],C=w[6]>>4&15;n+="."+_e(I)+"."+_e(D)+"."+_e(C)}break;case"av01":var k=pe(i,["av1C"])[0];if(k&&k.length>2){var M=k[1]>>>5,x=31&k[1],O=k[2]>>>7?"H":"M",N=(64&k[2])>>6,F=(32&k[2])>>5,B=2===M&&N?F?12:10:N?10:8,U=(16&k[2])>>4,G=(8&k[2])>>3,$=(4&k[2])>>2,H=3&k[2];n+="."+M+"."+_e(x)+O+"."+_e(B)+"."+U+"."+G+$+H+"."+_e(1)+"."+_e(1)+"."+_e(1)+".0",t=Ee("dav1",i)}}return{codec:n,encrypted:a,supplemental:t}}function Ee(e,t){var r=pe(t,["dvvC"]),i=r.length?r[0]:pe(t,["dvcC"])[0];if(i){var s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return e+"."+_e(s)+"."+_e(n)}}function Se(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function Te(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function _e(e){return(e<10?"0":"")+e}function Le(e){var t=de(e,0),r=8;1&t&&(r+=4),4&t&&(r+=4);for(var i=0,s=de(e,4),n=0;n<s;n++)256&t&&(i+=de(e,r),r+=4),512&t&&(r+=4),1024&t&&(r+=4),2048&t&&(r+=4);return i}function be(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Re(e,t){var r=[],i=t.samples,s=t.timescale,n=t.id,a=!1;return pe(i,["moof"]).map((function(o){var l=o.byteOffset-8;pe(o,["traf"]).map((function(o){var h=pe(o,["tfdt"]).map((function(e){var t=e[0],r=de(e,4);return 1===t&&(r*=Math.pow(2,32),r+=de(e,8)),r/s}))[0];return void 0!==h&&(e=h),pe(o,["tfhd"]).map((function(h){var u=de(h,4),d=16777215&de(h,0),c=0,f=!!(16&d),g=0,p=!!(32&d),m=8;u===n&&(!!(1&d)&&(m+=8),!!(2&d)&&(m+=4),!!(8&d)&&(c=de(h,m),m+=4),f&&(g=de(h,m),m+=4),p&&(m+=4),"video"===t.type&&(a=Ae(t.codec)),pe(o,["trun"]).map((function(n){var o=n[0],h=16777215&de(n,0),u=!!(1&h),d=0,f=!!(4&h),p=!!(256&h),m=0,v=!!(512&h),y=0,E=!!(1024&h),S=!!(2048&h),T=0,_=de(n,4),L=8;u&&(d=de(n,L),L+=4),f&&(L+=4);for(var b=d+l,R=0;R<_;R++){if(p?(m=de(n,L),L+=4):m=c,v?(y=de(n,L),L+=4):y=g,E&&(L+=4),S&&(T=0===o?de(n,L):fe(n,L),L+=4),t.type===Z)for(var A=0;A<y;){var P=de(i,b);Pe(a,i[b+=4])&&we(i.subarray(b,b+P),a?2:1,e+T/s,r),b+=P,A+=P+4}e+=m/s}})))}))}))})),r}function Ae(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Pe(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6==(31&t)}function we(e,t,r,i){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){j.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===s[u++]){var d=ue(s,u);if(u+=2,49===d){var c=de(s,u);if(u+=4,1195456820===c){var f=s[u++];if(3===f){var g=s[u++],p=64&g,m=p?2+3*(31&g):0,v=new Uint8Array(m);if(p){v[0]=g;for(var y=1;y<m;y++)v[y]=s[u++]}i.push({type:f,payloadType:a,pts:r,bytes:v})}}}}}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++];i.push({payloadType:a,pts:r,uuid:E.join(""),userData:Y(L),userDataBytes:L})}}}function Ie(e){for(var t=e.byteLength,r=[],i=1;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return e;var s=t-r.length,n=new Uint8Array(s),a=0;for(i=0;i<s;a++,i++)a===r[0]&&(a++,r.shift()),n[i]=e[a];return n}function De(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}var Ce=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 Me(e,t){var r=ke[t];return!!r&&!!r[e.slice(0,4)]}function xe(e,t,r){return void 0===r&&(r=!0),!e.split(",").some((function(e){return!Oe(e,t,r)}))}function Oe(e,t,r){var i;void 0===r&&(r=!0);var s=De(r);return null!=(i=null==s?void 0:s.isTypeSupported(Ne(e,t)))&&i}function Ne(e,t){return t+"/mp4;codecs="+e}function Fe(e){if(e){var t=e.substring(0,4);return ke.video[t]}return 2}function Be(e){var t=Ce();return e.split(",").reduce((function(e,r){var i=t&&Ae(r)?9:ke.video[r];return i?(2*i+e)/(e?3:2):(ke.audio[r]+e)/(e?2:1)}),0)}var Ue={},Ge=/flac|opus|mp4a\.40\.34/i;function $e(e,t){return void 0===t&&(t=!0),e.replace(Ge,(function(e){return function(e,t){if(void 0===t&&(t=!0),Ue[e])return Ue[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i<r.length;i++){var s;if(Oe(r[i],"audio",t))return Ue[e]=r[i],r[i];if("mp3"===r[i]&&null!=(s=De(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)}))}function He(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function We(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function Ve(e){var t=De(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function qe(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var je=["NONE","TYPE-0","TYPE-1",null],ze=["SDR","PQ","HLG"];function Ke(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i<t/2?r?"v2":"YES":""}var Ye=function(){function e(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}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}(),Xe=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 r=null==(t=e.supplemental)?void 0:t.videoCodec;r&&r!==e.videoCodec&&(this.codecSet+=","+r.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 Qe(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return Qe(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),-1===i.indexOf(t)&&i.push(t)}},t.addFallback=function(){},i(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 Qe(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}var Je=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,i){if(e&&(i=e(r,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}}(t))};function Ze(e,t){j.log('[abr] start candidates with "'+e+'" ignored because '+t)}function et(e){return e.reduce((function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function tt(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}var rt=function(e){function t(t){var r;return(r=e.call(this,"abr",t.logger)||this).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,i=r,s=i.fragCurrent,n=i.partCurrent,a=i.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=r._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var m=p>-1&&p!==g,v=!!e||m;if(v||!l.paused&&l.playbackRate&&l.readyState){var y=a.mainForwardBufferInfo;if(v||null!==y){var E=r.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(!(c<=Math.max(E,d/(2*S)*1e3))){var T=y?y.len/S:0,L=u.loading.first?u.loading.first-u.loading.start:-1,b=u.loaded&&L>-1,R=r.getBwEstimate(),A=a.levels,w=A[g],I=Math.max(u.loaded,Math.round(d*(s.bitrate||w.averageBitrate)/8)),D=b?c-L:c;D<1&&b&&(D=Math.min(c,8*u.loaded/R));var C=b?1e3*u.loaded/D:0,k=E/1e3,M=C?(I-u.loaded)/C:8*I/R+k;if(!(M<=T)){var x,O=C?8*C:R,N=!0===(null==(t=(null==e?void 0:e.details)||r.hls.latestLevelDetails)?void 0:t.live),F=r.hls.config.abrBandWidthUpFactor,B=Number.POSITIVE_INFINITY;for(x=g-1;x>f;x--){var U=A[x].maxBitrate,G=!A[x].details||N;if((B=r.getTimeToLoadFrag(k,O,d*U,G))<Math.min(T,d+k))break}if(!(B>=M||B>10*d)){b?r.bwEstimator.sample(c-Math.min(E,L),u.loaded):r.bwEstimator.sampleTTFB(c);var $=A[x].maxBitrate;r.getBwEstimate()*F>$&&r.resetEstimator($);var H=r.findBestLevel($,f,x,0,T,1,1);H>-1&&(x=H),r.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: "+T.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: "+(_(R)?0|R:"Unknown")+" bps\n New BW estimate: "+(0|r.getBwEstimate())+" bps\n Switching to level "+x+" @ "+(0|$)+" bps"),a.nextLoadLevel=a.nextAutoLevel=x,r.clearTimer();var W=function(){if(r.clearTimer(),r.fragCurrent===s&&r.hls.loadLevel===x&&x>0){var e=r.getStarvationDelay();if(r.warn("Aborting inflight request "+(x>0?"and switching down":"")+"\n Fragment duration: "+s.duration.toFixed(3)+" s\n Time to underbuffer: "+e.toFixed(3)+" s"),s.abortRequests(),r.fragCurrent=r.partCurrent=null,x>f){var t=r.findBestLevel(r.hls.levels[f].bitrate,f,x,0,e,1,1);-1===t&&(t=f),r.hls.nextLoadLevel=r.hls.nextAutoLevel=t,r.resetEstimator(r.hls.levels[t].bitrate)}}};m||M>2*B?W():r.timer=self.setInterval(W,1e3*B),a.trigger(P.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:u})}}}}}}}},r.hls=t,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}o(t,e);var r=t.prototype;return r.resetEstimator=function(e){e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},r.initEstimator=function(){var e=this.hls.config;return new N(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},r.registerListeners=function(){var e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.FRAG_LOADING,this.onFragLoading,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(P.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.FRAG_LOADING,this.onFragLoading,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(P.ERROR,this.onError,this))},r.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},r.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},r.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},r.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},r.onFragLoading=function(e,t){var r,i=t.frag;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},r.onLevelSwitching=function(e,t){this.clearTimer()},r.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 r=t.frag,i=this.fragCurrent,s=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var n=performance.now(),a=s?s.stats:r.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)}}},r.getTimeToLoadFrag=function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)},r.onLevelLoaded=function(e,t){var r=this.hls.config,i=t.stats.loading,s=i.end-i.first;_(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},r.onFragLoaded=function(e,t){var r=t.frag,i=t.part,s=i?i.stats:r.stats;if(r.type===k&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var n=i?i.duration:r.duration,a=this.hls.levels[r.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(r.bitrateTest){var h={stats:s,frag:r,part:i,id:r.type};this.onFragBuffered(P.FRAG_BUFFERED,h),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part,s=null!=i&&i.stats.loaded?i.stats:r.stats;if(!s.aborted&&!this.ignoreFragment(r)){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(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},r.ignoreFragment=function(e){return e.type!==k||"initSegment"===e.sn},r.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},r.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},r.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,s=r.config,n=r.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,i,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,i,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=r.levels[n],m=r.loadLevelObj;return m&&(null==p?void 0:p.bitrate)<m.bitrate?n:r.loadLevel},r.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r},r.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},r.findBestLevel=function(e,t,r,i,s,n,a){var o,l=this,h=i+s,u=this.lastLoadedFragLevel,d=-1===u?this.hls.firstLevel:u,c=this.fragCurrent,f=this.partCurrent,g=this.hls,p=g.levels,m=g.allAudioTracks,v=g.loadLevel,y=g.config;if(1===p.length)return 0;var E,S=p[d],T=!(null==(o=this.hls.latestLevelDetails)||!o.live),L=-1===v||-1===u,b="SDR",R=(null==S?void 0:S.frameRate)||0,A=y.audioPreference,P=y.videoPreference,w=(this.audioTracksByGroup||(this.audioTracksByGroup=et(m)),-1);if(L){if(-1!==this.firstSelection)return this.firstSelection;var I=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce((function(e,t,r){if(!t.codecSet)return e;var i=t.audioGroups,s=e[t.codecSet];s||(e[t.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,t.bitrate);var n=Math.min(t.height,t.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,t.frameRate),s.minIndex=Math.min(s.minIndex,r),s.maxScore=Math.max(s.maxScore,t.score),s.fragmentError+=t.fragmentError,s.videoRanges[t.videoRange]=(s.videoRanges[t.videoRange]||0)+1,e}),{})}(p,0,t,r)),D=function(e,t,r,i,s){for(var n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.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,m=0,v=[],y=function(e,t){var r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){var s="SDR"!==(i=t.allowedVideoRanges||ze.slice(0)).join("")&&!t.videoCodec;(r=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}())||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}(t,s),E=y.preferHDR,S=y.allowedVideoRanges,T=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--;)T();c=_(c)?c:0,f=_(f)?f:0;var b=Math.max(1080,c),R=Math.max(30,f);g=_(g)?g:r,r=Math.max(g,r),d||(t=void 0);var A=n.length>1;return{codecSet:n.reduce((function(t,i){var s=e[i];if(i===t)return t;if(v=d?S.filter((function(e){return s.videoRanges[e]>0})):[],A){if(s.minBitrate>r)return Ze(i,"min bitrate of "+s.minBitrate+" > current estimate of "+r),t;if(!s.hasDefaultAudio)return Ze(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Ze(i,'audio codec preference "'+o+'" not found'),t;if(a&&!h){if(!s.channels[a])return Ze(i,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(s.channels)+")"),t}else if((!o||h)&&u&&0===s.channels[2])return Ze(i,"no renditions with stereo sound found"),t;if(s.minHeight>b)return Ze(i,"min resolution of "+s.minHeight+" > maximum of "+b),t;if(s.minFramerate>R)return Ze(i,"min framerate of "+s.minFramerate+" > maximum of "+R),t;if(!v.some((function(e){return s.videoRanges[e]>0})))return Ze(i,"no variants with VIDEO-RANGE of "+Je(v)+" found"),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Ze(i,'video codec preference "'+l+'" not found'),t;if(s.maxScore<m)return Ze(i,"max score of "+s.maxScore+" < selected max of "+m),t}return t&&(Be(i)>=Be(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,m=s.maxScore,i)}),void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}(I,b,e,A,P),C=D.codecSet,k=D.videoRanges,M=D.minFramerate,x=D.minBitrate,O=D.minIndex,N=D.preferHDR;w=O,E=C,b=N?k[k.length-1]:k[0],R=M,e=Math.max(e,x),this.log("picked start tier "+Je(D))}else E=null==S?void 0:S.codecSet,b=null==S?void 0:S.videoRange;for(var F,B=f?f.duration:c?c.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,G=[],$=function(){var t,o=p[H],c=H>d;if(!o)return 0;if((E&&o.codecSet!==E||b&&o.videoRange!==b||c&&R>o.frameRate||!c&&R>0&&R<o.frameRate||o.supportedResult&&(null==(t=o.supportedResult.decodingInfoResults)||!t[0].smooth))&&(!L||H!==w))return G.push(H),0;var g,m=o.details,y=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||B;g=c?a*e:n*e;var S=B&&i>=2*B&&0===s?o.averageBitrate:o.maxBitrate,A=l.getTimeToLoadFrag(U,g,S*y,void 0===m);if(g>=S&&(H===u||0===o.loadError&&0===o.fragmentError)&&(A<=U||!_(A)||T&&!l.bitrateTestDelay||A<h)){var P=l.forcedAutoLevel;return H===v||-1!==P&&P===v||(G.length&&l.trace("Skipped level(s) "+G.join(",")+" of "+r+' max with CODECS and VIDEO-RANGE:"'+p[G[0]].codecs+'" '+p[G[0]].videoRange+'; not compatible with "'+E+'" '+b),l.info("switch candidate:"+d+"->"+H+" adjustedbw("+Math.round(g)+")-bitrate="+Math.round(g-S)+" ttfb:"+U.toFixed(1)+" avgDuration:"+y.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+A.toFixed(1)+" firstSelection:"+L+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+v)),L&&(l.firstSelection=H),{v:H}}},H=r;H>=t;H--)if(0!==(F=$())&&F)return F.v;return-1},r.deriveNextAutoLevel=function(e){var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)},i(t,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,r,t,0,s,1,1);if(n>-1)return n;var a=this.hls.firstLevel,o=Math.min(Math.max(a,r),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(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var s=this.hls.levels;if(s.length>Math.max(e,i)&&s[e].loadError<=s[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(F),it=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,r){if(null!==this.queues&&null!==this.tracks){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}},t.appendBlocker=function(e){var t=this;return new Promise((function(r){var i={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(i,e)}))},t.prependBlocker=function(e){var t=this;return new Promise((function(r){if(t.queues){var i={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(i)}}))},t.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(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 r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;var s=null==(i=this.tracks[e])?void 0:i.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,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer"+(i.updating?" updating":"")+(r.ended?" ended":"")+(r.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}(),st=function(e,t){for(var r=0,i=e.length-1,s=null,n=null;r<=i;){var a=t(n=e[s=(r+i)/2|0]);if(a>0)r=s+1;else{if(!(a<0))return n;i=s-1}}return null};function nt(e,t,r,i,s){void 0===r&&(r=0),void 0===i&&(i=0),void 0===s&&(s=.005);var n=null;if(e){n=t[1+e.sn-t[0].sn]||null;var a=e.endDTS-r;a>0&&a<15e-7&&(r+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===at(r,i,n)||function(e,t,r){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var i=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),r);return e.start<=i}return!1}(n,e,Math.min(s,i))))return n;var o=st(t,at.bind(null,r,i));return!o||o===e&&n?n:o}function at(e,t,r){if(void 0===e&&(e=0),void 0===t&&(t=0),r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function ot(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function lt(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 ht(e,t){var r=lt(t);return e.default[(r?"timeout":"error")+"Retry"]}function ut(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function dt(e){return u(u({},e),{errorRetry:null,timeoutRetry:null})}function ct(e,t,r,i){if(!e)return!1;var s=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(s)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,n):n}var ft=function(e){function t(t){var r;return(r=e.call(this,"error-controller",t.logger)||this).hls=void 0,r.playlistError=0,r.penalizedRenditions={},r.hls=t,r.registerListeners(),r}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(P.ERROR,this.onError,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.ERROR,this.onError,this),e.off(P.ERROR,this.onErrorOut,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this))},r.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},r.startLoad=function(e){},r.stopLoad=function(){this.playlistError=0},r.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===k?e.level:this.hls.loadLevel},r.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},r.onLevelUpdated=function(){this.playlistError=0},r.onError=function(e,t){var r;if(!t.fatal){var i=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!=(r=t.frag)&&r.gap)return void(t.errorAction=gt());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,o=t.parent===k?t.level:i.loadLevel;return void(t.details===A.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(a=n.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o)));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 l=i.loadLevelObj;if(l&&(s.type===D&&l.hasAudioGroup(s.groupId)||s.type===C&&l.hasSubtitleGroup(s.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var h=i.loadLevelObj,u=null==h?void 0:h.attrs["HDCP-LEVEL"];return void(u?t.errorAction={action:2,flags:2,hdcpLevel:u}:this.keySystemError(t));case A.BUFFER_ADD_CODEC_ERROR:case A.REMUX_ALLOC_ERROR:case A.BUFFER_APPEND_ERROR:var d;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(d=t.level)?d:i.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=gt())}t.type===R.KEY_SYSTEM_ERROR&&this.keySystemError(t)}},r.keySystemError=function(e){var t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)},r.getPlaylistRetryOrSwitchAction=function(e,t){var r=ht(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(ct(r,i,lt(e),e.response))return{action:5,flags:0,retryConfig:r,retryCount:i};var s=this.getLevelSwitchAction(e,t);return r&&(s.retryConfig=r,s.retryCount=i),s},r.getFragRetryOrSwitchAction=function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],s=t.config,n=s.fragLoadPolicy,a=s.keyLoadPolicy,o=ht(e.details.startsWith("key")?a:n,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(i&&(e.details!==A.FRAG_GAP&&i.fragmentError++,ct(o,l,lt(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(e,r);return o&&(h.retryConfig=o,h.retryCount=l),h},r.getLevelSwitchAction=function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var s,n,a=e.details;i.loadError++,a===A.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,h=r.loadLevel,u=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||(r.loadLevel=-1);for(var c,f=null==(s=e.frag)?void 0:s.type,g=(f===M&&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 i.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,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r})),m=null!=(n=e.context)?n:{},v=m.type,y=m.groupId,E=function(){var t=(S+h)%l.length;if(t!==h&&t>=u&&t<=d&&0===l[t].loadError){var r,s,n=l[t];if(a===A.FRAG_GAP&&f===k&&e.frag){var c=l[t].details;if(c){var m=nt(e.frag,c.fragments,e.frag.start);if(null!=m&&m.gap)return 0}}else{if(v===D&&n.hasAudioGroup(y)||v===C&&n.hasSubtitleGroup(y))return 0;if(f===M&&null!=(r=i.audioGroups)&&r.some((function(e){return n.hasAudioGroup(e)}))||f===x&&null!=(s=i.subtitleGroups)&&s.some((function(e){return n.hasSubtitleGroup(e)}))||g&&i.audioCodec===n.audioCodec||!g&&i.audioCodec!==n.audioCodec||p&&i.codecSet===n.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(c=E())||1!==c););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}},r.onErrorOut=function(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.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()},r.sendAlternateToPenaltyBox=function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.flags,s=r.hdcpLevel,n=r.nextAutoLevel;switch(i){case 0:this.switchLevel(e,n);break;case 2:s&&(t.maxHdcpLevel=je[je.indexOf(s)-1],r.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')}r.resolved||this.switchLevel(e,n)}},r.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 r=qe(e.mimeType),i=this.hls.levels,s=i.length;s--;)i[s][e.sourceBufferName+"Codec"]===r&&this.hls.removeLevel(s)},t}(F);function gt(e){var t={action:0,flags:0};return e&&(t.resolved=!0),t}var pt={length:0,start:function(){return 0},end:function(){return 0}},mt=function(){function e(){}return e.isBuffered=function(t,r){if(t)for(var i=e.getBuffered(t),s=i.length;s--;)if(r>=i.start(s)&&r<=i.end(s))return!0;return!1},e.bufferedRanges=function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]},e.timeRangesToArray=function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t},e.bufferInfo=function(t,r,i){if(t){var s=e.bufferedRanges(t);if(s.length)return e.bufferedInfo(s,r,i)}return{len:0,start:r,end:r,bufferedIndex:-1}},e.bufferedInfo=function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var i=-1,s=[];if(r)for(var n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(i=n);var a=s.length;if(a){var o=s[a-1].end;e[n].start-o<r?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===i&&t>=f&&t<=g&&(i=c),t+r>=f&&t<g)u=f,h=(d=g)-t;else if(t+r<f){l=f;break}}return{len:h,start:u||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:i}},e.getBuffered=function(e){try{return e.buffered||pt}catch(e){return j.log("failed to get media.buffered",e),pt}},e}(),vt=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,yt="HlsJsTrackRemovedError",Et=function(e){function t(t){var r;return(r=e.call(this,t)||this).name=yt,r}return o(t,e),t}(f(Error)),St=function(e){function t(t,r){var i,s;return(i=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,i.fragmentTracker=void 0,i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.blockedAudioAppend=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,s=t.mediaSource;e&&i.log("Media source opened"),r&&s&&(s.removeEventListener("sourceopen",i._onMediaSourceOpen),r.removeEventListener("emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(P.MEDIA_ATTACHED,{media:r,mediaSource:s}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){i.log("Media source closed")},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource ("+r+" > "+t+")")},i.hls=t,i.fragmentTracker=r,i.appendSource=(s=De(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}o(t,e);var r=t.prototype;return r.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},r.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},r.registerListeners=function(){var e=this.hls;e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.BUFFER_RESET,this.onBufferReset,this),e.on(P.BUFFER_APPENDING,this.onBufferAppending,this),e.on(P.BUFFER_CODECS,this.onBufferCodecs,this),e.on(P.BUFFER_EOS,this.onBufferEos,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.FRAG_PARSED,this.onFragParsed,this),e.on(P.FRAG_CHANGED,this.onFragChanged,this),e.on(P.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.BUFFER_RESET,this.onBufferReset,this),e.off(P.BUFFER_APPENDING,this.onBufferAppending,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.BUFFER_EOS,this.onBufferEos,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.FRAG_PARSED,this.onFragParsed,this),e.off(P.FRAG_CHANGED,this.onFragChanged,this),e.off(P.ERROR,this.onError,this)},r.transferMedia=function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};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===r?n(i,o.tracks):this.sourceBuffers.forEach((function(t){var r=t[0];r&&(i[r]=n({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null})),{media:t,mediaSource:r,tracks:i}},r.initTracks=function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},r.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},r.onManifestParsed=function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(i+" bufferCodec event(s) expected."),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()},r.onMediaAttaching=function(e,t){var r=this.media=t.media,i=De(this.appendSource);if(this.transferData=this.overrides=void 0,r&&i){var s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),s)this._objectUrl=r.src,this.attachTransferred();else{var a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&n instanceof o,Tt(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,a),r.load()}catch(e){r.src=a}else r.src=a}r.addEventListener("emptied",this._onMediaEmptied)}},r.assignMediaSource=function(e){var t,r;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(r=e.constructor)?void 0:r.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))},r.attachTransferred=function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,s=r.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=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: "+Je(i,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+Je(s,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!function(e,t){var r=Object.keys(e),i=Object.keys(t),s=r.length,n=i.length;return!s||!n||s===n&&!r.some((function(e){return-1===i.indexOf(e)}))}(s,i)){r.mediaSource=null,r.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(i)+'") start time: '+u+" currentTime: "+l),this.onMediaDetaching(P.MEDIA_DETACHING,{}),this.onMediaAttaching(P.MEDIA_ATTACHING,r),void(t.currentTime=u))}this.transferData=void 0,n.forEach((function(t){var r=t,i=s[r];if(i){var n=i.buffer;if(n){var a=e.fragmentTracker,o=i.id;if(a.hasFragments(o)||a.hasParts(o)){var l=mt.getBuffered(n);a.detectEvictedFragments(r,l,o,null,!0)}var h=_t(r),u=[r,n];e.sourceBuffers[h]=u,n.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},r.onMediaDetaching=function(e,t){var r=this,i=!!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 "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.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),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&Tt(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(P.MEDIA_DETACHED,t)},r.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];r&&e.resetBuffer(r)})),this.initTracks()},r.resetBuffer=function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},r.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[_t(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)},r.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new it(this.tracks)},r.onBufferCodecs=function(e,t){var r=this,i=this.tracks,s=Object.keys(t);this.log('BUFFER_CODECS: "'+s+'" (current SB count '+this.sourceBufferCount+")");var n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&s.some((function(e){return!i[e]}));n||a?this.warn('Unsupported transition between "'+Object.keys(i)+'" and "'+s+'" SourceBuffers'):(s.forEach((function(e){var s,n,a,o=t[e],l=o.id,h=o.codec,u=o.levelCodec,d=o.container,c=o.metadata,f=o.supplemental,g=i[e],p=null==(s=r.transferData)||null==(n=s.tracks)?void 0:n[e],m=null!=p&&p.buffer?p:g,v=(null==m?void 0:m.pendingCodec)||(null==m?void 0:m.codec),y=null==m?void 0:m.levelCodec;g||(g=i[e]={buffer:void 0,listeners:[],codec:h,supplemental:f,container:d,levelCodec:u,metadata:c,id:l});var E=He(v,y),S=null==E?void 0:E.replace(vt,"$1"),T=He(h,u),_=null==(a=T)?void 0:a.replace(vt,"$1");T&&E&&S!==_&&("audio"===e.slice(0,5)&&(T=$e(T,r.appendSource)),r.log("switching codec "+v+" to "+T),T!==(g.pendingCodec||g.codec)&&(g.pendingCodec=T),g.container=d,r.appendChangeType(e,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())},r.appendChangeType=function(e,t,r){var i=this,s=t+";codecs="+r,n={label:"change-type="+s,execute:function(){var n=i.tracks[e];if(n){var a=n.buffer;null!=a&&a.changeType&&(i.log("changing "+e+" sourceBuffer type to "+s),a.changeType(s),n.codec=r,n.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(n,e,this.isPending(this.tracks[e]))},r.blockAudio=function(e){var t,r=this,i=e.start,s=i+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(i,k))?void 0:t.gap)){var n={label:"block-audio",execute:function(){var e,t=r.tracks.video;(r.lastVideoAppendEnd>s||null!=t&&t.buffer&&mt.isBuffered(t.buffer,s)||!0===(null==(e=r.fragmentTracker.getAppendedFrag(s,k))?void 0:e.gap))&&(r.blockedAudioAppend=null,r.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}},r.unblockAudio=function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))},r.onBufferAppending=function(e,t){var r=this,i=this.tracks,s=t.data,n=t.type,a=t.parent,o=t.frag,l=t.part,h=t.chunkMeta,u=h.buffering[n],d=o.sn,c=self.performance.now();u.start=c;var f=o.stats.buffering,g=l?l.stats.buffering:null;0===f.start&&(f.start=c),g&&0===g.start&&(g.start=c);var p=i.audio,m=!1;"audio"===n&&"audio/mpeg"===(null==p?void 0:p.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var v=this.tracks.video,y=null==v?void 0:v.buffer;if(y&&"initSegment"!==d){var E=l||o,S=this.blockedAudioAppend;if("audio"!==n||"main"===a||this.blockedAudioAppend){if("video"===n){var T=E.end;if(S){var _=S.frag.start;(T>_||T<this.lastVideoAppendEnd||mt.isBuffered(y,_))&&this.unblockAudio()}this.lastVideoAppendEnd=T}}else{var L=E.start+.05*E.duration,b=y.buffered,w=this.currentOp("video");b.length||w?!w&&!mt.isBuffered(y,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(E):this.blockAudio(E)}}var I=(l||o).start,D={label:"append-"+n,execute:function(){if(u.executeStart=self.performance.now(),m){var e=r.tracks[n];if(e){var t=e.buffer;if(t){var i=I-t.timestampOffset;Math.abs(i)>=.1&&(r.log("Updating audio SourceBuffer timestampOffset to "+I+" (delta: "+i+") sn: "+d+")"),t.timestampOffset=I)}}}r.appendExecutor(s,n)},onStart:function(){},onComplete:function(){var e=self.performance.now();u.executeEnd=u.end=e,0===f.first&&(f.first=e),g&&0===g.first&&(g.first=e);var t={};r.sourceBuffers.forEach((function(e){var r=e[0],i=e[1];r&&(t[r]=mt.getBuffered(i))})),r.appendErrors[n]=0,"audio"===n||"video"===n?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(P.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:t})},onError:function(e){var t,i={type:R.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=r.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR)i.details=A.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&r.mediaSourceOpenOrEnded&&!s)i.errorAction=gt(!0);else if(e.name===yt&&0===r.sourceBufferCount)i.errorAction=gt(!0);else{var a=++r.appendErrors[n];r.warn("Failed "+a+"/"+r.hls.config.appendErrorMaxRetry+' times to append segment in "'+n+'" sourceBuffer ('+(s||"no media error")+")"),(a>=r.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}r.hls.trigger(P.ERROR,i)}};this.append(D,n,this.isPending(this.tracks[n]))},r.getFlushOp=function(e,t,r){var i=this;return this.log('queuing "'+e+'" remove '+t+"-"+r),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){i.hls.trigger(P.BUFFER_FLUSHED,{type:e})},onError:function(s){i.warn("Failed to remove "+t+"-"+r+' from "'+e+'" SourceBuffer',s)}}},r.onBufferFlushing=function(e,t){var r=this,i=t.type,s=t.startOffset,n=t.endOffset;i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.append(r.getFlushOp(t,s,n),t)}))},r.onFragParsed=function(e,t){var r=this,i=t.frag,s=t.part,n=[],a=s?s.elementaryStreams:i.elementaryStreams;a[ee]?n.push("audiovideo"):(a[J]&&n.push("audio"),a[Z]&&n.push("video")),0===n.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);var t=s?s.stats:i.stats;r.hls.trigger(P.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})}),n).catch((function(e){r.warn("Fragment buffered callback "+e),r.stepOperationQueue(r.sourceBufferTypes)}))},r.onFragChanged=function(e,t){this.trimBuffers()},r.onBufferEos=function(e,t){var r,i=this;this.sourceBuffers.forEach((function(e){var r=e[0];if(r){var s=i.tracks[r];t.type&&t.type!==r||(s.ending=!0,s.ended||(s.ended=!0,i.log(r+" buffer reached EOS")))}}));var s=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,r=e[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)}))&&(s?(this.log("Queueing EOS"),this.blockUntilOpen((function(){i.tracksEnded();var e=i.mediaSource;e&&"open"===e.readyState?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(P.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(P.BUFFERED_TO_END,void 0)))},r.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}}))},r.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())},r.updateDuration=function(){var e=this,t=this.getDurationAndRange();t&&this.blockUntilOpen((function(){return e.updateMediaSource(t)}))},r.onError=function(e,t){if(t.details===A.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;_(i)&&i!==t.frag.level&&this.resetAppendErrors()}},r.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},r.trimBuffers=function(){var e=this.hls,t=this.details,r=this.media;if(r&&null!==t&&this.sourceBufferCount){var i=e.config,s=r.currentTime,n=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(_(a)&&a>=0){var o=Math.max(a,n),l=Math.floor(s/n)*n-o;this.flushBackBuffer(s,n,l)}if(_(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){var h=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),u=Math.max(h,n),d=Math.floor(s/n)*n+u;this.flushFrontBuffer(s,n,d)}}},r.flushBackBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(e){var t=e[0],s=e[1];if(s){var n=mt.getBuffered(s);if(n.length>0&&r>n.start(0)){var a;i.hls.trigger(P.BACK_BUFFER_REACHED,{bufferEnd:r});var o=i.tracks[t];if(null!=(a=i.details)&&a.live)i.hls.trigger(P.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=o&&o.ended)return void i.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");i.hls.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:t})}}}))},r.flushFrontBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(t){var s=t[0],n=t[1];if(n){var a=mt.getBuffered(n),o=a.length;if(o<2)return;var l=a.start(o-1),h=a.end(o-1);if(r>l||e>=l&&e<=h)return;i.hls.trigger(P.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}}))},r.getDurationAndRange=function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&r.setLiveSeekableRange){var s=Math.max(0,t.fragmentStart);return{duration:1/0,start:s,end:Math.max(s,i)}}return{duration:1/0}}var n=null==(e=this.overrides)?void 0:e.duration;if(n)return _(n)?{duration:n}:null;var a=this.media.duration;return i>(_(r.duration)?r.duration:0)&&i>a||!_(a)?{duration:i}:null},r.updateMediaSource=function(e){var t=e.duration,r=e.start,i=e.end,s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==t&&(_(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),s.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to "+s.duration+". Setting seekable range to "+r+"-"+i+"."),s.setLiveSeekableRange(r,i)))},r.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+Je(r)),this.tracksReady){var i,s=null==(i=this.transferData)?void 0:i.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}},r.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(r){var i=r[0],s=r[1];if(i){var n=e.tracks[i];t[i]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}})),this.hls.trigger(P.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var r=t[0];e.executeNext(r)}))}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}},r.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var s=i,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":"")+" "+Je(n));try{var l=r.addSourceBuffer(o),h=_t(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(P.ERROR,{type:R.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()},r.getTrackCodec=function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&xe(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),s=0;s<i.length;s++)Me(i[s],"video")||r.push(i[s]);return t&&r.push(t),r.join(",")}(i,r));var s=He(i,e.levelCodec);return s?"audio"===t.slice(0,5)?$e(s,this.appendSource):s:""},r.trackSourceBuffer=function(e,t){var r=this,i=t.buffer;if(i){var s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,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 i=t.removedRanges;null!=i&&i.length&&r.hls.trigger(P.BUFFER_FLUSHED,{type:e})}))}},r.onSBUpdateStart=function(e){var t=this.currentOp(e);t&&t.onStart()},r.onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)},r.onSBUpdateError=function(e,t){var r,i=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(r=this.mediaSource)?void 0:r.readyState));this.error(""+i,t),this.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var s=this.currentOp(e);s&&s.onError(i)},r.removeExecutor=function(e,t,r){var i=this.media,s=this.mediaSource,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!s||!a)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(e);var o=_(i.duration)?i.duration:1/0,l=_(s.duration)?s.duration:1/0,h=Math.max(0,t),u=Math.min(r,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)},r.appendExecutor=function(e,t){var r=this.tracks[t],i=null==r?void 0:r.buffer;if(!i)throw new Et("Attempting to append to the "+t+" SourceBuffer, but it does not exist");r.ending=!1,r.ended=!1,i.appendBuffer(e)},r.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)}},r.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],r=e[1];return t&&r.updating}))},r.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var r=t[0];return r&&!!e.currentOp(r)}))},r.isPending=function(e){return!!e&&!e.buffer},r.blockBuffers=function(e,t){var r=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 i=this.operationQueue,s=t.map((function(e){return r.appendBlocker(e)}));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then((function(t){i===r.operationQueue&&(e(),r.stepOperationQueue(r.sourceBufferTypes))}))},r.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;i&&!i.updating&&t.shiftAndExecuteNext(e)}))},r.append=function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)},r.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},r.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},r.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},r.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},r.addBufferListener=function(e,t,r){var i=this.tracks[e];if(i){var s=i.buffer;if(s){var n=r.bind(this,e);i.listeners.push({event:t,listener:n}),s.addEventListener(t,n)}}},r.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach((function(e){r.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},i(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,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var r,i,s=t[0];return s&&(!(null!=(r=e.tracks[s])&&r.ended)||(null==(i=e.tracks[s])?void 0:i.ending))}))}},{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,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,r){return t+(e.isPending(e.tracks[r])?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 Tt(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function _t(e){return"audio"===e?1:0}var Lt=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(P.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.BUFFER_CODECS,this.onBufferCodecs,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListener=function(){var e=this.hls;e.off(P.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this)},t.onFpsDropLevelCapping=function(e,t){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.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 r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&_(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,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+r+": "+e[r].height+"p@"+e[r].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var s=i.filter((function(e,i){return r.isLevelAllowed(e)&&i<=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 r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.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,r){if(null==e||!e.length)return-1;for(var i,s,n=e.length-1,a=Math.max(t,r),o=0;o<e.length;o+=1){var l=e[o];if((l.width>=a||l.height>=a)&&(i=l,!(s=e[o+1])||i.width!==s.width||i.height!==s.height)){n=o;break}}return n},i(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)}}])}(),bt=/^(\d+)x(\d+)$/,Rt=/(.+?)=(".*?"|.*?)(?:,|$)/g,At=function(){function e(t,r){"string"==typeof t&&(t=e.parseAttrList(t,r)),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 r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}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 r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var r=this[e];return(r?r.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=bt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var r,i={};for(Rt.lastIndex=0;null!==(r=Rt.exec(e));){var s=r[1].trim(),n=r[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));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":j.warn(e+": attribute "+s+" is missing quotes")}i[s]=n}return i},i(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function Pt(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var wt=i((function(e,t,r){var i;if(void 0===r&&(r=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!=(i=null==t?void 0:t.tagOrder)?i:r,t){var s=t.attr;for(var a in s)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==s[a]){j.warn('DATERANGE tag attribute: "'+a+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=a;break}e=n(new At({}),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"]);_(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?(j.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(_(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&&_(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)}}]),It=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}return e.prototype.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1},i(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&_(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(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){var e;return null!=(e=this.fragments)&&e.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 r=e.length;r--;)if(e[r].index>t)return e[r].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 Dt(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Ct(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)}}var kt=function(){function e(e,t,r,i,s){void 0===i&&(i=[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=r,this.keyFormatVersions=i,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Dt(e)}e.clearKeyUriToKeyIdMap=function(){};var t=e.prototype;return t.isSupported=function(){if(this.method){if(Dt(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1},t.getDecryptData=function(t){if(!this.encrypted||!this.uri)return null;if(Dt(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&(j.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0);var r=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t);return new e(this.method,this.uri,"identity",this.keyFormatVersions,r)}return this},e}(),Mt=/#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,xt=/#EXT-X-MEDIA:(.*)/g,Ot=/^#EXT(?:INF|-X-TARGETDURATION):/m,Nt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ft=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("|")),Bt=function(){function e(){}return e.findGroup=function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}},e.resolve=function(e,t){return T.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.isMediaPlaylist=function(e){return Ot.test(e)},e.parseMasterPlaylist=function(t,r){var i,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},n=[];for(Mt.lastIndex=0;null!=(i=Mt.exec(t));)if(i[1]){var a,o=new At(i[1],s),l=i[2],h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,r)},u=o.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),Wt(o.CODECS,h);var d=o["SUPPLEMENTAL-CODECS"];d&&(h.supplemental={},Wt(d,h.supplemental)),null!=(a=h.unknownCodecs)&&a.length||n.push(h),s.levels.push(h)}else if(i[3]){var c=i[3],f=i[4];switch(c){case"SESSION-DATA":var g=new At(f,s),p=g["DATA-ID"];p&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[p]=g);break;case"SESSION-KEY":var m=$t(f,r,s);m.encrypted&&m.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(m)):j.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+f+'"');break;case"DEFINE":break;case"CONTENT-STEERING":var v=new At(f,s);s.contentSteering={uri:e.resolve(v["SERVER-URI"],r),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":s.startTimeOffset=Ht(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,r,i){var s,n={},a=i.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(xt.lastIndex=0;null!==(s=xt.exec(t));){var h=new At(s[1],i),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,m=h.CHARACTERISTICS,v=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,r):""};if(g&&(y.assocLang=g),p&&(y.channels=p),m&&(y.characteristics=m),v&&(y.instreamId=v),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Vt(y,E,"audioCodec"),Vt(y,E,"textCodec")}c.push(y)}}return n},e.parseLevelPlaylist=function(e,t,r,i,s,a){var o,l,h,u,d,c={url:t},f=new It(t),g=f.fragments,p=[],m=null,v=0,y=0,E=0,S=0,T=0,L=null,b=new ie(i,c),R=-1,A=!1,P=null;if(Nt.lastIndex=0,f.m3u8=e,f.hasVariableRefs=!1,"#EXTM3U"!==(null==(o=Nt.exec(e))?void 0:o[0]))return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;null!==(l=Nt.exec(e));){A&&(A=!1,(b=new ie(i,c)).playlistOffset=E,b.start=E,b.sn=v,b.cc=S,T&&(b.bitrate=T),b.level=r,m&&(b.initSegment=m,m.rawProgramDateTime&&(b.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),P&&(b.setByteRange(P),P=null)));var w=l[1];if(w){b.duration=parseFloat(w);var I=(" "+l[2]).slice(1);b.title=I||null,b.tagList.push(I?["INF",w,I]:["INF",w])}else if(l[3]){if(_(b.duration)){b.playlistOffset=E,b.start=E,u&&zt(b,u,f),b.sn=v,b.level=r,b.cc=S,g.push(b);var D=(" "+l[3]).slice(1);b.relurl=D,qt(b,L,p),L=b,E+=b.duration,v++,y=0,A=!0}}else{if(!(l=l[0].match(Ft))){j.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);var C=(" "+l[h]).slice(1),k=(" "+l[h+1]).slice(1),M=l[h+2]?(" "+l[h+2]).slice(1):null;switch(C){case"BYTERANGE":L?b.setByteRange(k,L):b.setByteRange(k);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=k,b.tagList.push(["PROGRAM-DATE-TIME",k]),-1===R&&(R=g.length);break;case"PLAYLIST-TYPE":f.type&&Kt(f,C,l),f.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?Kt(f,C,l):g.length>0&&Yt(f,C,l),v=f.startSN=parseInt(k);break;case"SKIP":f.skippedSegments&&Kt(f,C,l);var x=new At(k,f),O=x.decimalInteger("SKIPPED-SEGMENTS");if(_(O)){f.skippedSegments+=O;for(var N=O;N--;)g.push(null);v+=O}var F=x.enumeratedString("RECENTLY-REMOVED-DATERANGES");F&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(F.split("\t")));break;case"TARGETDURATION":0!==f.targetduration&&Kt(f,C,l),f.targetduration=Math.max(parseInt(k),1);break;case"VERSION":null!==f.version&&Kt(f,C,l),f.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":case"DEFINE":break;case"ENDLIST":f.live||Kt(f,C,l),f.live=!1;break;case"#":(k||M)&&b.tagList.push(M?[k,M]:[k]);break;case"DISCONTINUITY":S++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([C]);break;case"BITRATE":b.tagList.push([C,k]),T=1e3*parseInt(k),_(T)?b.bitrate=T:T=0;break;case"DATERANGE":var B=new At(k,f),U=new wt(B,f.dateRanges[B.ID],f.dateRangeTagCount);f.dateRangeTagCount++,U.isValid||f.skippedSegments?f.dateRanges[U.id]=U:j.warn('Ignoring invalid DATERANGE tag: "'+k+'"'),b.tagList.push(["EXT-X-DATERANGE",k]);break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?Kt(f,C,l):g.length>0&&Yt(f,C,l),f.startCC=S=parseInt(k);break;case"KEY":var G=$t(k,t,f);if(G.isSupported()){if("NONE"===G.method){u=void 0;break}u||(u={}),u[G.keyFormat]&&(u=n({},u)),u[G.keyFormat]=G}else j.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+k+'"');break;case"START":f.startTimeOffset=Ht(k);break;case"MAP":var $=new At(k,f);if(b.duration){var H=new ie(i,c);jt(H,$,r,u),m=H,b.initSegment=m,m.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=m.rawProgramDateTime)}else{var W=b.byteRangeEndOffset;if(W){var V=b.byteRangeStartOffset;P=W-V+"@"+V}else P=null;jt(b,$,r,u),m=b,A=!0}m.cc=S;break;case"SERVER-CONTROL":d&&Kt(f,C,l),d=new At(k),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&&Kt(f,C,l);var q=new At(k);f.partTarget=q.decimalFloatingPoint("PART-TARGET");break;case"PART":var z=f.partList;z||(z=f.partList=[]);var K=y>0?z[z.length-1]:void 0,Y=y++,X=new At(k,f),Q=new se(X,b,c,Y,K);z.push(Q),b.duration+=Q.duration;break;case"PRELOAD-HINT":var J=new At(k,f);f.preloadHint=J;break;case"RENDITION-REPORT":var Z=new At(k,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(Z);break;default:j.warn("line parsed but not handled: "+l)}}}L&&!L.relurl?(g.pop(),E-=L.duration,f.partList&&(f.fragmentHint=L)):f.partList&&(qt(b,L,p),b.cc=S,f.fragmentHint=b,u&&zt(b,u,f)),f.targetduration||(f.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));var ee=g.length,te=g[0],re=g[ee-1];if((E+=f.skippedSegments*f.targetduration)>0&&ee&&re){f.averagetargetduration=E/ee;var ne=re.sn;f.endSN="initSegment"!==ne?ne:0,f.live||(re.endList=!0),te&&void 0===f.startCC&&(f.startCC=te.cc),R>0&&(function(e,t){for(var r=e[t],i=t;i--;){var s=e[i];if(!s)return;s.programDateTime=r.programDateTime-1e3*s.duration,r=s}}(g,R),te&&p.unshift(te))}else f.endSN=0,f.startCC=0;return f.fragmentHint&&(E+=f.fragmentHint.duration),f.totalduration=E,p.length&&f.dateRangeTagCount&&te&&Ut(p,f),f.endCC=S,f},e}();function Ut(e,t){for(var r=e.length,i=e[r-1],s=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges),a=n.length;a--;){var o=t.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=i.ref;for(var h=r;h--;){var u=Gt(t,l,e,h,s);if(-1!==u){o.tagAnchor=t.fragments[u].ref;break}}}}function Gt(e,t,r,i,s){var n=r[i];if(n){var a,o=n.programDateTime;if((t>=o||0===i)&&t<=o+1e3*(((null==(a=r[i+1])?void 0:a.start)||s)-n.start)){var l=r[i].sn-e.startSN,h=e.fragments;if(h.length>r.length)for(var u=(r[i+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 $t(e,t,r){var i,s,n=new At(e,r),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,u=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&j.error("Invalid IV: "+n.IV);var d=o?Bt.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new kt(a,d,u,c,l)}function Ht(e){var t=new At(e).decimalFloatingPoint("TIME-OFFSET");return _(t)?t:null}function Wt(e,t){var r=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var i=r.filter((function(t){return Me(t,e)}));i.length&&(t[e+"Codec"]=i.map((function(e){return e.split("/")[0]})).join(","),r=r.filter((function(e){return-1===i.indexOf(e)})))})),t.unknownCodecs=r}function Vt(e,t,r){var i=t[r];i&&(e[r]=i)}function qt(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function jt(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function zt(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||i.push(e)}function Kt(e,t,r){e.playlistParsingError=new Error("#EXT-X-"+t+" must not appear more than once ("+r[0]+")")}function Yt(e,t,r){e.playlistParsingError=new Error("#EXT-X-"+t+" must appear before the first Media Segment ("+r[0]+")")}function Xt(e,t){var r=t.startPTS;if(_(r)){var i,s=0;t.sn>e.sn?(s=r-e.start,i=e):(s=e.start-r,i=t),i.duration!==s&&i.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 Qt(e,t,r,i,s,n){i-r<=0&&(j.warn("Fragment should have a positive duration",t),i=r+t.duration,n=s+t.duration);var a=r,o=i,l=t.startPTS,h=t.endPTS;if(_(l)){var u=Math.abs(l-r);_(t.deltaPTS)?t.deltaPTS=Math.max(u,t.deltaPTS):t.deltaPTS=u,a=Math.max(r,l),r=Math.min(r,l),s=Math.min(s,t.startDTS),o=Math.min(i,h),i=Math.max(i,h),n=Math.max(n,t.endDTS)}var d=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=a,t.startDTS=s,t.endPTS=i,t.minEndPTS=o,t.endDTS=n;var c,f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;var g=f-e.startSN,p=e.fragments;for(p[g]=t,c=g;c>0;c--)Xt(p[c],p[c-1]);for(c=g;c<p.length-1;c++)Xt(p[c],p[c+1]);return e.fragmentHint&&Xt(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function Jt(e,t){if(e!==t){for(var r,i=null,s=e.fragments,a=s.length-1;a>=0;a--){var o=s[a].initSegment;if(o){i=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?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(i&&!d&&u&&(d=t.fragments[h]=u),u&&d){if(r(u,d,h,o),u.url&&u.url!==d.url)return void(t.playlistParsingError=Zt("media sequence mismatch "+d.sn+":",e,t,0,d));if(u.cc!==d.cc)return void(t.playlistParsingError=Zt("discontinuity sequence mismatch ("+u.cc+"!="+d.cc+")",e,t,0,d))}}}(e,t,(function(s,n,a,o){if(!t.startCC&&n.cc!==s.cc){for(var l,h,u=s.cc-n.cc,d=a;d<o.length;d++)o[d].cc+=u;t.startCC=null!=(l=null==(h=rr(e,t.startSN-1))?void 0:h.cc)?l:o[0].cc,t.endCC=o[o.length-1].cc}_(s.startPTS)&&_(s.endPTS)&&(n.setStart(n.startPTS=s.startPTS),n.startDTS=s.startDTS,n.maxStartPTS=s.maxStartPTS,n.endPTS=s.endPTS,n.endDTS=s.endDTS,n.minEndPTS=s.minEndPTS,n.setDuration(s.endPTS-s.startPTS),n.duration&&(r=n),t.PTSKnown=t.alignedSliding=!0),s.hasStreams&&(n.elementaryStreams=s.elementaryStreams),n.loader=s.loader,s.hasStats&&(n.stats=s.stats),s.initSegment&&(n.initSegment=s.initSegment,i=s.initSegment)}));var l=t.fragments,h=t.fragmentHint?l.concat(t.fragmentHint):l;if(i&&h.forEach((function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)})),t.skippedSegments)if(t.deltaUpdateFailed=l.some((function(e){return!e})),t.deltaUpdateFailed){j.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var u=t.skippedSegments;u--;)l.shift();t.startSN=l[0].sn}else{t.endCC=l[l.length-1].cc,t.canSkipDateRanges&&(t.dateRanges=function(e,t){var r=t.dateRanges,i=t.recentlyRemovedDateranges,s=n({},e);i&&i.forEach((function(e){delete s[e]}));var a=Object.keys(s).length;return a&&Object.keys(r).forEach((function(e){var t=s[e],i=new wt(r[e].attr,t);i.isValid?(s[e]=i,t||(i.tagOrder+=a)):j.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+Je(r[e].attr)+'"')})),s}(e.dateRanges,t));var d=e.fragments.filter((function(e){return e.rawProgramDateTime}));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var c=1;c<h.length;c++)null===h[c].programDateTime&&qt(h[c],h[c-1],d);Ut(d,t)}!function(e,t,r){if(e&&t)for(var i=0,s=0,n=e.length;s<=n;s++){var a=e[s],o=t[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?r(a,o):i--}}(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),r?Qt(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):er(e,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var f=t.advancedDateTime;if(t.advanced&&f){var g=t.edge;t.driftStart||(t.driftStartTime=f,t.driftStart=g),t.driftEndTime=f,t.driftEnd=g}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Zt(e,t,r,i,s){return new Error(e+" "+s.url+"\nPlaylist starting @"+t.startSN+"\n"+t.m3u8+"\n\nPlaylist starting @"+r.startSN+"\n"+r.m3u8)}function er(e,t,r){void 0===r&&(r=!0);var i=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,n=i>=0,a=0;if(n&&i<s.length)a=s[i].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&r)a=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}!function(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,a)}function tr(e,t){void 0===t&&(t=1/0);var r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var s=1e3*i[i.length-1].duration;s<r&&(r=s)}}else r/=2;return Math.round(r)}function rr(e,t,r){if(!e)return null;var i=e.fragments[t-e.startSN];return i||((i=e.fragmentHint)&&i.sn===t?i:t<e.startSN&&r&&r.sn===t?r:null)}function ir(e,t,r){return e?sr(e.partList,t,r):null}function sr(e,t,r){if(e)for(var i=e.length;i--;){var s=e[i];if(s.index===r&&s.fragment.sn===t)return s}return null}function nr(e){e.forEach((function(e,t){var r;null==(r=e.details)||r.fragments.forEach((function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}var ar=function(e){function t(t){var r;return(r=e.call(this,"content-steering",t.logger)||this).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=t,r.registerListeners(),r}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.ERROR,this.onError,this))},r.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},r.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)}},r.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},r.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},r.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},r.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},r.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},r.onManifestLoaded=function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},r.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},r.onError=function(e,t){var r=t.errorAction;if(2===(null==r?void 0:r.action)&&1===r.flags){var i=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&&i?n=this.getPathwayForGroupId(o,h,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&i&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),r.resolved=this.pathwayId!==n),r.resolved||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+n+" levels: "+(i?i.length:i)+" priorities: "+Je(s)+" penalized: "+Je(this.penalizedPathways))}},r.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t},r.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},r.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(e){i-r[e]>3e5&&delete r[e]}));for(var s=0;s<e.length;s++){var n=e[s];if(!(n in r)){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,nr(t),this.hls.trigger(P.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}}}},r.getPathwayForGroupId=function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),s=0;s<i.length;s++)if(t===D&&i[s].hasAudioGroup(e)||t===C&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return r},r.clonePathways=function(e){var t=this,r=this.levels;if(r){var i={},s={};e.forEach((function(e){var n=e.ID,a=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some((function(e){return e.pathwayId===n}))){var l=t.getLevelsForPathway(a).map((function(e){var t=new At(e.attrs);t["PATHWAY-ID"]=n;var r=t.AUDIO&&t.AUDIO+"_clone_"+n,a=t.SUBTITLES&&t.SUBTITLES+"_clone_"+n;r&&(i[t.AUDIO]=r,t.AUDIO=r),a&&(s[t.SUBTITLES]=a,t.SUBTITLES=a);var l=lr(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new Xe({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}));r.push.apply(r,l),or(t.audioTracks,i,o,n),or(t.subtitleTracks,s,o,n)}}))}},r.loadSteeringManifest=function(e){var t,r=this,i=this.hls.config,s=i.loader;this.loader&&this.loader.destroy(),this.loader=new s(i);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||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+n)}var a={responseType:"json",url:t.href},o=i.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,i,s,n){r.log('Loaded steering manifest: "'+t+'"');var a=e.data;if(1===(null==a?void 0:a.VERSION)){r.updated=performance.now(),r.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(e){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}r.scheduleRefresh(r.uri||s.url),l&&r.clonePathways(l);var u={steeringManifest:a,url:t.toString()};r.hls.trigger(P.STEERING_MANIFEST_LOADED,u),h&&r.updatePathwayPriority(h)}else r.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(e,t,i,s){if(r.log("Error loading steering manifest: "+e.code+" "+e.text+" ("+t.url+")"),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest "+t.url+" no longer available");var n=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,n);else{var a=r.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(n=1e3*parseFloat(o))}r.log("Steering manifest "+t.url+" rate limited")}},onTimeout:function(e,t,i){r.log("Timeout loading steering manifest ("+t.url+")"),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: "+t),this.loader.load(a,h,u)},r.scheduleRefresh=function(e,t){var r=this;void 0===t&&(t=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var t,i=null==(t=r.hls)?void 0:t.media;!i||i.ended?r.scheduleRefresh(e,1e3*r.timeToLoad):r.loadSteeringManifest(e)}),t)},i(t,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}}])}(F);function or(e,t,r,i){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 At(a.attrs),a.url=a.attrs.URI=lr(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=i,a}));e.push.apply(e,a)}))}function lr(e,t,r,i){var s,n=i.HOST,a=i.PARAMS,o=i[r];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 hr=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(P.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(P.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListeners=function(){this.hls.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(P.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 r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var s=i-this.lastTime,n=r-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*n/s,l=this.hls;if(l.trigger(P.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:r}),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(P.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,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}(),ur=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,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,s=0;s<e.length;s++){var n=e[s];r.set(n,i),i+=n.length}return r}(t,r),this.reset(),e):new Uint8Array(0)},t.reset=function(){this.chunks.length=0,this.dataLength=0},e}();function dr(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 cr(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 fr(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,(r|=(127&e[t+2])<<7)|127&e[t+3]}function gr(e,t){for(var r=t,i=0;cr(e,t);)i+=10,i+=fr(e,t+6),dr(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(r,r+i)}function pr(e,t){return 255===e[t]&&240==(246&e[t+1])}function mr(e,t){return 1&e[t+1]?7:9}function vr(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function yr(e,t){return t+1<e.length&&pr(e,t)}function Er(e,t){if(yr(e,t)){var r=mr(e,t);if(t+r>=e.length)return!1;var i=vr(e,t);if(i<=r)return!1;var s=t+i;return s===e.length||yr(e,s)}return!1}function Sr(e,t,r,i,s){if(!e.samplerate){var a=function(e,t,r,i){var s=t[r+2],n=s>>2&15;if(!(n>12)){var a=1+(s>>6&3),o=t[r+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 j.log("manifest codec:"+i+", 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:i}}var c=new Error("invalid ADTS sampling index:"+n);e.emit(P.ERROR,P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}(t,r,i,s);if(!a)return;n(e,a)}}function Tr(e){return 9216e4/e}function _r(e,t,r,i,s){var n,a=i+s*Tr(e.samplerate),o=function(e,t){var r=mr(e,t);if(t+r<=e.length){var i=vr(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,h=o.headerLength,u=h+l,d=Math.max(0,r+u-t.length);d?(n=new Uint8Array(u-h)).set(t.subarray(r+h,t.length),0):n=t.subarray(r+h,r+u);var c={unit:n,pts:a};return d||e.samples.push(c),{sample:c,length:u,missing:d}}var f=t.length-r;return(n=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:n,pts:a},length:f,missing:-1}}function Lr(e,t){return cr(e,t)&&fr(e,t+6)+10<=e.length-t}function br(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=1/0),function(e,t,r,i){var s=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.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 i(s,u,Math.floor(Math.min(u+Math.max(r,0),l))-u)}(e,t,r,Uint8Array)}function Rr(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Y(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=Y(e.data.subarray(t),!0);t+=r.length+1;var i=Y(e.data.subarray(t));return{key:e.type,info:r,data:i}}var s=Y(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 r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=Y(br(e.data,1,r)),s=e.data[2+r],n=e.data.subarray(3+r).indexOf(0);if(-1!==n){var a,o=Y(br(e.data,3+r,n));return a="--\x3e"===i?Y(br(e.data,4+r+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+r+n)),t.mimeType=i,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,r=Y(e.data.subarray(t),!0);t+=r.length+1;var i=Y(e.data.subarray(t));return{key:e.type,info:r,data:i}}var s=Y(e.data.subarray(1));return{key:e.type,info:"",data:s}}}(e)}function Ar(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=fr(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}var Pr=10,wr=10;function Ir(e){for(var t=0,r=[];cr(e,t);){var i=fr(e,t+6);e[t+5]>>6&1&&(t+=Pr);for(var s=(t+=Pr)+i;t+wr<s;){var n=Ar(e.subarray(t)),a=Rr(n);a&&r.push(a),t+=n.size+Pr}dr(e,t)&&(t+=Pr)}return r}function Dr(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),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function kr(e){for(var t=Ir(e),r=0;r<t.length;r++){var i=t[r];if(Dr(i))return Cr(i)}}var Mr=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 Or=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,r,i){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,r){},t.demux=function(e,t){this.cachedData&&(e=be(this.cachedData,e),this.cachedData=null);var r,i=gr(e,0),s=i?i.length:0,n=this._audioTrack,a=this._id3Track,o=i?kr(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&_(o))&&(this.basePTS=Nr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Mr.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,r=s+=h.length):s=l}else Lr(e,s)?(i=gr(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Mr.audioId3,duration:Number.POSITIVE_INFINITY}),r=s+=i.length):s++;if(s===l&&r!==l){var u=e.slice(r);this.cachedData?this.cachedData=be(this.cachedData,u):this.cachedData=u}}return{audioTrack:n,videoTrack:xr(),id3Track:a,textTrack:xr()}},t.demuxSampleAes=function(e,t,r){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,r){return _(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},Fr=null,Br=[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],Ur=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Gr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],$r=[0,1,1,4];function Hr(e,t,r,i,s){if(!(r+24>t.length)){var n=Wr(t,r);if(n&&r+n.frameLength<=t.length){var a=i+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(r,r+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 Wr(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==n){var a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Br[14*(3===r?3-i:3===i?3:4)+s-1],h=Ur[3*(3===r?0:2===r?1:2)+n],u=3===o?1:2,d=Gr[r][i],c=$r[i],f=8*d*c,g=Math.floor(d*l/h+a)*c;if(null===Fr){var p=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Fr=p?parseInt(p[1]):0}return!!Fr&&Fr<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:u,frameLength:g,samplesPerFrame:f}}}function Vr(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function qr(e,t){return t+1<e.length&&Vr(e,t)}function jr(e,t){if(t+1<e.length&&Vr(e,t)){var r=Wr(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var s=t+i;return s===e.length||qr(e,s)}return!1}var zr=function(e){function t(t,r){var i;return(i=e.call(this)||this).observer=void 0,i.config=void 0,i.observer=t,i.config=r,i}o(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,s){e.prototype.resetInitSegment.call(this,t,r,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e,t){if(!e)return!1;var r=gr(e,0),i=(null==r?void 0:r.length)||0;if(jr(e,i))return!1;for(var s=e.length;i<s;i++)if(Er(e,i))return t.log("ADTS sync word found !"),!0;return!1},r.canParse=function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&pr(e,t)&&vr(e,t)<=e.length-t}(e,t)},r.appendFrame=function(e,t,r){Sr(e,this.observer,t,r,e.manifestCodec);var i=_r(e,t,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i},t}(Or),Kr=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,s){e.prototype.resetInitSegment.call(this,t,r,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=gr(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==kr(t)&&function(e,t){var r=0,i=5;t+=i;for(var s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);i>0;){a[0]=e[t];var o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,r=r?r<<o|s[0]:s[0],t+=1,i-=o}return r}(e,r)<=16)return!1;for(var i=e.length;r<i;r++)if(jr(e,r))return j.log("MPEG Audio sync word found !"),!0;return!1},r.canParse=function(e,t){return function(e,t){return Vr(e,t)&&4<=e.length-t}(e,t)},r.appendFrame=function(e,t,r){if(null!==this.basePTS)return Hr(e,t,r,this.basePTS,this.frameIndex)},t}(Or),Yr=function(){function e(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}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}(),Xr=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),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},t.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],s=r[1],n=r[2],a=r[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 m=g^g<<1^g<<2^g<<3^g<<4;m=m>>>8^255&m^99,e[f]=m,t[m]=f;var v=c[f],y=c[v],E=c[y],S=257*c[m]^16843008*m;i[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*v^16843008*f,l[m]=S<<24|S>>>8,h[m]=S<<16|S>>>16,u[m]=S<<8|S>>>24,d[m]=S,f?(f=v^c[c[c[E^v]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){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],m=g[1],v=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]]^m[c[l>>>16&255]]^v[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,r){for(var i,s,n,a,o,l,h,u,d,c,f,g,p,m,v=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,S=this.invSubMix,T=S[0],_=S[1],L=S[2],b=S[3],R=this.uint8ArrayToUint32Array_(r),A=R[0],P=R[1],w=R[2],I=R[3],D=new Int32Array(e),C=new Int32Array(D.length),k=this.networkToHostOrderSwap;t<D.length;){for(d=k(D[t]),c=k(D[t+1]),f=k(D[t+2]),g=k(D[t+3]),o=d^y[0],l=g^y[1],h=f^y[2],u=c^y[3],p=4,m=1;m<v;m++)i=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=i,l=s,h=n,u=a,p+=4;i=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],C[t]=k(i^A),C[t+1]=k(a^P),C[t+2]=k(n^w),C[t+3]=k(s^I),A=d,P=c,w=f,I=g,t+=4}return C.buffer},e}(),Qr=function(){function e(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}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}(),Jr=function(){function e(e,t){var r=(void 0===t?{}:t).removePKCS7Padding,i=void 0===r||r;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=i,i)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 r,i,s,n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(s=(i=(r=n).byteLength)&&new DataView(r.buffer).getUint8(i-1))?r.slice(0,i-s):r:n},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,r,i){var s=this;return this.useSoftware?new Promise((function(n,a){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);s.softwareDecrypt(o,t,r,i);var l=s.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)},t.softwareDecrypt=function(e,t,r,i){var s=this.currentIV,n=this.currentResult,a=this.remainderData;if(0!==i||16!==t.byteLength)return j.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=be(a,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;s&&(r=s);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Xr),l.expandKey(t);var h=n;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,h||null},t.webCryptoDecrypt=function(e,t,r,i){var s=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new Qr(this.subtle,t,i)}return this.fastAesKey.expandKey().then((function(t){return s.subtle?(s.logOnce("WebCrypto AES decrypt"),new Yr(s.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(n){return j.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+n.name+": "+n.message),s.onWebCryptoError(e,t,r,i)}))},t.onWebCryptoError=function(e,t,r,i){var s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);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,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t},t.logOnce=function(e){this.logEnabled&&(j.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),Zr=/\/emsg[-/]ID3/i,ei=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,r,i){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=ve(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,m=f.codec;n.id=g,n.timescale=p,n.codec=m}a.id=le.text,s.sampleDuration=0,s.duration=n.duration=i}},t.resetContiguity=function(){this.remainderData=null},e.probe=function(e){return function(e){for(var t=e.byteLength,r=0;r<t;){var i=de(e,r);if(i>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=be(this.remainderData,e));var n=function(e){var t={valid:null,remainder:null},r=pe(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(r);this.remainderData=n.remainder,i.samples=n.valid||new Uint8Array}else i.samples=r;var a=this.extractID3Track(i,t);return s.samples=Re(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=Re(e,t),{videoTrack:t,audioTrack:xr(),id3Track:i,textTrack:xr()}},t.extractID3Track=function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var s=pe(e.samples,["emsg"]);s&&s.forEach((function(e){var s=function(e){var t=e[0],r="",i="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==he(e.subarray(h,h+1));)r+=he(e.subarray(h,h+1)),h+=1;for(r+=he(e.subarray(h,h+1)),h+=1;"\0"!==he(e.subarray(h,h+1));)i+=he(e.subarray(h,h+1)),h+=1;i+=he(e.subarray(h,h+1)),h+=1,s=de(e,12),n=de(e,16),o=de(e,20),l=de(e,24),h=28}else if(1===t){s=de(e,h+=4);var u=de(e,h+=4),d=de(e,h+=4);for(h+=4,a=Math.pow(2,32)*u+d,L(a)||(a=Number.MAX_SAFE_INTEGER,j.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=de(e,h),l=de(e,h+=4),h+=4;"\0"!==he(e.subarray(h,h+1));)r+=he(e.subarray(h,h+1)),h+=1;for(r+=he(e.subarray(h,h+1)),h+=1;"\0"!==he(e.subarray(h,h+1));)i+=he(e.subarray(h,h+1)),h+=1;i+=he(e.subarray(h,h+1)),h+=1}return{schemeIdUri:r,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Zr.test(s.schemeIdUri)){var n=ti(s,t),a=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=s.payload;i.samples.push({data:o,len:o.byteLength,dts:n,pts:n,type:Mr.emsg,duration:a})}else if(r.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=ti(s,t);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:l,pts:l,type:Mr.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return i},t.demuxSampleAes=function(e,t,r){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 ti(e,t){return _(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var ri=function(){function e(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Jr(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,r){var i=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),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}))}},t.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,r),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,s=32;s<e.length-16;s+=160,i+=16)r.set(e.subarray(s,s+16),i);return r},t.getAvcDecryptedUnit=function(e,t){for(var r=new Uint8Array(t),i=0,s=32;s<e.length-16;s+=160,i+=16)e.set(r.subarray(i,i+16),s);return e},t.decryptAvcSample=function(e,t,r,i,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,r+1,i)}))},t.decryptAvcSamples=function(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var s=e[t].units;!(r>=s.length);r++){var n=s[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,r,i,n),this.decrypter.isSync())))return}}},e}(),ii=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}},t.getLastNalUnit=function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var s=i.units;r=s[s.length-1]}return r},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var s=r[i-1];e.pts=s.pts,e.dts=s.dts}t.samples.push(e)}},t.parseNALu=function(e,t,r){var i,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(i=t[h++],a)if(1!==a)if(i)if(1===i){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=be(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=i?0:2;else a=i?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=be(p.data,t))}return e.naluState=a,l},e}(),si=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,r=e.byteLength-t,i=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");i.set(e.subarray(r,r+s)),this.word=new DataView(i.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),r=this.word>>>32-t;if(e>32&&j.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?r<<t|this.readBits(t):r},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}(),ni=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var r=t.prototype;return r.parsePES=function(e,t,r,i){var s,n=this,a=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),a.forEach((function(i){var a,h;switch(i.type){case 1:var u=!1;s=!0;var d,c=i.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,r.pts,r.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,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:s=!0,we(i.data,1,r.pts,t.samples);break;case 7:var g,p;s=!0,l=!0;var m=i.data,v=n.readSPS(m);if(!e.sps||e.width!==v.width||e.height!==v.height||(null==(g=e.pixelRatio)?void 0:g[0])!==v.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[m];for(var y=m.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=[i.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,r.pts,r.dts));break;case 12:s=!0;break;default:s=!1}o&&s&&o.units.push(i)})),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},r.getNALuType=function(e,t){return 31&e[t]},r.readSliceType=function(e){var t=new si(e);return t.readUByte(),t.readUEG(),t.readUEG()},r.skipScalingList=function(e,t){for(var r=8,i=8,s=0;s<e;s++)0!==i&&(i=(r+t.readEG()+256)%256),r=0===i?r:i},r.readSPS=function(e){var t,r,i,s=new si(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),m=this.skipScalingList.bind(this);h();var v=h();if(u(5),f(3),h(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){var y=d();if(3===y&&f(1),p(),p(),f(1),c())for(r=3!==y?8:12,i=0;i<r;i++)c()&&m(i<6?16:64,s)}p();var E=d();if(0===E)d();else if(1===E)for(f(1),g(),g(),t=d(),i=0;i<t;i++)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}(ii),ai=188,oi=function(){function e(e,t,r,i){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=r,this.logger=i,this.videoParser=null}e.probe=function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset "+i),-1!==i},e.syncOffset=function(e){for(var t=e.length,r=Math.min(940,t-ai)+1,i=0;i<r;){for(var s=!1,n=-1,a=0,o=i;o<t;o+=ai){if(71!==e[o]||t-o!==ai&&71!==e[o+ai]){if(a)return-1;break}if(a++,-1===n&&0!==(n=o)&&(r=Math.min(n+18612,e.length-ai)+1),s||(s=0===li(e,o)),s&&a>1&&(0===n&&a>2||o+ai>r))return n}i++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:le[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,r,i,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.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,r,i,s){var n;void 0===i&&(i=!1),void 0===s&&(s=!1),i||(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,m=null,v=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=be(this.remainderData,t)).length,this.remainderData=null),E<ai&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var S=Math.max(0,e.syncOffset(t));(E-=(E-S)%ai)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var T=0,_=S;_<E;_+=ai)if(71===t[_]){var L=!!(64&t[_+1]),b=li(t,_),R=void 0;if((48&t[_+3])>>4>1){if((R=_+5+t[_+4])===_+ai)continue}else R=_+4;switch(b){case u:L&&(d&&(n=fi(d,this.logger))&&(null===this.videoParser&&"avc"===a.segmentCodec&&(this.videoParser=new ni),null!==this.videoParser&&this.videoParser.parsePES(a,h,n,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(R,_+ai)),d.size+=_+ai-R);break;case c:if(L){if(g&&(n=fi(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n)}g={data:[],size:0}}g&&(g.data.push(t.subarray(R,_+ai)),g.size+=_+ai-R);break;case f:L&&(p&&(n=fi(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(t.subarray(R,_+ai)),p.size+=_+ai-R);break;case 0:L&&(R+=t[R]+1),y=this._pmtId=hi(t,R);break;case y:L&&(R+=t[R]+1);var A=ui(t,R,this.typeSupported,i,this.observer,this.logger);(u=A.videoPid)>0&&(a.pid=u,a.segmentCodec=A.segmentVideoCodec),(c=A.audioPid)>0&&(o.pid=c,o.segmentCodec=A.segmentAudioCodec),(f=A.id3Pid)>0&&(l.pid=f),null===m||v||(this.logger.warn("MPEG-TS PMT found at "+_+" after unknown PID '"+m+"'. Backtracking to sync byte @"+S+" to parse all TS packets."),m=null,_=S-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=b}}else T++;T>0&&di(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 P={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(P),P},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,r=e.audioTrack,i=e.videoTrack,s=e.id3Track,n=e.textTrack,a=i.pesData,o=r.pesData,l=s.pesData;if(a&&(t=fi(a,this.logger))?(null===this.videoParser&&"avc"===i.segmentCodec&&(this.videoParser=new ni),null!==this.videoParser&&(this.videoParser.parsePES(i,n,t,!0),i.pesData=null)):i.pesData=a,o&&(t=fi(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t)}r.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=fi(l,this.logger))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=l},t.demuxSampleAes=function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new ri(this.observer,this.config,t);return this.decrypt(i,s)},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,s=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(function(){s.samples?t.decryptAvcSamples(s.samples,0,0,(function(){r(e)})):r(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(function(){r(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 r,i,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=be(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(r=n,i=o.length;r<i-1&&!yr(o,r);r++);if(r!==n){var d,c=r<i-1;if(d=c?"AAC PES did not start with ADTS header,offset:"+r:"No ADTS header found in AAC PES",di(this.observer,new Error(d),c,this.logger),!c)return}if(Sr(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)s=t.pts;else{if(!a)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=Tr(e.samplerate);s=a.sample.pts+f}for(var g,p=0;r<i;){if(r+=(g=_r(e,o,r,s,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;r<i-1&&!yr(o,r);r++);}},t.parseMPEGPES=function(e,t){var r=t.data,i=r.length,s=0,n=0,a=t.pts;if(void 0!==a)for(;n<i;)if(qr(r,n)){var o=Hr(e,r,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){},t.parseID3PES=function(e,t){if(void 0!==t.pts){var r=n({},t,{type:this._videoTrack?Mr.emsg:Mr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function li(e,t){return((31&e[t+1])<<8)+e[t+2]}function hi(e,t){return(31&e[t+10])<<8|e[t+11]}function ui(e,t,r,i,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=li(e,t),h=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){ci("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(!i){ci("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=l);break;case 3:case 4:r.mpeg||r.mp3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){ci("AC-3",n);break}case 129:n.warn("AC-3 in M2TS support not included in build");break;case 6:if(-1===a.audioPid&&h>0)for(var u=t+5,d=h;d>2;){106===e[u]&&n.warn("AC-3 in M2TS support not included in build");var c=e[u+1]+2;u+=c,d-=c}break;case 194:case 135:return di(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:return di(s,new Error("Unsupported HEVC in M2TS found"),void 0,n),a}t+=h+5}return a}function di(e,t,r,i){i.warn("parsing error: "+t.message),e.emit(P.ERROR,P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function ci(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function fi(e,t){var r,i,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]=be(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var h=r[7];192&h&&(n=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&h?n-(a=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[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=r[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=(r=l[c]).byteLength;if(u){if(u>g){u-=g;continue}r=r.subarray(u),g-=u,u=0}d.set(r,o),o+=g}return i&&(i-=s+3),{data:d,pts:n,dts:a,len:i}}return null}var gi=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}(),pi=Math.pow(2,32)-1,mi=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 r=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]),i=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:r,audio:i};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,r=arguments.length,i=new Array(r>1?r-1:0),s=1;s<r;s++)i[s-1]=arguments[s];for(var n=i.length,a=n;n--;)t+=i[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(i[n],t),t+=i[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,r){r*=t;var i=Math.floor(r/(pi+1)),s=Math.floor(r%(pi+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,i>>24,i>>16&255,i>>8&255,255&i,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,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(pi+1)),s=Math.floor(r%(pi+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,i>>24,i>>16&255,i>>8&255,255&i,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 r,i,s=t.samples||[],n=new Uint8Array(4+s.length);for(r=0;r<s.length;r++)i=s[r].flags,n[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.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 r,i,s,n=[],a=[];for(r=0;r<t.sps.length;r++)s=(i=t.sps[r]).byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)s=(i=t.pps[r]).byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(i));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 r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("mp3"===r&&"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"===r)return e.box(e.types.stsd,e.STSD,e.avc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+r+"/"+t.codec+")")},e.tkhd=function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,n=t.height||0,a=Math.floor(i/(pi+1)),o=Math.floor(i%(pi+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,r>>24&255,r>>16&255,r>>8&255,255&r,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,r){var i=e.sdtp(t),s=t.id,n=Math.floor(r/(pi+1)),a=Math.floor(r%(pi+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,i.length+16+20+8+16+8+8),i)},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 r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,s,n,a,o,l,h=t.samples||[],u=h.length,d=12+16*u,c=new Uint8Array(d);for(r+=8+d,c.set(["video"===t.type?1:0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<u;i++)n=(s=h[i]).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*i);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var r=e.moov(t);return be(e.FTYP,r)},e.hvc1=function(e){return new Uint8Array},e}();function vi(e,t){return function(e,t,r,i){var s=1e3*e*(1/9e4);return Math.round(s)}(e)}mi.types=void 0,mi.HDLR_TYPES=void 0,mi.STTS=void 0,mi.STSC=void 0,mi.STCO=void 0,mi.STSZ=void 0,mi.VMHD=void 0,mi.SMHD=void 0,mi.STSD=void 0,mi.FTYP=void 0,mi.DINF=void 0;var yi=null,Ei=null;function Si(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Ti=function(){function e(e,t,r,i){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.logger=i,this.ISGenerated=!1,null===yi){var s=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);yi=s?parseInt(s[1]):0}if(null===Ei){var n=navigator.userAgent.match(/Safari\/(\d+)/i);Ei=n?parseInt(n[1]):0}}var t=e.prototype;return t.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},t.resetTimeStamp=function(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e},t.resetNextTimestamp=function(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},t.resetInitSegment=function(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},t.getVideoStartPts=function(e){var t=!1,r=e[0].pts,i=e.reduce((function(e,i){var s=i.pts,n=s-e;return n<-4294967296&&(t=!0,n=(s=_i(s,r))-e),n>0?e:s}),r);return t&&this.logger.debug("PTS rollover detected"),i},t.remux=function(e,t,r,i,s,n,a,o){var l,h,u,d,c,f,g=s,p=s,m=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!m||E)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var T,_,L,b,R=this.videoTrackConfig;(R&&(t.width!==R.width||t.height!==R.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(_=R.pixelRatio)?void 0:_[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(b=R.pixelRatio)?void 0:b[1]))||!R&&S||null===this.nextAudioPts&&E)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,s,n));var A,P=this.isVideoContiguous,w=-1;if(S&&(w=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,w>0){this.logger.warn("[mp4-remuxer]: Dropped "+w+" out of "+y+" video samples due to a missing keyframe");var I=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,A=p+=(t.samples[0].pts-I)/t.inputTimeScale}else-1===w&&(this.logger.warn("[mp4-remuxer]: No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&S){var D=this.getVideoStartPts(t.samples),C=(_i(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,C),p+=Math.max(0,-C)}if(E){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||S||o===M?p:void 0),S){var k=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,p,P,k)}}else S&&(l=this.remuxVideo(t,p,P,0));l&&(l.firstKeyFrame=w,l.independent=-1!==w,l.firstKeyFramePTS=A)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=Li(r,s,this._initPTS,this._initDTS)),i.samples.length&&(d=bi(i,s,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:c}},t.generateIS=function(e,t,r,i){var s,n,a,o=e.samples,l=t.samples,h=this.typeSupported,u={},d=this._initPTS,c=!d||i,f="audio/mp4";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):mi.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(a=e.inputTimeScale,d&&a===d.timescale?c=!1:s=n=o[0].pts-Math.round(a*r))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:mi.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(a=t.inputTimeScale,d&&a===d.timescale)c=!1;else{var g=this.getVideoStartPts(l),p=Math.round(a*r);n=Math.min(n,_i(l[0].dts,g)-p),s=Math.min(s,g-p)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:s,timescale:a},this._initDTS={baseTime:n,timescale:a}):s=a=void 0,{tracks:u,initPTS:s,timescale:a}},t.remuxVideo=function(e,t,r,i){var s,a,o=e.inputTimeScale,l=e.samples,h=[],u=l.length,d=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!r||null===c){var y=t*o,E=l[0].pts-_i(l[0].dts,l[0].pts);yi&&null!==c&&Math.abs(y-E-c)<15e3?r=!0:c=y-E}for(var S=d.baseTime*o/d.timescale,T=0;T<u;T++){var _=l[T];_.pts=_i(_.pts-S,c),_.dts=_i(_.dts-S,c),_.dts<l[T>0?T-1:T].dts&&(v=!0)}v&&l.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),s=l[0].dts;var L=l[l.length-1].dts-s,b=L?Math.round(L/(u-1)):g||e.inputTimeScale/30;if(r){var w=s-c,I=w>b,D=w<-1;if((I||D)&&(I?this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+vi(w)+" ms ("+w+"dts) hole between fragments detected at "+t.toFixed(3)):this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+vi(-w)+" ms ("+w+"dts) overlapping between fragments detected at "+t.toFixed(3)),!D||c>=l[0].pts||yi)){s=c;var C=l[0].pts-w;if(I)l[0].dts=s,l[0].pts=C;else for(var k=!0,M=0;M<l.length&&!(l[M].dts>C&&k);M++){var x=l[M].pts;if(l[M].dts-=w,l[M].pts-=w,M<l.length-1){var O=l[M+1].pts;k=O<=l[M].pts==O<=x}}this.logger.log("Video: Initial PTS/DTS adjusted: "+vi(C)+"/"+vi(s)+", delta: "+vi(w)+" ms")}}for(var N=0,F=0,B=s=Math.max(0,s),U=0;U<u;U++){for(var G=l[U],$=G.units,H=$.length,W=0,V=0;V<H;V++)W+=$[V].data.length;F+=W,N+=H,G.length=W,G.dts<B?(G.dts=B,B+=b/4|0||1):B=G.dts,p=Math.min(G.pts,p),m=Math.max(G.pts,m)}a=l[u-1].dts;var q,j=F+4*N+8;try{q=new Uint8Array(j)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:R.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:j,reason:"fail allocating video mdat "+j})}var z=new DataView(q.buffer);z.setUint32(0,j),q.set(mi.types.mdat,4);for(var K=!1,Y=Number.POSITIVE_INFINITY,X=Number.POSITIVE_INFINITY,Q=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY,Z=0;Z<u;Z++){for(var ee=l[Z],te=ee.units,re=0,ie=0,se=te.length;ie<se;ie++){var ne=te[ie],ae=ne.data,oe=ne.data.byteLength;z.setUint32(f,oe),f+=4,q.set(ae,f),f+=oe,re+=4+oe}var le=void 0;if(Z<u-1)g=l[Z+1].dts-ee.dts,le=l[Z+1].pts-ee.pts;else{var he=this.config,ue=Z>0?ee.dts-l[Z-1].dts:b;if(le=Z>0?ee.pts-l[Z-1].pts:b,he.stretchShortVideoTrack&&null!==this.nextAudioPts){var de=Math.floor(he.maxBufferHole*o),ce=(i?p+i*o:this.nextAudioPts)-ee.pts;ce>de?((g=ce-ue)<0?g=ue:K=!0,this.logger.log("[mp4-remuxer]: It is approximately "+ce/90+" ms to the next segment; using duration "+g/90+" ms for the last video frame.")):g=ue}else g=ue}var fe=Math.round(ee.pts-ee.dts);Y=Math.min(Y,g),Q=Math.max(Q,g),X=Math.min(X,le),J=Math.max(J,le),h.push(Si(ee.key,g,re,fe))}if(h.length)if(yi){if(yi<70){var ge=h[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(Ei&&J-X<Q-Y&&b/Q<.025&&0===h[0].cts){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var pe=s,me=0,ve=h.length;me<ve;me++){var ye=pe+h[me].duration,Ee=pe+h[me].cts;if(me<ve-1){var Se=ye+h[me+1].cts;h[me].duration=Se-Ee}else h[me].duration=me?h[me-1].duration:b;h[me].cts=0,pe=ye}}g=K||!g?b:g,this.nextAvcDts=c=a+g,this.videoSampleDuration=g,this.isVideoContiguous=!0;var Te={data1:mi.moof(e.sequenceNumber++,s,n(e,{samples:h})),data2:q,startPTS:p/o,endPTS:(m+g)/o,startDTS:s/o,endDTS:c/o,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Te},t.getSamplesPerFrame=function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}},t.remuxAudio=function(e,t,r,i,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,m=this.nextAudioPts||-1,v=t*a,y=u.baseTime*a/u.timescale;if(this.isAudioContiguous=r=r||g.length&&m>0&&(i&&Math.abs(v-m)<9e3||Math.abs(_i(g[0].pts-y,v)-m)<20*h),g.forEach((function(e){e.pts=_i(e.pts-y,v)})),!r||m<0){if(g=g.filter((function(e){return e.pts>=0})),!g.length)return;m=0===s?0:i&&!f?Math.max(0,v):g[0].pts}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,S=0,T=m;S<g.length;S++){var _=g[S],L=_.pts,b=L-T,w=Math.abs(1e3*b/a);if(b<=-E*h&&f)0===S&&(this.logger.warn("Audio frame @ "+(L/a).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*b/a)+" ms."),this.nextAudioPts=m=T=L);else if(b>=E*h&&w<1e4&&f){var I=Math.round(b/h);(T=L-I*h)<0&&(I--,T+=h),0===S&&(this.nextAudioPts=m=T),this.logger.warn("[mp4-remuxer]: Injecting "+I+" audio frame @ "+(T/a).toFixed(3)+"s due to "+Math.round(1e3*b/a)+" ms gap.");for(var D=0;D<I;D++){var C=Math.max(T,0),k=gi.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);k||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),k=_.unit.subarray()),g.splice(S,0,{unit:k,pts:C}),T+=h,S++}}_.pts=T,T+=h}for(var M,x=null,O=null,N=0,F=g.length;F--;)N+=g[F].unit.byteLength;for(var B=0,U=g.length;B<U;B++){var G=g[B],$=G.unit,H=G.pts;if(null!==O)c[B-1].duration=Math.round((H-O)/o);else{if(r&&"aac"===e.segmentCodec&&(H=m),x=H,!(N>0))return;N+=p;try{M=new Uint8Array(N)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:R.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:N,reason:"fail allocating audio mdat "+N})}d||(new DataView(M.buffer).setUint32(0,N),M.set(mi.types.mdat,4))}M.set($,p);var W=$.byteLength;p+=W,c.push(Si(!0,l,W,0)),O=H}var V=c.length;if(V){var q=c[c.length-1];this.nextAudioPts=m=O+o*q.duration;var j=d?new Uint8Array(0):mi.moof(e.sequenceNumber++,x/o,n({},e,{samples:c}));e.samples=[];var z=x/a,K=m/a,Y={data1:j,data2:M,startPTS:z,endPTS:K,startDTS:z,endDTS:K,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,Y}},e}();function _i(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function Li(e,t,r,i){var s=e.samples.length;if(s){for(var n=e.inputTimeScale,a=0;a<s;a++){var o=e.samples[a];o.pts=_i(o.pts-r.baseTime*n/r.timescale,t*n)/n,o.dts=_i(o.dts-i.baseTime*n/i.timescale,t*n)/n}var l=e.samples;return e.samples=[],{samples:l}}}function bi(e,t,r){var i=e.samples.length;if(i){for(var s=e.inputTimeScale,n=0;n<i;n++){var a=e.samples[n];a.pts=_i(a.pts-r.baseTime*s/r.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 Ri,Ai=function(){function e(e,t,r,i){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.logger=i}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(e){this.initPTS=e,this.lastEndTime=null},t.resetNextTimestamp=function(){this.lastEndTime=null},t.resetInitSegment=function(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(function(e,t){if(!e||!t)return e;var r=t.keyId;return r&&t.isCommonEncryption&&pe(e,["moov","trak"]).forEach((function(e){var t=pe(e,["mdia","minf","stbl","stsd"])[0].subarray(8),i=pe(t,["enca"]),s=i.length>0;s||(i=pe(t,["encv"])),i.forEach((function(e){pe(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=function(e){var t=pe(e,["schm"])[0];if(t){var r=he(t.subarray(4,8));if("cbcs"===r||"cenc"===r)return pe(e,["schi","tenc"])[0]}return null}(e);if(t){var i=t.subarray(8,24);i.some((function(e){return 0!==e}))||(j.log("[eme] Patching keyId in 'enc"+(s?"a":"v")+">sinf>>tenc' box: "+X(i)+" -> "+X(r)),t.set(r,8))}}))}))})),e}(e,i)),this.emitInitSegment=!0},t.generateInitSegment=function(e){var t=this.audioCodec,r=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=ve(e);i.audio&&(t=Pi(i.audio,J)),i.video&&(r=Pi(i.video,Z));var s={};i.audio&&i.video?s.audiovideo={container:"video/mp4",codec:t+","+r,supplemental:i.video.supplemental,initSegment:e,id:"main"}:i.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?s.video={container:"video/mp4",codec:r,supplemental:i.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s},t.remux=function(e,t,r,i,s,n){var a,o,l=this.initPTS,h=this.lastEndTime,u={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};_(h)||(h=this.lastEndTime=s||0);var d=t.samples;if(null==d||!d.length)return u;var c={initPTS:void 0,timescale:1},f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=function(e,t){for(var r=0,i=0,s=0,n=pe(e,["moof","traf"]),a=0;a<n.length;a++){var o=n[a],l=pe(o,["tfhd"])[0],h=t[de(l,4)];if(h){var u=h.default,d=de(l,0)|(null==u?void 0:u.flags),c=null==u?void 0:u.duration;8&d&&(c=de(l,2&d?12:8));for(var f=h.timescale||9e4,g=pe(o,["trun"]),p=0;p<g.length;p++)!(r=Le(g[p]))&&c&&(r=c*de(g[p],4)),h.type===Z?i+=r/f:h.type===J&&(s+=r/f)}}if(0===i&&0===s){for(var m=1/0,v=0,y=0,E=pe(e,["sidx"]),S=0;S<E.length;S++){var T=me(E[S]);if(null!=T&&T.references){m=Math.min(m,T.earliestPresentationTime/T.timescale);var L=T.references.reduce((function(e,t){return e+t.info.duration||0}),0);y=(v=Math.max(v,L+T.earliestPresentationTime/T.timescale))-m}}if(y&&_(y))return y}return i||s}(d,f),p=function(e,t){return pe(t,["moof","traf"]).reduce((function(t,r){var i=pe(r,["tfdt"])[0],s=i[0],n=pe(r,["tfhd"]).reduce((function(t,r){var n=de(r,4),a=e[n];if(a){var o=de(i,4);if(1===s){if(o===ae)return j.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;o*=ae+1,o+=de(i,8)}var l=o/(a.timescale||9e4);if(_(l)&&(null===t||l<t))return l}return t}),null);return null!==n&&_(n)&&(null===t||n<t)?n:t}),null)}(f,d),m=null===p?s:p;!n&&l||!function(e,t,r,i){if(null===e)return!0;var s=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-r)>s}(l,m,s,g)&&c.timescale===l.timescale||(c.initPTS=m-s,l&&1===l.timescale&&this.logger.warn("Adjusting initPTS @"+s+" from "+l.baseTime/l.timescale+" to "+c.initPTS),this.initPTS=l={baseTime:c.initPTS,timescale:1});var v=e?m-l.baseTime/l.timescale:h,y=v+g;!function(e,t,r){pe(t,["moof","traf"]).forEach((function(t){pe(t,["tfhd"]).forEach((function(i){var s=de(i,4),n=e[s];if(n){var a=n.timescale||9e4;pe(t,["tfdt"]).forEach((function(e){var t=e[0],i=r*a;if(i){var s=de(e,4);if(0===t)s-=i,ge(e,4,s=Math.max(s,0));else{s*=Math.pow(2,32),s+=de(e,8),s-=i,s=Math.max(s,0);var n=Math.floor(s/(ae+1)),o=Math.floor(s%(ae+1));ge(e,4,n),ge(e,8,o)}}}))}}))}))}(f,d,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var E=!!f.audio,S=!!f.video,T="";E&&(T+="audio"),S&&(T+="video");var L={data1:d,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:T,hasAudio:E,hasVideo:S,nb:1,dropped:0};return u.audio="audio"===L.type?L:void 0,u.video="audio"!==L.type?L:void 0,u.initSegment=c,u.id3=Li(r,s,l,l),i.samples.length&&(u.text=bi(i,s,l)),u},e}();function Pi(e,t){var r=null==e?void 0:e.codec;return r&&r.length>4?r:t===J?"ec-3"===r||"ac-3"===r||"alac"===r?r:"fLaC"===r||"Opus"===r?$e(r,!1):(j.warn('Unhandled audio codec "'+r+'" in mp4 MAP'),r||"mp4a"):(j.warn('Unhandled video codec "'+r+'" in mp4 MAP'),r||"avc1")}try{Ri=self.performance.now.bind(self.performance)}catch(e){Ri=Date.now}var wi=[{demux:ei,remux:Ai},{demux:oi,remux:Ti},{demux:zr,remux:Ti},{demux:Kr,remux:Ti}],Ii=function(){function e(e,t,r,i,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=r,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,r,i){var s=this,n=r.transmuxing;n.executeStart=Ri();var a=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var h=i||o,u=h.contiguous,d=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,p=h.initSegmentChange,m=l.audioCodec,v=l.videoCodec,y=l.defaultInitPts,E=l.duration,S=l.initSegmentData,T=function(e,t){var r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}(a,t);if(T&&Dt(T.method)){var _=this.getDecrypter(),L=Ct(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,r);return s.decryptionPromise=null,t})),this.decryptionPromise;var b=_.softwareDecrypt(a,T.key.buffer,T.iv.buffer,L);if(r.part>-1){var w=_.flush();b=w?w.buffer:w}if(!b)return n.executeEnd=Ri(),Di(r);a=new Uint8Array(b)}var I=this.needsProbing(d,c);if(I){var D=this.configureTransmuxer(a);if(D)return this.logger.warn("[transmuxer] "+D.message),this.observer.emit(P.ERROR,P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),n.executeEnd=Ri(),Di(r)}(d||c||p||I)&&this.resetInitSegment(S,m,v,E,t),(d||p||I)&&this.resetInitialTimestamp(y),u||this.resetContiguity();var C=this.transmux(a,T,g,f,r);this.asyncResult=Ci(C);var k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,n.executeEnd=Ri(),C},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=Ri();var i=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(i){var l=i.flush();l&&a.push(this.push(l.buffer,null,e))}var h=this.demuxer,u=this.remuxer;if(!h||!u){r.executeEnd=Ri();var d=[Di(e)];return this.asyncResult?Promise.resolve(d):d}var c=h.flush(o);return Ci(c)?(this.asyncResult=!0,c.then((function(r){return t.flushRemux(a,r,e),a}))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)},t.flushRemux=function(e,t,r){var i=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: "+r.sn+(r.part>-1?" part: "+r.part:"")+" of "+(this.id===k?"level":"track")+" "+r.level);var u=this.remuxer.remux(i,s,n,a,h,l,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=Ri()},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i,s){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(e,t,r,i),a.resetInitSegment(e,t,r,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,r,i,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,s):this.transmuxUnencrypted(e,r,i,s)},t.transmuxUnencrypted=function(e,t,r,i){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,r,!1,this.id),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,s){var n=this;return this.demuxer.demuxSampleAes(e,t,r).then((function(e){return{remuxResult:n.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,n.id),chunkMeta:s}}))},t.configureTransmuxer=function(e){for(var t,r=this.config,i=this.observer,s=this.typeSupported,n=0,a=wi.length;n<a;n++){var o;if(null!=(o=wi[n].demux)&&o.probe(e,this.logger)){t=wi[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(i,r,s,this.logger)),l&&l instanceof d||(this.demuxer=new d(i,r,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 Jr(this.config)),e},e}(),Di=function(e){return{remuxResult:{},chunkMeta:e}};function Ci(e){return"then"in e&&e.then instanceof Function}var ki=function(e,t,r,i,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=r,this.duration=i,this.defaultInitPts=s||null},Mi=function(e,t,r,i,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=r,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=n},xi=/(\d+)-(\d+)\/(\d+)/,Oi=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||Ni,this.controller=new self.AbortController,this.stats=new Q}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,r){var i=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 r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(n({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}(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=r,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&_(u)?u:d,this.requestTimeout=self.setTimeout((function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(s,e,i.response))}),t.timeout),(Ci(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(r){var n;i.response=i.loader=r;var a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(i.requestTimeout),t.timeout=d,i.requestTimeout=self.setTimeout((function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(s,e,i.response))}),d-(a-s.loading.start)),!r.ok){var l=r.status,h=r.statusText;throw new Fi(h||"fetch, bad network response",l,r)}s.loading.first=a,s.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=xi.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(_(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(r.headers)||s.total;var u=null==(n=i.callbacks)?void 0:n.onProgress;return u&&_(t.highWaterMark)?i.loadProgressively(r,s,e,t.highWaterMark,u):o?r.arrayBuffer():"json"===e.responseType?r.json():r.text()})).then((function(r){var n,a,o=i.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(i.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);var h=r[l];h&&(s.loaded=s.total=h);var u={url:o.url,data:r,code:o.status},d=null==(n=i.callbacks)?void 0:n.onProgress;d&&!_(t.highWaterMark)&&d(s,e,r,o),null==(a=i.callbacks)||a.onSuccess(u,s,e,o)})).catch((function(t){var r;if(self.clearTimeout(i.requestTimeout),!s.aborted){var n=t&&t.code||0,a=t?t.message:null;null==(r=i.callbacks)||r.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,r,i,s){void 0===i&&(i=0);var n=new ur,a=e.body.getReader(),o=function(){return a.read().then((function(a){if(a.done)return n.dataLength&&s(t,r,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return t.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&s(t,r,n.flush().buffer,e)):s(t,r,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},e}();function Ni(e,t){return new self.Request(e.url,t)}var Fi=function(e){function t(t,r,i){var s;return(s=e.call(this,t)||this).code=void 0,s.details=void 0,s.code=r,s.details=i,s}return o(t,e),t}(f(Error)),Bi=/^age:\s*[\d.]+\s*$/im,Ui=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 Q,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,r){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=r,this.loadInternal()},t.loadInternal=function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=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===i&&!e.stats.aborted)return n(i,r.url)})).catch((function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),n(i,r.url)})).then((function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)})).catch((function(t){var n;null==(n=e.callbacks)||n.onError({code:i.status,text:t.message},r,i,s)})):this.openAndSendXhr(i,r,t)}},t.openAndSendXhr=function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,s=r.loadPolicy,n=s.maxTimeToFirstByteMs,a=s.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[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),r.timeout=n&&_(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()},t.readystatechange=function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,s=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.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-(r.loading.first-r.loading.start)))),4===i)){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;r.loading.end=Math.max(self.performance.now(),r.loading.first);var u="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=u,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var c={url:t.responseURL,data:o,code:n};return void(null==(h=this.callbacks)||h.onSuccess(c,r,e,t))}}var f,g=s.loadPolicy.errorRetry;ct(g,r.retry,!1,{url:e.url,data:void 0,code:n})?this.retry(g):(j.error(n+" while loading "+e.url),null==(f=this.callbacks)||f.onError({code:n,text:t.statusText},e,t,r))}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(ct(e,this.stats.retry,!0))this.retry(e);else{var t;j.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,r=this.stats;this.retryDelay=ut(e,r.retry),r.retry++,j.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?void 0:t.url)+", retrying "+r.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&&Bi.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}(),Gi={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},$i=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,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,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:Ui,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:rt,bufferController:St,capLevelController:Lt,errorController:ft,fpsController:hr,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:null,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!1,certLoadPolicy:{default:Gi},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:Gi},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:K,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:ar,interstitialsController:void 0});function Hi(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Hi):Object.keys(e).reduce((function(t,r){return t[r]=Hi(e[r]),t}),{}):e}var Wi="NOT_LOADED",Vi="APPENDING",qi="PARTIAL",ji="OK",zi=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.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this)},t._unregisterListeners=function(){var e=this.hls;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this)},t.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var s=r[i];if(!s)break;var n=s.end;if(s.start<=e&&null!==n&&e<=n)return s}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){return this.getFragAtPos(e,t,!0)},t.getFragAtPos=function(e,t,r){for(var i=this.fragments,s=Object.keys(i),n=s.length;n--;){var a=i[s[n]];if((null==a?void 0:a.body.type)===t&&(!r||a.buffered)){var o=a.body;if(o.start<=e&&e<=o.end)return o}}return null},t.detectEvictedFragments=function(e,t,r,i,s){var n=this;this.timeRanges&&(this.timeRanges[e]=t);var a=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(i){var o=n.fragments[i];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 r=!n.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&n.removeFragment(o.body),r})):n.removeFragment(o.body))}else o.body.type===r&&n.removeFragment(o.body)}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges;if(r&&"initSegment"!==e.frag.sn){var i=e.frag,s=Yi(i),n=this.fragments[s];if(!(!n||n.buffered&&i.gap)){var a=!i.relurl;Object.keys(r).forEach((function(s){var o=i.elementaryStreams[s];if(o){var l=r[s],h=a||!0===o.partial;n.range[s]=t.getBufferedTimes(i,e.part,h,l)}})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ki(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}}},t.removeParts=function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Xi(r,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var r=Yi(e),i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)},t.getBufferedTimes=function(e,t,r,i){for(var s={time:[],partial:r},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n,h=0;h<i.length;h++){var u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(l>=u&&o<=d){s.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(a,i.end(h))});break}if(n<d&&a>u){var c=Math.max(n,i.start(h)),f=Math.min(a,i.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,r,i,s=null,n=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&Ki(h)&&(r=h.body.start-a,i=h.body.end+a,e>=r&&e<=i&&(t=Math.min(e-r,i-e),n<=t&&(s=h.body,n=t)))})),s},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Ki(t))},t.getState=function(e){var t=Yi(e),r=this.fragments[t];return r?r.buffered?Ki(r)?qi:ji:Vi:Wi},t.isTimeBuffered=function(e,t,r){for(var i,s,n=0;n<r.length;n++){if(i=r.start(n)-this.bufferPadding,s=r.end(n)+this.bufferPadding,e>=i&&t<=s)return!0;if(t<=i)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,s=Yi(r);this.fragments[s]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=t.frag,i=t.part,s=t.timeRanges,n=t.type;if("initSegment"!==r.sn){var a=r.type;if(i){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=s;var l=s[n];this.detectEvictedFragments(n,l,a,i)}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Yi(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var s=t[r[i]];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,r,i,s){var n=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=n.fragments[a];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||s)&&n.removeFragment(l)}}))},t.removeFragment=function(e){var t=Yi(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Xi(r,(function(e){return e.fragment.sn!==i}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var r=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;r&&r.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function Ki(e){var t,r,i;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(r=e.range.audio)?void 0:r.partial)||(null==(i=e.range.audiovideo)?void 0:i.partial))}function Yi(e){return e.type+"_"+e.level+"_"+e.sn}function Xi(e,t){return e.filter((function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r}))}var Qi=Math.pow(2,17),Ji=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 r=this,i=e.url;if(!i)return Promise.reject(new ts({type:R.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));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){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void l(es(e));e.gap=!1}var h=r.loader=n?new n(s):new a(s),d=Zi(e);e.loader=h;var c=dt(s.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Qi};e.stats=h.stats;var g={onSuccess:function(t,i,s,n){r.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){r.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:u({url:i,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:n,stats:a}))},onAbort:function(t,i,s){r.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:function(t,i,s){r.resetLoader(e,h),l(new ts({type:R.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(r,i,s,n){return t({frag:e,part:null,payload:s,networkDetails:n})}),h.load(d,f,g)}))},t.loadPart=function(e,t,r){var i=this;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||t.gap)l(es(e,t));else{var h=i.loader=n?new n(s):new a(s),d=Zi(e,t);e.loader=h;var c=dt(s.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Qi};t.stats=h.stats,h.load(d,f,{onSuccess:function(s,n,a,l){i.resetLoader(e,h),i.updateStatsFromPart(e,t);var u={frag:e,part:t,payload:s.data,networkDetails:l};r(u),o(u)},onError:function(r,s,n,a){i.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:u({url:d.url,data:void 0},r),error:new Error("HTTP Error "+r.code+" "+r.text),networkDetails:n,stats:a}))},onAbort:function(r,s,n){e.stats.aborted=t.stats.aborted,i.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:n,stats:r}))},onTimeout:function(r,s,n){i.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:r}))}})}}))},t.updateStatsFromPart=function(e,t){var r=e.stats,i=t.stats,s=i.total;if(r.loaded+=i.loaded,s){var n=Math.round(e.duration/t.duration),a=Math.min(Math.round(r.loaded/s),n),o=(n-a)*Math.round(r.loaded/a);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,h=i.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 Zi(e,t){void 0===t&&(t=null);var r,i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if(_(n)&&_(a)){var o,l=n,h=a;if("initSegment"===e.sn&&("AES-128"===(r=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===r)){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 es(e,t){var r=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),i={type:R.MEDIA_ERROR,details:A.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new ts(i)}var ts=function(e){function t(t){var r;return(r=e.call(this,t.error.message)||this).data=void 0,r.data=t,r}return o(t,e),t}(f(Error)),rs=function(e){function t(t,r){var i;return(i=e.call(this,t,r)||this)._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}o(t,e);var r=t.prototype;return r.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},r.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},r.onHandlerDestroyed=function(){},r.hasInterval=function(){return!!this._tickInterval},r.hasNextTick=function(){return!!this._tickTimer},r.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},r.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},r.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},r.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},r.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},r.doTick=function(){},t}(F),is=function(e,t,r,i,s,n){void 0===i&&(i=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=r,this.size=i,this.part=s,this.partial=n};function ss(e,t){for(var r=0,i=e.length;r<i;r++){var s;if((null==(s=e[r])?void 0:s.cc)===t)return e[r]}return null}function ns(e,t){if(e){var r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}function as(e,t){for(var r=t.fragments,i=0,s=r.length;i<s;i++)ns(r[i],e);t.fragmentHint&&ns(t.fragmentHint,e),t.alignedSliding=!0}var os={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_LEVEL:"WAITING_LEVEL"},ls=function(e){function t(t,r,i,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=os.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,r=e.fragCurrent,i=e.media,s=e.mediaBuffer,n=e.state,o=i?i.currentTime:0,l=mt.bufferInfo(s||i,o,t.maxBufferHole);if(a.log("media seeking to "+(_(o)?o.toFixed(3):o)+", state: "+n),a.state===os.ENDED)a.resetLoadingState();else if(r){var h=t.maxFragLookUpTolerance,u=r.start-h,d=r.start+r.duration+h;if(!l.len||d<l.start||u>l.end){var c=o>d;(o<u||c)&&(c&&r.loader&&(a.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),r.abortRequests(),a.resetLoadingState()),a.fragPrevious=null)}}if(i&&(a.fragmentTracker.removeFragmentsInRange(o,1/0,a.playlistType,!0),o>a.lastCurrentTime&&(a.lastCurrentTime=o),!a.loadingParts)){var f=Math.max(l.end,o),g=a.shouldLoadParts(a.getLevelDetails(),f);g&&(a.log("LL-Part loading ON after seeking to "+o.toFixed(2)+" with buffer @"+f.toFixed(2)),a.loadingParts=g)}a.hls.hasEnoughToStart||l.len||(a.log("setting startPosition to "+o+" because of seek before start"),a.nextLoadPosition=a.startPosition=o),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 Ji(t.config),a.keyLoader=i,a.fragmentTracker=r,a.config=t.config,a.decrypter=new Jr(t.config),a}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.ERROR,this.onError,this)},r.doTick=function(){this.onTickEnd()},r.onTickEnd=function(){},r.startLoad=function(e){},r.stopLoad=function(){if(this.state!==os.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=os.STOPPED}},r.pauseBuffering=function(){this.buffering=!1},r.resumeBuffering=function(){this.buffering=!0},r._streamEnded=function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var s=e.nextStart;if(s&&s>i&&s<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var n=t.partList;if(null!=n&&n.length){var a=n[n.length-1];return mt.isBuffered(this.media,a.start+a.duration/2)}var o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)},r.getLevelDetails=function(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details},r.onMediaAttached=function(e,t){var r=this.media=this.mediaBuffer=t.media;r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),r.addEventListener("seeking",this.onMediaSeeking),r.addEventListener("ended",this.onMediaEnded);var i=this.config;this.levels&&i.autoStartLoad&&this.state===os.STOPPED&&this.startLoad(i.startPosition)},r.onMediaDetaching=function(e,t){var r=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},r.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},r.onError=function(e,t){},r.onManifestLoaded=function(e,t){this.startTimeOffset=t.startTimeOffset},r.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),e.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},r.onHandlerDestroyed=function(){this.state=os.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)},r.loadFragment=function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)},r._loadFragForPlayback=function(e,t,r){var i=this;this._doFragLoad(e,t,r,(function(e){var t=e.frag;if(i.fragContextChanged(t))return i.warn(t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+i.fragInfo(t,!1,e.part)+") was dropped during download."),void i.fragmentTracker.removeFragment(t);t.stats.chunkCount++,i._handleFragmentLoadProgress(e)})).then((function(e){if(e){var t=i.state,r=e.frag;i.fragContextChanged(r)?(t===os.FRAG_LOADING||!i.fragCurrent&&t===os.PARSING)&&(i.fragmentTracker.removeFragment(r),i.state=os.IDLE):("payload"in e&&(i.log("Loaded "+r.type+" sn: "+r.sn+" of "+i.playlistLabel()+" "+r.level),i.hls.trigger(P.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}})).catch((function(t){i.state!==os.STOPPED&&i.state!==os.ERROR&&(i.warn("Frag error: "+((null==t?void 0:t.message)||t)),i.resetFragmentLoading(e))}))},r.clearTrackerIfNeeded=function(e){var t,r=this.fragmentTracker;if(r.getState(e)===Vi){var i=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,i),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))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===qi&&r.removeFragment(e))},r.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)},r.waitForLive=function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)},r.flushMainBuffer=function(e,t,r){if(void 0===r&&(r=null),e-t){var i={startOffset:e,endOffset:t,type:r};this.hls.trigger(P.BUFFER_FLUSHING,i)}},r._loadInitSegment=function(e,t){var r=this;this._doFragLoad(e,t).then((function(e){var t=null==e?void 0:e.frag;if(!t||r.fragContextChanged(t)||!r.levels)throw new Error("init load aborted");return e})).then((function(e){var t=r.hls,i=e.frag,s=e.payload,n=i.decryptdata;if(s&&s.byteLength>0&&null!=n&&n.key&&n.iv&&Dt(n.method)){var a=self.performance.now();return r.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,Ct(n.method)).catch((function(e){throw t.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((function(s){var n=self.performance.now();return t.trigger(P.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:a,tdecrypt:n}}),e.payload=s,r.completeInitSegmentLoad(e)}))}return r.completeInitSegmentLoad(e)})).catch((function(t){r.state!==os.STOPPED&&r.state!==os.ERROR&&(r.warn(t),r.resetFragmentLoading(e))}))},r.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==os.STOPPED&&(this.state=os.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()},r.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},r.fragBufferedComplete=function(e,t){var r=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:"+(r?function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="["+e.start(i).toFixed(3)+"-"+e.end(i).toFixed(3)+"]";return t}(mt.getBuffered(r)):"(detached)")+")"),re(e)){var i;if(e.type!==x){var s=e.elementaryStreams;if(!Object.keys(s).some((function(e){return!!s[e]})))return void(this.state=os.IDLE)}var n=null==(i=this.levels)?void 0:i[e.level];null!=n&&n.fragmentError&&(this.log("Resetting level fragment error count of "+n.fragmentError+" on frag buffered"),n.fragmentError=0)}this.state=os.IDLE},r._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,s=e.partsLoaded,n=!s||0===s.length||s.some((function(e){return!e})),a=new is(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}},r._handleFragmentLoadProgress=function(e){},r._doFragLoad=function(e,t,r,i){var s,n=this;void 0===r&&(r=null),this.fragCurrent=e;var a=null==t?void 0:t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var o=null;!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments):(this.log("Loading key for "+e.sn+" of ["+a.startSN+"-"+a.endSN+"], "+this.playlistLabel()+" "+e.level),this.state=os.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(P.KEY_LOADED,e),n.state===os.KEY_LOADING&&(n.state=os.IDLE),e})),this.hls.trigger(P.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));var l=this.fragPrevious;if(re(e)&&(!l||e.sn!==l.sn)){var h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log("LL-Part loading "+(h?"ON":"OFF")+" loading sn "+(null==l?void 0:l.sn)+"->"+e.sn),this.loadingParts=h)}if(r=Math.max(e.start,r||0),this.loadingParts&&re(e)){var u=a.partList;if(u&&i){r>e.end&&a.fragmentHint&&(e=a.fragmentHint);var d=this.getNextPart(u,e,r);if(d>-1){var c,f=u[d];return e=this.fragCurrent=f.fragment,this.log("Loading "+e.type+" sn: "+e.sn+" part: "+f.index+" ("+d+"/"+(u.length-1)+") of "+this.fragInfo(e,!1,f)+") cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=f.start+f.duration,this.state=os.FRAG_LOADING,c=o?o.then((function(r){return!r||n.fragContextChanged(r.frag)?null:n.doFragPartsLoad(e,f,t,i)})).catch((function(e){return n.handleFragLoadError(e)})):this.doFragPartsLoad(e,f,t,i).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(P.FRAG_LOADING,{frag:e,part:f,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(u,r))return Promise.resolve(null)}}if(re(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+r.toFixed(2)),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?"["+a.startSN+"-"+a.endSN+"]":"")+", target: "+parseFloat(r.toFixed(3))),_(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=os.FRAG_LOADING;var g,p=this.config.progressive;return g=p&&o?o.then((function(t){return!t||n.fragContextChanged(null==t?void 0:t.frag)?null:n.fragmentLoader.load(e,i)})).catch((function(e){return n.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,p?i:void 0),o]).then((function(e){var t=e[0];return!p&&t&&i&&i(t),t})).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(P.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g},r.doFragPartsLoad=function(e,t,r,i){var s=this;return new Promise((function(n,a){var o,l=[],h=null==(o=r.details)?void 0:o.partList,u=function(t){s.fragmentLoader.loadPart(e,t,i).then((function(i){l[t.index]=i;var a=i.part;s.hls.trigger(P.FRAG_LOADED,i);var o=ir(r.details,e.sn,t.index+1)||sr(h,e.sn,t.index+1);if(!o)return n({frag:e,part:a,partsLoaded:l});u(o)})).catch(a)};u(t)}))},r.handleFragLoadError=function(e){if("data"in e){var t=e.data;e.data&&t.details===A.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(P.ERROR,t)}else this.hls.trigger(P.ERROR,{type:R.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},r._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===os.PARSING){var r=t.frag,i=t.part,s=t.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n);var a=this.getLevelDetails(),o=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+r.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(r,i,s,e.partial)}else this.fragCurrent||this.state===os.STOPPED||this.state===os.ERROR||(this.state=os.IDLE)},r.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var r,i,s=e.partList[0];if(t>=s.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0)&&(this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}return!1},r.getCurrentContext=function(e){var t=this.levels,r=this.fragCurrent,i=e.level,s=e.sn,n=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment "+s+" of "+this.playlistLabel()+" "+i+". The current chunk will not be buffered."),null;var a=t[i],o=a.details,l=n>-1?ir(o,s,n):null,h=l?l.fragment:rr(o,s,r);return h?(r&&r!==h&&(h.stats=r.stats),{frag:h,part:l,level:a}):null},r.bufferFragmentData=function(e,t,r,i,s){var n;if(e&&this.state===os.PARSING){var a=e.data1,o=e.data2,l=a;if(a&&o&&(l=be(a,o)),null!=(n=l)&&n.length){var h={type:e.type,frag:t,part:r,chunkMeta:i,parent:t.type,data:l};if(this.hls.trigger(P.BUFFER_APPENDING,h),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}}},r.flushBufferGap=function(e){var t=this.media;if(t)if(mt.isBuffered(t,t.currentTime)){var r=t.currentTime,i=mt.bufferInfo(t,r,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,i.end-n),r+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}else this.flushMainBuffer(0,e.start)},r.getFwdBufferInfo=function(e,t){var r,i=this.getLoadPosition();if(!_(i))return null;var s=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,s)},r.getFwdBufferInfoAtPos=function(e,t,r,i){var s=mt.bufferInfo(e,t,i);if(0===s.len&&void 0!==s.nextStart){var n=this.fragmentTracker.getBufferedFrag(t,r);if(n&&(s.nextStart<=n.end||n.gap)){var a=Math.max(Math.min(s.nextStart,n.end)-t,i);return mt.bufferInfo(e,t,a)}}return s},r.getMaxBufferLength=function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)},r.reduceMaxBufferLength=function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t),s=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return s>=i&&(r.maxMaxBufferLength=s,this.warn("Reduce max buffer length to "+s+"s"),!0)},r.getAppendedFrag=function(e,t){var r;void 0===t&&(t=k);var i=null==(r=this.fragmentTracker)?void 0:r.getAppendedFrag(e,t);return i&&"fragment"in i?i.fragment:i},r.getNextFragment=function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var s=this.config,n=r[0].start,a=s.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=s.initialLiveManifestSize;if(i<l)return this.warn("Not enough fragments to start playback (have: "+i+", 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,r);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=r[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(r[p+1]||null,t)}return this.mapToInitFragWhenRequired(g)},r.isLoopLoading=function(e,t){var r=this.fragmentTracker.getState(e);return(r===ji||r===qi&&!!e.gap)&&this.nextLoadPosition>t},r.getNextFragmentLoopLoading=function(e,t,r,i,s){var n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t))&&!n.gap&&r.nextStart){var a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==a&&r.len+a.len>=s){var o=n.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,n},r.filterReplacedPrimary=function(e,t){return e?(this.hls.config,e):e},r.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment},r.getNextPart=function(e,t,r){for(var i=-1,s=!1,n=!0,a=0,o=e.length;a<o;a++){var l=e[a];if(n=n&&!l.independent,i>-1&&r<l.start)break;var h=l.loaded;h?i=-1:(s||l.independent||n)&&l.fragment===t&&(i=a),s=h}return i},r.loadedEndOfParts=function(e,t){var r=e[e.length-1];return r&&t>r.start&&r.loaded},r.getInitialLiveFragment=function(e,t){var r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!_(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i<e.length;++i){var s=e[i];if(ot(t,r,s))return s}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){var n=t[s-e.startSN];r.cc===n.cc&&(i=n,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(e,t){return st(e,(function(e){return e.cc<t?1:e.cc>t?-1:0}))}(t,r.cc),i&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn))}}else{var a=this.hls.liveSyncPosition;null!==a&&(i=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},r.getFragmentAtPosition=function(e,t,r){var i,s,n=this.config,a=this.fragPrevious,o=r.fragments,l=r.endSN,h=r.fragmentHint,u=n.maxFragLookUpTolerance,d=r.partList,c=!!(this.loadingParts&&null!=d&&d.length&&h);if(c&&h&&!this.bitrateTest&&d[d.length-1].fragment.sn===h.sn&&(o=o.concat(h),l=h.sn),i=e<t?nt(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=i.sn-r.startSN,g=this.fragmentTracker.getState(i);if((g===ji||g===qi&&i.gap)&&(a=i),a&&i.sn===a.sn&&(!c||d[0].fragment.sn>i.sn||!r.live&&!c)&&a&&i.level===a.level){var p=o[f+1];i=i.sn<l&&this.fragmentTracker.getState(p)!==ji?p:null}}return i},r.alignPlaylists=function(e,t,r){var i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;var s=e.fragmentStart,n=!t,a=e.alignedSliding&&_(s);if(n||!a&&!s){!function(e,t){e&&(function(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var r=Math.min(t.endCC,e.endCC),i=ss(t.fragments,r),s=ss(e.fragments,r);i&&s&&(j.log("Aligning playlist at start of dicontinuity sequence "+r),as(i.start-s.start,e))}}(t,e),!t.alignedSliding&&e&&function(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var r,i,s=e.fragments,n=t.fragments;if(s.length&&n.length){var a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=ss(n,a),i=ss(s,a)),r&&i||(i=ss(s,(r=n[Math.floor(n.length/2)]).cc)||s[Math.floor(s.length/2)]);var o=r.programDateTime,l=i.programDateTime;o&&l&&as((l-o)/1e3-(i.start-r.start),e)}}}(t,e),t.alignedSliding||!e||t.skippedSegments||er(e,t,!1))}(r,e);var o=e.fragmentStart;return this.log("Live playlist sliding: "+o.toFixed(2)+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" fragments: "+i),o}return s},r.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},r.setStartPosition=function(e,t){var r=this.startPosition;r<t&&(r=-1);var i=this.timelineOffset;if(-1===r){var s=null!==this.startTimeOffset,n=s?this.startTimeOffset:e.startTimeOffset;null!==n&&_(n)?(r=t+n,n<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to "+r+" for start time offset "+n+" found in "+(s?"multivariant":"media")+" playlist"),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge "+r),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+i}this.nextLoadPosition=r+i},r.getLoadPosition=function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r},r.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&re(e)&&e.stats.aborted&&(this.warn("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},r.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===os.FRAG_LOADING_WAITING_RETRY)||(this.state=os.IDLE)},r.onFragmentOrKeyLoadError=function(e,t){if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var i=t.frag;if(i&&i.type===e&&this.levels)if(this.fragContextChanged(i)){var s;this.warn("Frag load error must match current frag to retry "+i.url+" > "+(null==(s=this.fragCurrent)?void 0:s.url))}else{var n=t.details===A.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);var a=t.errorAction,o=a||{},l=o.action,h=o.flags,u=o.retryCount,d=void 0===u?0:u,c=o.retryConfig,f=!!a&&!!c,g=f&&5===l,p=f&&!a.resolved&&1===h;if(!g&&p&&re(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((g||p)&&d<c.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);var m=ut(c,d);this.warn("Fragment "+i.sn+" of "+e+" "+i.level+" errored with "+t.details+", retrying loading "+(d+1)+"/"+c.maxNumRetry+" in "+m+"ms"),a.resolved=!0,this.retryDate=self.performance.now()+m,this.state=os.FRAG_LOADING_WAITING_RETRY}else if(c&&a){if(this.resetFragmentErrors(e),!(d<c.maxNumRetry))return void this.warn(t.details+" reached or exceeded max retry ("+d+")");n||3===l||(a.resolved=!0)}else this.state=2===l?os.WAITING_LEVEL:os.ERROR;this.tickImmediate()}},r.reduceLengthAndFlushBuffer=function(e){if(this.state===os.PARSING||this.state===os.PARSED){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var n=!s;return n&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+r+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1},r.resetFragmentErrors=function(e){e===M&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==os.STOPPED&&(this.state=os.IDLE)},r.afterBufferFlushed=function(e,t,r){if(e){var i=mt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===os.ENDED&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==os.STOPPED&&(this.state=os.IDLE)},r.resetStartWhenNotLoaded=function(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var 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}},r.resetWhenMissingContext=function(e){this.warn("The loading context changed while buffering fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},r.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(e,t,r,i){var s=this,n=r.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=i?0:Qt(n,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return s.hls.trigger(P.LEVEL_PTS_UPDATED,{details:n,level:r,drift:h,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===r.fragmentError&&this.treatAsGap(e,r),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(P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=os.PARSED,this.log("Parsed "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+")"),this.hls.trigger(P.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")},r.playlistLabel=function(){return this.playlistType===k?"level":"track"},r.fragInfo=function(e,t,r){var i,s;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(r?"part":"frag")+":["+(null!=(i=t&&!r?e.startPTS:(r||e).start)?i:NaN).toFixed(3)+"-"+(null!=(s=t&&!r?e.endPTS:(r||e).end)?s:NaN).toFixed(3)+"]"+(r&&"main"===e.type?"INDEPENDENT="+(r.independent?"YES":"NO"):"")},r.treatAsGap=function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)},r.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},r.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},i(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(){return this.hls.config,!1}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}(rs);function hs(e,t,r){us(e,t,r),e.addEventListener(t,r)}function us(e,t,r){e.removeEventListener(t,r)}var ds=function(e){function t(t,r){var i;return(i=e.call(this,"gap-controller",t.logger)||this).hls=null,i.fragmentTracker=null,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(P.MEDIA_ENDED,{stalled:!1}))},i.hls=t,i.fragmentTracker=r,i.registerListeners(),i}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this))},r.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},r.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;hs(r,"playing",this.onMediaPlaying),hs(r,"waiting",this.onMediaWaiting),hs(r,"ended",this.onMediaEnded)},r.onMediaDetaching=function(e,t){this.clearInterval();var r=this.media;r&&(us(r,"playing",this.onMediaPlaying),us(r,"waiting",this.onMediaWaiting),us(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},r.onBufferAppended=function(e,t){this.buffered=t.timeRanges},r.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}},r.poll=function(e,t){var r,i,s=null==(r=this.hls)?void 0:r.config;if(s){var n=this.media,a=this.stalled;if(n){var o=n.seeking,l=this.seeking&&!o,h=!this.seeking&&o,u=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,e!==t)return t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(h||l)l&&this.stallResolved(e);else{if(u)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(P.MEDIA_ENDED,{stalled:!1})));if(mt.getBuffered(n).length){var d=mt.bufferInfo(n,e,0),c=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){var g=cs(this.hls.inFlightFragments,e),p=d.len>2,m=!c||g||c-e>2&&!f.getPartialFragment(e);if(p||m)return;this.moved=!1}var v=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(d.len>0||c))return;var y=Math.max(c,d.start||0)-e,E=null!=v&&v.live?2*v.targetduration:2,S=f.getPartialFragment(e);if(y>0&&(y<=E||S))return void(n.paused||this._trySkipBufferHole(S))}var T=s.detectStallWithCurrentTimeMs,_=self.performance.now(),L=this.waiting;if(null!==a){var b=_-a;if(!o&&(b>=T||L)&&this.hls){var R;if("ended"===(null==(R=this.mediaSource)?void 0:R.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(P.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}var A=mt.bufferInfo(n,e,s.maxBufferHole);this._tryFixBufferStall(A,b)}else this.stalled=L>0&&_-L<T?L:_}else this.nudgeRetry=0}}}},r.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(r)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(P.STALL_RESOLVED,{})}},r.nudgeOnVideoHole=function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var s=mt.bufferedInfo(mt.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){var n=mt.timeRangesToArray(i),a=mt.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&a<n.length-1){var o=mt.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=this.fragmentTracker.getPartialFragment(e)||void 0,c=mt.bufferInfo(this.media,e,0);this.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:c.len,bufferInfo:c})}}}}},r._tryFixBufferStall=function(e,t){var r,i,s=this.fragmentTracker,n=this.media,a=null==(r=this.hls)?void 0:r.config;if(n&&s&&a){var o=n.currentTime,l=null==(i=this.hls)?void 0:i.latestLevelDetails,h=s.getPartialFragment(o);if((h||null!=l&&l.live&&o<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;var u=e.buffered;(u&&u.length>1&&e.len>a.maxBufferHole||e.nextStart&&e.nextStart-o<a.maxBufferHole)&&(t>1e3*a.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}},r._reportStall=function(e){var t=this.hls,r=this.media,i=this.stallReported,s=this.stalled;if(!i&&null!==s&&r&&t){this.stallReported=!0;var n=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+Je(e)+")");this.warn(n.message),t.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:s}})}},r._trySkipBufferHole=function(e){var t,r=this.fragmentTracker,i=this.media,s=null==(t=this.hls)?void 0:t.config;if(!i||!r||!s)return 0;var n=i.currentTime,a=mt.bufferInfo(i,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&&i.readyState<3,u=o-n;if(u>0&&(l||h)){if(u>s.maxBufferHole){var d=!1;if(0===n){var c=r.getAppendedFrag(0,k);c&&o<c.end&&(d=!0)}if(!d){var f=e||r.getAppendedFrag(n,k);if(f){var g;if(null==(g=this.hls.loadLevelObj)||!g.details)return 0;if(cs(this.hls.inFlightFragments,o))return 0;for(var p=!1,m=f.end;m<o;){var v=r.getPartialFragment(m);if(!v){p=!0;break}m+=v.duration}if(p)return 0}}}var y=Math.max(o+.05,n+.1);if(this.warn("skipping hole, adjusting currentTime from "+n+" to "+y),this.moved=!0,i.currentTime=y,null==e||!e.gap){var E=new Error("fragment loaded with buffer holes, seeking from "+n+" to "+y);this.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:E,reason:E.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return y}}return 0},r._tryNudgeBuffer=function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,s=null==t?void 0:t.config;if(!r||!s)return 0;var n=r.currentTime;if(this.nudgeRetry++,i<s.nudgeMaxRetry){var a=n+(i+1)*s.nudgeOffset,o=new Error("Nudging 'currentTime' from "+n+" to "+a);this.warn(o.message),r.currentTime=a,t.trigger(P.ERROR,{type:R.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(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}},i(t,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}(rs);function cs(e,t){var r=fs(e.main);if(r&&r.start<=t)return r;var i=fs(e.audio);return i&&i.start<=t?i:null}function fs(e){if(!e)return null;switch(e.state){case os.IDLE:case os.STOPPED:case os.ENDED:case os.ERROR:return null}return e.frag}function gs(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function ps(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ms(e,t,r,i,s){var n=new e(t,r,"");try{n.value=i,s&&(n.type=s)}catch(a){n=new e(t,r,Je(s?u({type:s},i):i))}return n}var vs=function(){var e=ps();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),ys=function(){function e(e){var t=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=function(){t.hls&&t.hls.trigger(P.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.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)},t._unregisterListeners=function(){var e=this.hls;e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)},t.onMediaAttaching=function(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)},t.onMediaAttached=function(){var e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)},t.onMediaDetaching=function(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&function(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(var i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===r&&(e.mode=r)}(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 r=e[t];if("metadata"===r.kind&&"id3"===r.label)return gs(r,this.media),r}return this.media.addTextTrack("metadata","id3")}},t.onFragParsingMetadata=function(e,t){if(this.media){var r=this.hls.config,i=r.enableEmsgMetadataCues,s=r.enableID3MetadataCues;if(i||s){var n=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=ps();if(a)for(var o=0;o<n.length;o++){var l=n[o].type;if((l!==Mr.emsg||i)&&s){var h=Ir(n[o].data);if(h){var u=n[o].pts,d=u+n[o].duration;d>vs&&(d=vs),d-u<=0&&(d=u+.25);for(var c=0;c<h.length;c++){var f=h[c];if(!Dr(f)){this.updateId3CueEnds(u,l);var g=ms(a,u,d,f,l);g&&this.id3Track.addCue(g)}}}}}}}},t.updateId3CueEnds=function(e,t){var r,i=null==(r=this.id3Track)?void 0:r.cues;if(i)for(var s=i.length;s--;){var n=i[s];n.type===t&&n.startTime<e&&n.endTime===vs&&(n.endTime=e)}},t.onBufferFlushing=function(e,t){var r=t.startOffset,i=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)&&function(e,t,r,i){var s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var n=function(e,t,r){var i=[],s=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;for(var i,s=0,n=r;s<=n;)if(t<e[i=Math.floor((n+s)/2)].startTime)n=i-1;else{if(!(t>e[i].startTime&&s<r))return i;s=i+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<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),a=0;a<n.length;a++)i&&!i(n[a])||e.removeCue(n[a]);"disabled"===s&&(e.mode=s)}(n,r,i,"audio"===s?function(e){return e.type===Mr.audioId3&&h}:"video"===s?function(e){return e.type===Mr.emsg&&l}:function(e){return e.type===Mr.audioId3&&h||e.type===Mr.emsg&&l})}},t.onLevelUpdated=function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)},t.onLevelPtsUpdated=function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var r=this;if(this.media&&e.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var i,s=this.id3Track,n=e.dateRanges,a=Object.keys(n),o=this.dateRangeCuesAppended;if(s&&t)if(null!=(i=s.cues)&&i.length)for(var l=Object.keys(o).filter((function(e){return!a.includes(e)})),h=function(){var e=l[u],t=o[e].cues;delete o[e],Object.keys(t).forEach((function(e){try{var i=t[e];i.removeEventListener("enter",r.onEventCueEnter),s.removeCue(i)}catch(e){}}))},u=l.length;u--;)h();else o=this.dateRangeCuesAppended={};var d=e.fragments[e.fragments.length-1];if(0!==a.length&&_(null==d?void 0:d.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var c=ps(),f=function(){var e=a[g],t=n[e],i=t.startTime,s=o[e],l=(null==s?void 0:s.cues)||{},h=(null==s?void 0:s.durationKnown)||!1,u=vs,d=t.duration;if(t.endDate&&null!==d)u=i+d,h=!0;else if(t.endOnNext&&!h){var f=a.reduce((function(e,r){if(r!==t.id){var i=n[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e}),null);f&&(u=f.startTime,h=!0)}for(var p,m,v=Object.keys(t.attr),y=0;y<v.length;y++){var E=v[y];if("ID"!==(m=E)&&"CLASS"!==m&&"CUE"!==m&&"START-DATE"!==m&&"DURATION"!==m&&"END-DATE"!==m&&"END-ON-NEXT"!==m){var S=l[E];if(S)h&&!s.durationKnown?S.endTime=u:Math.abs(S.startTime-i)>.01&&(S.startTime=i,S.endTime=u);else if(c){var T=t.attr[E];Pt(E)&&(p=T,T=Uint8Array.from(p.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);var _=ms(c,i,u,{key:E,data:T},Mr.dateRange);_&&(_.id=e,r.id3Track.addCue(_),l[E]=_)}}}o[e]={cues:l,dateRange:t,durationKnown:h}},g=0;g<a.length;g++)f()}}},e}(),Es=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,r=t.levelDetails;if(e&&r){t.currentTime=e.currentTime;var i=t.computeLatency();if(null!==i){t._latency=i;var s=t.config,n=s.lowLatencyMode,a=s.maxLiveSyncPlaybackRate;if(n&&1!==a&&r.live){var o=t.targetLatency;if(null!==o){var l=i-o;if(l<Math.min(t.maxLatency,o+r.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(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.ERROR,this.onError,this))},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.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 r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onError=function(e,t){var r;t.details===A.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(i=this.targetLatency)?void 0:i.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},i(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,r=e.partHoldBack,i=e.targetduration,s=this.config,n=s.liveSyncDuration,a=s.liveSyncDurationCount,o=s.lowLatencyMode,l=this.hls.userConfig,h=o&&r||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*i);var u=i;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 r=this.levelDetails;if(null===r)return null;var i=r.edge,s=e-t-this.edgeStalled,n=i-r.totalduration,a=i-(this.config.lowLatencyMode&&r.partTarget||r.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 r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}])}(),Ss=function(e){function t(t,r){var i;return(i=e.call(this,r,t.logger)||this).hls=void 0,i.canLoad=!1,i.timer=-1,i.hls=t,i}o(t,e);var r=t.prototype;return r.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},r.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},r.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},r.stopLoad=function(){this.canLoad=!1,this.clearTimer()},r.switchParams=function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var s=-1,n=0;n<i.length;n++){var a=i[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=i[s],h=parseInt(l["LAST-MSN"])||(null==t?void 0:t.lastPartSn),u=parseInt(l["LAST-PART"])||(null==t?void 0: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=r&&Ke(r);return new Ye(h,u>=0?u:void 0,c)}}},r.loadPlaylist=function(e){this.clearTimer()},r.loadingPlaylist=function(e,t){this.clearTimer()},r.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},r.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},r.playlistLoaded=function(e,t,r){var i=t.details,s=t.stats,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;i.advancedDateTime=Date.now()-a;var o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){var l=Math.max(o||0,0);i.appliedTimelineOffset=l,i.fragments.forEach((function(e){e.start=e.playlistOffset+l}))}if(i.live||null!=r&&r.live){var h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(r),r&&i.fragments.length>0){Jt(r,i);var u=i.playlistParsingError;if(u){this.warn(u);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var c,f=t.networkDetails;return void d.trigger(P.ERROR,{type:R.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:u,reason:u.message,level:t.level||void 0,parent:null==(c=i.fragments[0])?void 0:c.type,networkDetails:f,stats:s})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=s.loading.start);var g,p=this.hls.mainForwardBufferInfo,m=p?p.end-p.len:0,v=tr(i,1e3*(i.edge-m));if(i.requestScheduled+v<n?i.requestScheduled=n:i.requestScheduled+=v,this.log("live playlist "+e+" "+(i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED")),!this.canLoad||!i.live)return;var y=void 0,E=void 0;if(i.canBlockReload&&i.endSN&&i.advanced){var S=this.hls.config.lowLatencyMode,T=i.lastPartSn,_=i.endSN,L=i.lastPartIndex,b=T===_;-1!==L?b?(y=_+1,E=S?0:L):(y=T,E=S?L+1:i.maxPartIndex):y=_+1;var w=i.age,I=w+i.ageHeader,D=Math.min(I-i.partTarget,1.5*i.targetduration);if(D>0){if(I>3*i.targetduration)this.log("Playlist last advanced "+w.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=r&&r.tuneInGoal&&I-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+D+" with playlist age: "+i.age),D=0;else{var C=Math.floor(D/i.targetduration);y+=C,void 0!==E&&(E+=Math.round(D%i.targetduration/i.partTarget)),this.log("CDN Tune-in age: "+i.ageHeader+"s last advanced "+w.toFixed(2)+"s goal: "+D+" skip sn "+C+" to part "+E)}i.tuneInGoal=D}if(g=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),S||!b)return i.requestScheduled=n,void this.loadingPlaylist(h,g)}else(i.canBlockReload||i.canSkipUntil)&&(g=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));g&&void 0!==y&&i.canBlockReload&&(i.requestScheduled=s.loading.first+Math.max(v-2*a,v/2)),this.scheduleLoading(h,g,i)}else this.clearTimer()},r.scheduleLoading=function(e,t,r){var i=this,s=r||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 i.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},r.getDeliveryDirectives=function(e,t,r,i){var s=Ke(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,s=""),new Ye(r,i,s)},r.checkRetry=function(e){var t=this,r=e.details,i=lt(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(i&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var c=ut(h,l);this.clearTimer(),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+r+'" in '+c+"ms")}e.levelRetry=!0,s.resolved=!0}return u},t}(F),Ts=function(e){function t(t,r){var i;return(i=e.call(this,t,"level-controller")||this)._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}o(t,e);var r=t.prototype;return r._registerListeners=function(){var e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.ERROR,this.onError,this)},r._unregisterListeners=function(){var e=this.hls;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},r.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},r.onManifestLoading=function(e,t){this.resetLevels()},r.onManifestLoaded=function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,h=!1;t.levels.forEach((function(e){var t,u=e.attrs,d=e.audioCodec,c=e.videoCodec;d&&(e.audioCodec=d=$e(d,i)||void 0),0===(null==(t=c)?void 0:t.indexOf("avc1"))&&(c=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var i=t[r].split(".");if(i.length>2){var s=i.shift()+".";s+=parseInt(i.shift()).toString(16),s+=("000"+parseInt(i.shift()).toString(16)).slice(-4),t[r]=s}}return t.join(",")}(c));var f=e.width,g=e.height,p=e.unknownCodecs,m=p?p.length:0;if(p)for(var v=m;v--;){var y=p[v];r.isAudioSupported(y)?(e.audioCodec=d=d?d+","+y:y,m--,ke.audio[d.substring(0,4)]=2):r.isVideoSupported(y)&&(e.videoCodec=c=c?c+","+y:y,m--,ke.video[c.substring(0,4)]=2)}if(o||(o=!(!f||!g)),l||(l=!!c),h||(h=!!d),m||d&&!r.isAudioSupported(d)||c&&!r.isVideoSupported(c))r.log('Some or all CODECS not supported "'+u.CODECS+'"');else{var E=u.CODECS,S=u["FRAME-RATE"],T=u["HDCP-LEVEL"],_=u["PATHWAY-ID"],L=u.RESOLUTION,b=u["VIDEO-RANGE"],R=(_||".")+"-"+e.bitrate+"-"+L+"-"+S+"-"+E+"-"+b+"-"+T;if(n[R])if(n[R].uri===e.url||e.attrs["PATHWAY-ID"])n[R].addGroupId("audio",u.AUDIO),n[R].addGroupId("text",u.SUBTITLES);else{var A=a[R]+=1;e.attrs["PATHWAY-ID"]=new Array(A+1).join(".");var P=r.createLevel(e);n[R]=P,s.push(P)}else{var w=r.createLevel(e);n[R]=w,a[R]=1,s.push(w)}}})),this.filterAndSortMediaOptions(s,t,o,l,h)},r.createLevel=function(e){var t=new Xe(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'+r.videoCodec+'"');this.log(i.message),t.supportedResult=z.getUnsupportedResult(i,[])}return t},r.isAudioSupported=function(e){return xe(e,"audio",this.hls.config.preferManagedMediaSource)},r.isVideoSupported=function(e){return xe(e,"video",this.hls.config.preferManagedMediaSource)},r.filterAndSortMediaOptions=function(e,t,r,i,s){var n=this,a=[],o=[],l=e;if((r||i)&&s&&(l=l.filter((function(e){var t,r=e.videoCodec,i=e.videoRange,s=e.width,n=e.height;return(!!r||!(!s||!n))&&!!(t=i)&&ze.indexOf(t)>-1}))),0!==l.length){t.audioTracks&&_s(a=t.audioTracks.filter((function(e){return!e.audioCodec||n.isAudioSupported(e.audioCodec)}))),t.subtitles&&_s(o=t.subtitles);var h=l.slice(0);l.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(r&&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 ze.indexOf(e.videoRange)-ze.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=Fe(e.videoCodec),s=Fe(t.videoCodec);if(i!==s)return s-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var n=Be(e.codecSet),a=Be(t.codecSet);if(n!==a)return a-n}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var u=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==h.length)for(var d=0;d<h.length;d++)if(h[d].pathwayId===l[0].pathwayId){u=h[d];break}this._levels=l;for(var c=0;c<l.length;c++)if(l[c]===u){var f;this._firstLevel=c;var g=u.bitrate,p=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+l.length+" level(s) found, first bitrate: "+g),void 0===(null==(f=this.hls.userConfig)?void 0:f.abrEwmaDefaultEstimate)){var m=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);m>p&&p===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=m)}break}var v=s&&!i,y=this.hls.config,E=!(!y.audioStreamController||!y.audioTrackController),S={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:i,altAudio:E&&!v&&a.some((function(e){return!!e.url}))};this.hls.trigger(P.MANIFEST_PARSED,S)}else Promise.resolve().then((function(){if(n.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: "+Je(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,r){return r.indexOf(e)===t}))),n.warn(r),e+=" ("+r+")");var i=new Error(e);n.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}}))},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===I&&t.context.level===this.level&&this.checkRetry(t)},r.onFragBuffered=function(e,t){var r=t.frag;if(void 0!==r&&r.type===k){var i=r.elementaryStreams;if(!Object.keys(i).some((function(e){return!!i[e]})))return;var s=this._levels[r.level];null!=s&&s.loadError&&(this.log("Resetting level error count of "+s.loadError+" on frag buffered"),s.loadError=0)}},r.onLevelLoaded=function(e,t){var r,i,s=t.level,n=t.details,a=t.levelInfo;if(!a)return this.warn("Invalid level index "+s),void(null!=(i=t.deliveryDirectives)&&i.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!=(r=t.deliveryDirectives)&&r.skip&&(n.deltaUpdateFailed=!0)},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=this.getUrlWithDirectives(t.uri,r),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==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(n?" Pathway "+n:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+i),this.hls.trigger(P.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})},r.removeLevel=function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter((function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));nr(i),this._levels=i,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=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(P.LEVELS_UPDATED,{levels:i})}},r.onLevelsUpdated=function(e,t){var r=t.levels;this._levels=r},r.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(P.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))},i(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 r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(P.ERROR,{type:R.OTHER_ERROR,details:A.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)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(P.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(),r=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=r}}},{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)}}])}(Ss);function _s(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var Ls=[];function bs(e,t,r){if(!((i=t.remuxResult).audio||i.video||i.text||i.id3||i.initSegment))return!1;var i,s=[],n=t.remuxResult,a=n.audio,o=n.video;return a&&Rs(s,a),o&&Rs(s,o),e.postMessage({event:"transmuxComplete",data:t,instanceNo:r},s),!0}function Rs(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function As(e,t,r,i){t.reduce((function(t,r){return bs(e,r,i)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0],instanceNo:i}),e.postMessage({event:"flush",data:r,instanceNo:i})}function Ps(e,t,r){self.postMessage({event:e,data:t,instanceNo:r})}void 0!==r&&r&&self.addEventListener("message",(function(e){var t=e.data,r=t.instanceNo;if(void 0!==r){var i=Ls[r];if("reset"===t.cmd&&(delete Ls[t.resetNo],i&&i.destroy(),t.cmd="init"),"init"===t.cmd){var s=JSON.parse(t.config),n=new E;n.on(P.FRAG_DECRYPTED,Ps),n.on(P.ERROR,Ps);var a=W(s.debug,t.id);return function(e,t){var r=function(r){e[r]=function(e){Ps("workerLog",{logType:r,message:e},t)}};for(var i in e)r(i)}(a,r),Ls[r]=new Ii(n,t.typeSupported,s,"",t.id,a),void Ps("init",null,r)}if(i)switch(t.cmd){case"configure":i.configure(t.config);break;case"demux":var o=i.push(t.data,t.decryptdata,t.chunkMeta,t.state);Ci(o)?o.then((function(e){bs(self,e,r)})).catch((function(e){Ps(P.ERROR,{instanceNo:r,type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker push error"},r)})):bs(self,o,r);break;case"flush":var l=t.chunkMeta,h=i.flush(l);Ci(h)?h.then((function(e){As(self,e,l,r)})).catch((function(e){Ps(P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker flush error"},r)})):As(self,h,l,r)}}}));var ws="1.6.2",Is={},Ds=0,Cs=function(){function e(e,r,i,s){var n=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ds++,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,r=n.hls;if(r&&null!=t&&t.event&&t.instanceNo===n.instanceNo)switch(t.event){case"init":var i,s=null==(i=n.workerContext)?void 0:i.objectURL;s&&self.URL.revokeObjectURL(s);break;case"transmuxComplete":n.handleTransmuxComplete(t.data);break;case"flush":n.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.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,r.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(P.ERROR,{type:R.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var a=e.config;this.hls=e,this.id=r,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;var o=function(e,t){(t=t||{}).frag=n.frag||void 0,e===P.ERROR&&(t.parent=n.id,t.part=n.part,n.error=t.error),n.hls.trigger(e,t)};this.observer=new E,this.observer.on(P.FRAG_DECRYPTED,o),this.observer.on(P.ERROR,o);var l=Ve(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 "'+r+'"'),this.workerContext=function(e){var t=Is[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Is[e]=i,i}(a.workerPath)):(h.log('injecting Web Worker for "'+r+'"'),this.workerContext=function(){var e=Is[ws];if(e)return e.clientCount++,e;var r=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+t.toString()+")(true);"],{type:"text/javascript"}),i=self.URL.createObjectURL(r),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return Is[ws]=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:r,config:Je(a)})}catch(t){h.warn('Error setting up "'+r+'" Web Worker, fallback to inline',t),this.terminateWorker(),this.error=null,this.transmuxer=new Ii(this.observer,l,a,"",r,e.logger)}}else this.transmuxer=new Ii(this.observer,l,a,"",r,e.logger)}var r=e.prototype;return r.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=Ds++;var t=this.hls.config,r=Ve(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Je(t)})}},r.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=Is[e||ws];if(t&&1==t.clientCount--){var r=t.worker,i=t.objectURL;delete Is[e||ws],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}},r.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},r.push=function(e,t,r,i,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,m=s.decryptdata,v=this.frag,y=!(v&&s.cc===v.cc),E=!(v&&l.level===v.level),S=v?l.sn-v.sn:-1,T=this.part?l.part-this.part.index:-1,_=0===S&&l.id>1&&l.id===(null==v?void 0:v.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 R=!(v&&(null==(u=s.initSegment)?void 0:u.url)===(null==(d=v.initSegment)?void 0:d.url)),A=new Mi(y,L,o,E,p,R);if(!L||y||R){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+s.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===k?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+p+"\n initSegmentChange: "+R);var P=new ki(r,i,t,a,h);this.configureTransmuxer(P)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:A},e instanceof ArrayBuffer?[e]:[]);else if(g){var w=g.push(e,m,l,A);Ci(w)?w.then((function(e){c.handleTransmuxComplete(e)})).catch((function(e){c.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(w)}},r.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var s=i.flush(e);Ci(s)?s.then((function(r){t.handleFlushResult(r,e)})).catch((function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}},r.transmuxerError=function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(P.ERROR,{type:R.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:r}))},r.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},r.configureTransmuxer=function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)},r.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}();function ks(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ms(){if(!De())return!1;var e=ks();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var xs=function(e){function t(t,r,i){var s;return(s=e.call(this,t,r,i,"stream-controller",k)||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)&&(s.log("Media seeked to "+t.toFixed(3)),s.getBufferedFrag(t))){var r=s.getFwdBufferInfoAtPos(e,t,k,0);null!==r&&0!==r.len?s.tick():s.warn("Main forward buffer length at "+t+' on "seeked" event '+(r?r.len:"empty")+")")}},s.registerListeners(),s}o(t,e);var r=t.prototype;return r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(P.MANIFEST_PARSED,this.onManifestParsed,this),t.on(P.LEVEL_LOADING,this.onLevelLoading,this),t.on(P.LEVEL_LOADED,this.onLevelLoaded,this),t.on(P.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(P.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(P.BUFFER_CREATED,this.onBufferCreated,this),t.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(P.FRAG_BUFFERED,this.onFragBuffered,this)},r.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(P.MANIFEST_PARSED,this.onManifestParsed,this),t.off(P.LEVEL_LOADED,this.onLevelLoaded,this),t.off(P.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(P.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(P.BUFFER_CREATED,this.onBufferCreated,this),t.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(P.FRAG_BUFFERED,this.onFragBuffered,this)},r.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},r.startLoad=function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var s=i.startLevel;-1===s&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @"+r.toFixed(3)),e=r),this.state=os.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=os.STOPPED},r.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case os.WAITING_LEVEL:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=os.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=os.IDLE;break}break;case os.FRAG_LOADING_WAITING_RETRY:var s,n=self.performance.now(),a=this.retryDate;if(!a||n>=a||null!=(s=this.media)&&s.seeking){var o=this.levels,l=this.level,h=null==o?void 0:o[l];this.resetStartWhenNotLoaded(h||null),this.state=os.IDLE}}this.state===os.IDLE&&this.doTickIdle(),this.onTickEnd()},r.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()},r.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var s=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[s]){var n=r[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(P.BUFFER_EOS,l),void(this.state=os.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===os.WAITING_LEVEL||this.waitForLive(n))return this.level=s,this.state=os.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&&re(f)&&this.fragmentTracker.getState(f)!==ji){var g,p=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,m=h.fragments[p-1];m&&f.cc===m.cc&&(f=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var v=this.audioOnly&&!this.altAudio?J:Z,y=(v===Z?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,v,k)}f=this.getNextFragmentLoopLoading(f,h,a,k,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,c))}}}}}},r.loadFragment=function(t,r,i){var s=this.fragmentTracker.getState(t);s===Wi||s===qi?re(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,r)):e.prototype.loadFragment.call(this,t,r,i):this._loadInitSegment(t,r):this.clearTrackerIfNeeded(t)},r.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,k)},r.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},r.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},r.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.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;r=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(t.currentTime+r);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)}}}},r.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case os.KEY_LOADING:case os.FRAG_LOADING:case os.FRAG_LOADING_WAITING_RETRY:case os.PARSING:case os.PARSED:this.state=os.IDLE}this.nextLoadPosition=this.getLoadPosition()},r.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,2===this.altAudio?"video":null)},r.onMediaAttached=function(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;hs(i,"playing",this.onMediaPlaying),hs(i,"seeked",this.onMediaSeeked)},r.onMediaDetaching=function(t,r){var i=this.media;i&&(us(i,"playing",this.onMediaPlaying),us(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,e.prototype.onMediaDetaching.call(this,t,r),r.transferMedia||(this._hasEnoughToStart=!1)},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(P.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},r.onManifestParsed=function(e,t){var r,i,s=!1,n=!1;t.levels.forEach((function(e){var t=e.audioCodec;t&&(s=s||-1!==t.indexOf("mp4a.40.2"),n=n||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&n&&!("function"==typeof(null==(i=ks())||null==(r=i.prototype)?void 0:r.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},r.onLevelLoading=function(e,t){if(this.levels&&this.state===os.IDLE){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=os.WAITING_LEVEL)}},r.onLevelLoaded=function(e,t){var r,i=this.levels,s=this.startFragRequested,n=t.level,a=t.details,o=a.totalduration;if(i){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!==os.FRAG_LOADING&&this.state!==os.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();var u=0;if(a.live||null!=(r=l.details)&&r.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(P.LEVEL_UPDATED,{details:a,level:n}),this.state===os.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=os.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}else this.warn("Levels were reset while loading level "+n)},r.synchronizeToLiveEdge=function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==i&&r.duration>i&&(s<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&r.readyState<4||s<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState&&(this.warn("Playback: "+s.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+i.toFixed(3)),r.currentTime=i))}}},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,s=e.payload,n=this.levels;if(n){var a=n[r.level];if(a){var o=a.details;if(!o)return this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset"),void this.fragmentTracker.removeFragment(r);var l=a.videoCodec,h=o.PTSKnown||!o.live,u=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Cs(this.hls,k,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,p=new is(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,g),m=this.initPTS[r.cc];c.push(s,u,d,l,r,i,o.totalduration,h,p,m)}else this.warn("Level "+r.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r.onAudioTrackSwitching=function(e,t){var r=this,i=this.hls,s=2===this.altAudio;if(tt(t.url,i))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(),i.once(P.BUFFER_FLUSHED,(function(){var e;null==(e=r.hls)||e.trigger(P.AUDIO_TRACK_SWITCHED,t)})),void i.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(P.AUDIO_TRACK_SWITCHED,t)}},r.onAudioTrackSwitched=function(e,t){var r=tt(t.url,this.hls);if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?2:0,this.tick()},r.onBufferCreated=function(e,t){var r,i,s=t.tracks,n=!1;for(var a in s){var o=s[a];if("main"===o.id){if(i=a,r=o,"video"===a){var l=s[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part,s=r.type===k;if(s){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===os.PARSED&&(this.state=os.IDLE));var n=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),re(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}var a=this.media;a&&(!this._hasEnoughToStart&&mt.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())},r.onError=function(e,t){var r;if(t.fatal)this.state=os.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(k,t);break;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==os.WAITING_LEVEL||(null==(r=t.context)?void 0:r.type)!==I||(this.state=os.IDLE);break;case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.resetLoadingState();break;case A.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},r.onFragLoadEmergencyAborted=function(){this.state=os.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==J||!this.altAudio){var i=(r===Z?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r,k),this.tick())}},r.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},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to "+r+", already seeking at "+t);var i=this.timelineOffset;i&&r&&(r+=i);var s=this.getLevelDetails(),n=mt.getBuffered(e),a=n.length?n.start(0):0,o=a-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);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"),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position "+r+" from current time "+t+" buffer start "+a),e.currentTime=r)}}},r._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},r._loadBitrateTestFrag=function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then((function(e){var i=r.hls,s=null==e?void 0:e.frag;if(s&&!r.fragContextChanged(s)){t.fragmentError=0,r.state=os.IDLE,r.startFragRequested=!1,r.bitrateTest=!1;var n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(P.FRAG_LOADED,e),s.bitrateTest=!1}}))},r._handleTransmuxComplete=function(e){var t,r=this.playlistType,i=this.hls,s=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var o=a.frag,l=a.part,h=a.level,u=s.video,d=s.text,c=s.id3,f=s.initSegment,g=h.details,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=os.PARSING,f){if(null!=f&&f.tracks){var m=o.initSegment||o;this._bufferInitSegment(h,f.tracks,m,n),i.trigger(P.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:r,tracks:f.tracks})}var v=f.initPTS,y=f.timescale;_(v)&&(this.initPTS[o.cc]={baseTime:v,timescale:y},i.trigger(P.INIT_PTS_FOUND,{frag:o,id:r,initPTS:v,timescale:y}))}if(u&&g){p&&"audiovideo"===u.type&&this.logMuxedErr(o);var E=g.fragments[o.sn-1-g.startSN],S=o.sn===g.startSN,T=!E||o.cc>E.cc;if(!1!==s.independent){var L=u.startPTS,b=u.endPTS,R=u.startDTS,A=u.endDTS;if(l)l.elementaryStreams[u.type]={startPTS:L,endPTS:b,startDTS:R,endDTS:A};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!T&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),I=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:L;if(!S&&I<D-this.config.maxBufferHole&&!T)return void this.backtrack(o);T&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,b,o.start,A,!0)}else S&&L-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,L,b,R,A),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,S||T)}else{if(!S&&!T)return void this.backtrack(o);o.gap=!0}}if(p){var C=p.startPTS,k=p.endPTS,M=p.startDTS,x=p.endDTS;l&&(l.elementaryStreams[J]={startPTS:C,endPTS:k,startDTS:M,endDTS:x}),o.setElementaryStreamInfo(J,C,k,M,x),this.bufferFragmentData(p,o,l,n)}if(g&&null!=c&&null!=(t=c.samples)&&t.length){var O={id:r,frag:o,details:g,samples:c.samples};i.trigger(P.FRAG_PARSING_METADATA,O)}if(g&&d){var N={id:r,frag:o,details:g,samples:d.samples};i.trigger(P.FRAG_PARSING_USERDATA,N)}}}else this.resetWhenMissingContext(n)},r.logMuxedErr=function(e){this.warn((re(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},r._bufferInitSegment=function(e,t,r,i){var s=this;if(this.state===os.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var n=t.audio,a=t.video,o=t.audiovideo;if(n){var l=He(n.codec,e.audioCodec);"mp4a"===l&&(l="mp4a.40.5");var h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var u=n.metadata;u&&"channelCount"in u&&1!==(u.channelCount||1)&&-1===h.indexOf("firefox")&&(l="mp4a.40.5")}l&&-1!==l.indexOf("mp4a.40.5")&&-1!==h.indexOf("android")&&"audio/mpeg"!==n.container&&(l="mp4a.40.2",this.log("Android: force audio codec to "+l)),e.audioCodec&&e.audioCodec!==l&&this.log('Swapping manifest audio codec "'+e.audioCodec+'" for "'+l+'"'),n.levelCodec=l,n.id=k,this.log("Init audio buffer, container:"+n.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(e.audioCodec||"")+"/"+n.codec+"]"),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=k;var d=a.codec;if(4===(null==d?void 0:d.length))switch(d){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||"")+"/"+d+"]"+(a.codec!==d?" 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 c=Object.keys(t);if(c.length){if(this.hls.trigger(P.BUFFER_CODECS,t),!this.hls)return;c.forEach((function(e){var n=t[e].initSegment;null!=n&&n.byteLength&&s.hls.trigger(P.BUFFER_APPENDING,{type:e,data:n,frag:r,part:null,chunkMeta:i,parent:r.type})}))}this.tickImmediate()}},r.getMainFwdBufferInfo=function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,k)},r.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=os.IDLE},r.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(mt.isBuffered(e,r)?t=this.getAppendedFrag(r):mt.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,s=t.level;i&&t.sn===i.sn&&i.level===s||(this.fragPlaying=t,this.hls.trigger(P.FRAG_CHANGED,{frag:t}),i&&i.level===s||this.hls.trigger(P.LEVEL_SWITCHED,{level:s}))}}},i(t,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.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)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(_(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?nt(null,r.fragments,t):null);if(i){var s=i.programDateTime;if(null!==s){var n=s+1e3*(t-i.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}}])}(ls),Os=function(){function e(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}var t=e.prototype;return t.abort=function(e){for(var t in this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}},t.detach=function(){for(var e in this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}},t.destroy=function(){for(var e in this.detach(),this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}},t.createKeyLoadError=function(e,t,r,i,s){return void 0===t&&(t=A.KEY_LOAD_ERROR),new ts({type:R.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:i})},t.loadClear=function(e,t){var r=this;if(this.emeController&&this.config.emeEnabled)for(var i=e.sn,s=e.cc,n=function(){var e=t[a];if(s<=e.cc&&("initSegment"===i||"initSegment"===e.sn||i<e.sn))return r.emeController.selectKeySystemFormat(e).then((function(t){e.setKeyFormat(t)})),1},a=0;a<t.length&&!n();a++);},t.load=function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(r){return t.loadInternal(e,r)})):this.loadInternal(e)},t.loadInternal=function(e,t){var r,i;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");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,l=this.keyUriToKeyInfo[a];if(null!=(r=l)&&r.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(null!=(i=l)&&i.keyLoadPromise)switch(null==(o=l.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return l.keyLoadPromise.then((function(t){return s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:l}}))}switch(l=this.keyUriToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":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+'"')))}},t.loadKeyEME=function(e,t){var r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i=this.emeController.loadKey(r);if(i)return(e.keyLoadPromise=i.then((function(t){return e.mediaKeySessionContext=t,r}))).catch((function(t){throw e.keyLoadPromise=null,t}))}return Promise.resolve(r)},t.loadKeyHTTP=function(e,t){var r=this,i=this.config,s=new(0,i.loader)(i);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=i.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,t,i,s){var o=i.frag,l=i.keyInfo,h=i.url;if(!o.decryptdata||l!==r.keyUriToKeyInfo[h])return a(r.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,i,s,n){r.resetLoader(i),a(r.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,i,s){r.resetLoader(i),a(r.createKeyLoadError(t,A.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:function(e,i,s){r.resetLoader(i),a(r.createKeyLoadError(t,A.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,h,d)}))},t.resetLoader=function(e){var t=e.frag,r=e.keyInfo,i=e.url,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[i],s&&s.destroy()},e}();function Ns(e){switch(e.type){case D:return M;case C:return x;default:return k}}function Fs(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var Bs=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(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(P.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(P.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,s=new(r||i)(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 r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:w,url:r,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var r=t.id,i=t.level,s=t.pathwayId,n=t.url,a=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:s,responseType:"text",type:I,url:n,deliveryDirectives:a,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var r=t.id,i=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:D,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onSubtitleTrackLoading=function(e,t){var r=t.id,i=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:C,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onLevelsUpdated=function(e,t){var r=this.loaders[I];if(r){var i=r.context;i&&!t.levels.some((function(e){return e===i.levelOrTrack}))&&(r.abort(),delete this.loaders[I])}},t.load=function(e){var t,r,i,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(r=e.type===w?a.manifestLoadPolicy.default:n({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),o=this.createInternalLoader(e),_(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===I&&null!==e.level?i=this.hls.levels[e.level].details:e.type===D&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===C&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var u=i.partTarget,d=i.targetduration;if(u&&d){var c=1e3*Math.max(3*u,.8*d);r=n({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}var f=r.errorRetry||r.timeoutRetry||{},g={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},p={onSuccess:function(e,t,r,i){var n=s.getInternalLoader(r);s.resetInternalLoader(r.type);var a=e.data;0===a.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Bt.isMediaPlaylist(a)||r.type!==w?s.handleTrackOrLevelPlaylist(e,t,r,i||null,n):s.handleMasterPlaylist(e,t,r,i)):s.handleManifestParsingError(e,r,new Error("no EXTM3U delimiter"),i||null,t)},onError:function(e,t,r,i){s.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){s.handleNetworkError(t,r,!0,void 0,e)}};o.load(e,g,p)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,s=e.forceStartLoad;(r||s)&&(this.hls.logger.log((r?"auto":"force")+" startLoad with configured startPosition "+i),this.hls.startLoad(i))}},t.handleMasterPlaylist=function(e,t,r,i){var s=this.hls,n=e.data,a=Fs(e,r),o=Bt.parseMasterPlaylist(n,a);if(o.playlistParsingError)this.handleManifestParsingError(e,r,o.playlistParsingError,i,t);else{var l=o.contentSteering,h=o.levels,u=o.sessionData,d=o.sessionKeys,c=o.startTimeOffset,f=o.variableList;this.variableList=f;var g=Bt.parseMasterPlaylistMedia(n,a,o),p=g.AUDIO,m=void 0===p?[]:p,v=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];m.length&&(m.some((function(e){return!e.url}))||!h[0].audioCodec||h[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 At({}),bitrate:0,url:""}))),s.trigger(P.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:v,captions:y,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:c,variableList:f})}},t.handleTrackOrLevelPlaylist=function(e,t,r,i,s){var n=this.hls,a=r.id,o=r.level,l=r.type,h=Fs(e,r),u=_(o)?o:_(a)?a:0,d=Ns(r),c=Bt.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===w){var f={attrs:new At({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=t.loading.start+tr(c,0),n.trigger(P.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=c,this.handlePlaylistLoaded(c,e,t,r,i,s)},t.handleManifestParsingError=function(e,t,r,i,s){this.hls.trigger(P.ERROR,{type:R.NETWORK_ERROR,details:A.MANIFEST_PARSING_ERROR,fatal:t.type===w,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:s})},t.handleNetworkError=function(e,t,r,i,s){void 0===r&&(r=!1);var n="A network "+(r?"timeout":"error"+(i?" (status "+i.code+")":""))+" occurred while loading "+e.type;e.type===I?n+=": "+e.level+" id: "+e.id:e.type!==D&&e.type!==C||(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 w:o=r?A.MANIFEST_LOAD_TIMEOUT:A.MANIFEST_LOAD_ERROR,l=!0;break;case I:o=r?A.LEVEL_LOAD_TIMEOUT:A.LEVEL_LOAD_ERROR,l=!1;break;case D:o=r?A.AUDIO_TRACK_LOAD_TIMEOUT:A.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case C:o=r?A.SUBTITLE_TRACK_LOAD_TIMEOUT:A.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);var d={type:R.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(i){var c=(null==t?void 0:t.url)||e.url;d.response=u({url:c,data:void 0},i)}this.hls.trigger(P.ERROR,d)},t.handlePlaylistLoaded=function(e,t,r,i,s,n){var a=this.hls,o=i.type,l=i.level,h=i.id,u=i.groupId,d=i.deliveryDirectives,c=Fs(t,i),f=Ns(i),g="number"==typeof i.level&&f===k?l:void 0;if(e.fragments.length){e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));var p=e.playlistParsingError;if(p){if(this.hls.logger.warn(p),!a.config.ignorePlaylistParsingErrors)return void a.trigger(P.ERROR,{type:R.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:p,reason:p.message,response:t,context:i,level:g,parent:f,networkDetails:s,stats:r});e.playlistParsingError=null}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case w:case I:a.trigger(P.LEVEL_LOADED,{details:e,levelInfo:i.levelOrTrack||a.levels[0],level:g||0,id:h||0,stats:r,networkDetails:s,deliveryDirectives:d,withoutMultiVariant:o===w});break;case D:a.trigger(P.AUDIO_TRACK_LOADED,{details:e,track:i.levelOrTrack,id:h||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:d});break;case C:a.trigger(P.SUBTITLE_TRACK_LOADED,{details:e,track:i.levelOrTrack,id:h||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:d})}}else{var m=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(P.ERROR,{type:R.NETWORK_ERROR,details:A.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:t,context:i,level:g,parent:f,networkDetails:s,stats:r})}},e}(),Us={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Gs={};var $s=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 E,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 r=this.logger=W(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(e,t,r){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 i=Hi(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(r){var s=e+"Loading"+r,l=t[s];if(void 0!==l&&a){o.push(s);var h=i[n].default;switch(t[n]={default:h},r){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&&r.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+n+'": '+Je(t[n]))})),u(u({},i),t)}(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&function(e,t){var r=e.loader;r!==Oi&&r!==Ui?(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=Oi,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,r);var s=i.abrController,n=i.bufferController,a=i.capLevelController,o=i.errorController,l=i.fpsController,h=new o(this),d=this.abrController=new s(this),c=new zi(this),f=i.interstitialsController,g=f?this.interstitialsController=new f(this,e):null,p=this.bufferController=new n(this,c),m=this.capLevelController=new a(this),v=new l(this),y=new Bs(this),S=i.contentSteeringController,T=S?new S(this):null,_=this.levelController=new Ts(this,T),L=new ys(this),b=new Os(this.config),R=this.streamController=new xs(this,c,b),A=this.gapController=new ds(this,c);m.setStreamController(R),v.setStreamController(R);var w=[y,_,R];g&&w.splice(1,0,g),T&&w.splice(1,0,T),this.networkControllers=w;var I=[d,p,A,m,v,L,c];this.audioTrackController=this.createController(i.audioTrackController,w);var D=i.audioStreamController;D&&w.push(this.audioStreamController=new D(this,c,b)),this.subtitleTrackController=this.createController(i.subtitleTrackController,w);var C=i.subtitleStreamController;C&&w.push(this.subtititleStreamController=new C(this,c,b)),this.createController(i.timelineController,I),b.emeController=this.emeController=this.createController(i.emeController,I),this.cmcdController=this.createController(i.cmcdController,I),this.latencyController=this.createController(Es,I),this.coreComponents=I,w.push(h);var k=h.onErrorOut;"function"==typeof k&&this.on(P.ERROR,k,h),this.on(P.MANIFEST_LOADED,y.onManifestLoaded,y)}e.isMSESupported=function(){return Ms()},e.isSupported=function(){return function(){if(!Ms())return!1;var e=De();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(Ne(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Ne(t,"audio"))})))}()},e.getMediaSource=function(){return De()};var t=e.prototype;return t.createController=function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null},t.on=function(e,t,r){void 0===r&&(r=this),this._emitter.on(e,t,r)},t.once=function(e,t,r){void 0===r&&(r=this),this._emitter.once(e,t,r)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,r,i){void 0===r&&(r=this),this._emitter.off(e,t,r,i)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,r){return this._emitter.emit(e,t,r)},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 r=e===P.ERROR;this.trigger(P.ERROR,{type:R.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:r,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(P.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(P.ERROR,{type:R.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 r="media"in e,i=r?e.media:e,s=r?e:{media:i};this._media=i,this.trigger(P.MEDIA_ATTACHING,s)}},t.detachMedia=function(){this.logger.log("detachMedia"),this.trigger(P.MEDIA_DETACHING,{}),this._media=null},t.transferMedia=function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(P.MEDIA_DETACHING,{transferMedia:e}),e},t.loadSource=function(e){this.stopLoad();var t=this.media,r=this._url,i=this._url=T.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+i),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(P.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 r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);},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),function(e,t,r){var i=e.videoCodec,s=e.audioCodec;if(!i&&!s||!r)return Promise.resolve(Us);var n=[];if(i){var a={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},o=e.videoRange;"SDR"!==o&&(a.transferFunction=o.toLowerCase());var l=i.split(","),h=navigator.userAgent;if(l.some((function(e){return Ae(e)}))&&Ce())return Promise.resolve(function(e,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:e}}(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: ("+h+")"),n));n.push.apply(n,l.map((function(e){return{type:"media-source",video:u(u({},a),{},{contentType:Ne(We(e),"video")})}})))}return s&&e.audioGroups&&e.audioGroups.forEach((function(e){var r;e&&(null==(r=t.groups[e])||r.tracks.forEach((function(t){if(t.groupId===e){var r=t.channels||"",i=parseFloat(r);_(i)&&i>2&&n.push.apply(n,s.split(",").map((function(e){return{type:"media-source",audio:{contentType:Ne(e,"audio"),channels:""+i}}})))}})))})),Promise.all(n.map((function(e){var t=function(e){var t=e.audio,r=e.video,i=r||t;if(i){var s=qe(i.contentType);if(r)return"r"+r.height+"x"+r.width+"f"+Math.ceil(r.framerate)+(r.transferFunction||"sd")+"_"+s+"_"+Math.ceil(r.bitrate/1e5);if(t)return"c"+t.channels+(t.spatialRendering?"s":"n")+"_"+s}return""}(e);return Gs[t]||(Gs[t]=r.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}}))}(e,et(t),navigator.mediaCapabilities)},i(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={})[k]=this.streamController.inFlightFrag,e);return this.audioStreamController&&(t[M]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[x]=this.subtititleStreamController.inFlightFrag),t}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/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 je.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 r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var s=e;s--;){var n=t[s].attrs["HDCP-LEVEL"];if(n&&n<=i)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 ws}},{key:"Events",get:function(){return P}},{key:"MetadataSchema",get:function(){return Mr}},{key:"ErrorTypes",get:function(){return R}},{key:"ErrorDetails",get:function(){return A}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:$i},set:function(t){e.defaultConfig=t}}])}();return $s.defaultConfig=void 0,$s},e.exports=i()}(!1)},424:(e,t)=>{"use strict";t.h=s;var r=2147483647;function i(e){if(e>r)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,r){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,r)}function n(e,t,r){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 r=0|u(e,t),n=i(r),a=n.write(e,t);a!==r&&(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(v(e,ArrayBuffer)||e&&v(e.buffer,ArrayBuffer))return function(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r);return i.__proto__=s.prototype,i}(e,t,r);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,r);var a=function(e){if(s.isBuffer(e)){var t=0|h(e.length),r=i(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?i(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,r);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),i(e<0?0:0|h(e))}function l(e){for(var t=e.length<0?0:0|h(e.length),r=i(t),s=0;s<t;s+=1)r[s]=255&e[s];return r}function h(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function u(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||v(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 r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return m(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;default:if(n)return i?-1:m(e).length;t=(""+t).toLowerCase(),n=!0}}function d(e,t,r,i){r=Number(r)||0;const s=e.length-r;i?(i=Number(i))>s&&(i=s):i=s;const n=t.length;let a;for(i>n/2&&(i=n/2),a=0;a<i;++a){const i=parseInt(t.substr(2*a,2),16);if(y(i))return a;e[r+a]=i}return a}function c(e,t,r,i){return p(m(t,e.length-r),e,r,i)}function f(e,t,r,i){return p(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function g(e,t,r,i){return p(function(e,t){let r,i,s;const n=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)r=e.charCodeAt(a),i=r>>8,s=r%256,n.push(s),n.push(i);return n}(t,e.length-r),e,r,i)}function p(e,t,r,i){let s;for(s=0;s<i&&!(s+r>=t.length||s>=e.length);++s)t[s+r]=e[s];return s}function m(e,t){var r;t=t||1/0;for(var i=e.length,s=null,n=[],a=0;a<i;++a){if((r=e.charCodeAt(a))>55295&&r<57344){if(!s){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(a+1===i){(t-=3)>-1&&n.push(239,191,189);continue}s=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),s=r;continue}r=65536+(s-55296<<10|r-56320)}else s&&(t-=3)>-1&&n.push(239,191,189);if(s=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function v(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,r){return n(e,t,r)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,r){return function(e,t,r){return a(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},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 r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var i=s.allocUnsafe(t),n=0;for(r=0;r<e.length;++r){var a=e[r];if(v(a,Uint8Array)&&(a=s.from(a)),!s.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(i,n),n+=a.length}return i},s.byteLength=u,s.prototype._isBuffer=!0,s.prototype.copy=function(e,t,r,i){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);var n=i-r;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,r,i);else if(this===e&&r<t&&t<i)for(var a=n-1;a>=0;--a)e[a+t]=this[a+r];else Uint8Array.prototype.set.call(e,this.subarray(r,i),t);return n},s.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}const s=this.length-t;if((void 0===r||r>s)&&(r=s),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return d(this,e,t,r);case"utf8":case"utf-8":return c(this,e,t,r);case"ascii":case"latin1":case"binary":return f(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}}},832:function(e,t,r){var i;!function(s){"use strict";function n(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function a(e,t,r,i,s,a){return n((o=n(n(t,e),n(i,a)))<<(l=s)|o>>>32-l,r);var o,l}function o(e,t,r,i,s,n,o){return a(t&r|~t&i,e,t,s,n,o)}function l(e,t,r,i,s,n,o){return a(t&i|r&~i,e,t,s,n,o)}function h(e,t,r,i,s,n,o){return a(t^r^i,e,t,s,n,o)}function u(e,t,r,i,s,n,o){return a(r^(t|~i),e,t,s,n,o)}function d(e,t){var r,i,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(r=0;r<e.length;r+=16)i=c,s=f,a=g,d=p,c=o(c,f,g,p,e[r],7,-680876936),p=o(p,c,f,g,e[r+1],12,-389564586),g=o(g,p,c,f,e[r+2],17,606105819),f=o(f,g,p,c,e[r+3],22,-1044525330),c=o(c,f,g,p,e[r+4],7,-176418897),p=o(p,c,f,g,e[r+5],12,1200080426),g=o(g,p,c,f,e[r+6],17,-1473231341),f=o(f,g,p,c,e[r+7],22,-45705983),c=o(c,f,g,p,e[r+8],7,1770035416),p=o(p,c,f,g,e[r+9],12,-1958414417),g=o(g,p,c,f,e[r+10],17,-42063),f=o(f,g,p,c,e[r+11],22,-1990404162),c=o(c,f,g,p,e[r+12],7,1804603682),p=o(p,c,f,g,e[r+13],12,-40341101),g=o(g,p,c,f,e[r+14],17,-1502002290),c=l(c,f=o(f,g,p,c,e[r+15],22,1236535329),g,p,e[r+1],5,-165796510),p=l(p,c,f,g,e[r+6],9,-1069501632),g=l(g,p,c,f,e[r+11],14,643717713),f=l(f,g,p,c,e[r],20,-373897302),c=l(c,f,g,p,e[r+5],5,-701558691),p=l(p,c,f,g,e[r+10],9,38016083),g=l(g,p,c,f,e[r+15],14,-660478335),f=l(f,g,p,c,e[r+4],20,-405537848),c=l(c,f,g,p,e[r+9],5,568446438),p=l(p,c,f,g,e[r+14],9,-1019803690),g=l(g,p,c,f,e[r+3],14,-187363961),f=l(f,g,p,c,e[r+8],20,1163531501),c=l(c,f,g,p,e[r+13],5,-1444681467),p=l(p,c,f,g,e[r+2],9,-51403784),g=l(g,p,c,f,e[r+7],14,1735328473),c=h(c,f=l(f,g,p,c,e[r+12],20,-1926607734),g,p,e[r+5],4,-378558),p=h(p,c,f,g,e[r+8],11,-2022574463),g=h(g,p,c,f,e[r+11],16,1839030562),f=h(f,g,p,c,e[r+14],23,-35309556),c=h(c,f,g,p,e[r+1],4,-1530992060),p=h(p,c,f,g,e[r+4],11,1272893353),g=h(g,p,c,f,e[r+7],16,-155497632),f=h(f,g,p,c,e[r+10],23,-1094730640),c=h(c,f,g,p,e[r+13],4,681279174),p=h(p,c,f,g,e[r],11,-358537222),g=h(g,p,c,f,e[r+3],16,-722521979),f=h(f,g,p,c,e[r+6],23,76029189),c=h(c,f,g,p,e[r+9],4,-640364487),p=h(p,c,f,g,e[r+12],11,-421815835),g=h(g,p,c,f,e[r+15],16,530742520),c=u(c,f=h(f,g,p,c,e[r+2],23,-995338651),g,p,e[r],6,-198630844),p=u(p,c,f,g,e[r+7],10,1126891415),g=u(g,p,c,f,e[r+14],15,-1416354905),f=u(f,g,p,c,e[r+5],21,-57434055),c=u(c,f,g,p,e[r+12],6,1700485571),p=u(p,c,f,g,e[r+3],10,-1894986606),g=u(g,p,c,f,e[r+10],15,-1051523),f=u(f,g,p,c,e[r+1],21,-2054922799),c=u(c,f,g,p,e[r+8],6,1873313359),p=u(p,c,f,g,e[r+15],10,-30611744),g=u(g,p,c,f,e[r+6],15,-1560198380),f=u(f,g,p,c,e[r+13],21,1309151649),c=u(c,f,g,p,e[r+4],6,-145523070),p=u(p,c,f,g,e[r+11],10,-1120210379),g=u(g,p,c,f,e[r+2],15,718787259),f=u(f,g,p,c,e[r+9],21,-343485551),c=n(c,i),f=n(f,s),g=n(g,a),p=n(p,d);return[c,f,g,p]}function c(e){var t,r="",i=32*e.length;for(t=0;t<i;t+=8)r+=String.fromCharCode(e[t>>5]>>>t%32&255);return r}function f(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var i=8*e.length;for(t=0;t<i;t+=8)r[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return r}function g(e){var t,r,i="0123456789abcdef",s="";for(r=0;r<e.length;r+=1)t=e.charCodeAt(r),s+=i.charAt(t>>>4&15)+i.charAt(15&t);return s}function p(e){return unescape(encodeURIComponent(e))}function m(e){return function(e){return c(d(f(e),8*e.length))}(p(e))}function v(e,t){return function(e,t){var r,i,s=f(e),n=[],a=[];for(n[15]=a[15]=void 0,s.length>16&&(s=d(s,8*e.length)),r=0;r<16;r+=1)n[r]=909522486^s[r],a[r]=1549556828^s[r];return i=d(n.concat(f(t)),512+8*t.length),c(d(a.concat(i),640))}(p(e),p(t))}function y(e,t,r){return t?r?v(t,e):g(v(t,e)):r?m(e):g(m(e))}void 0===(i=function(){return y}.call(t,r,t,e))||(e.exports=i)}()},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var r={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[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 r.isAndroid()||r.isAndroidWebView()?t.ANDROID_WEB:r.isIOS()||r.isIpad()||r.isIOSWebView()?t.IOS_WEB:r.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!n(s("os "))&&!n(s("android[/ ]"))},isIOS:function(){return n(s("os "))},isIpad:function(){return i().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(i())},isMobile:function(){return r.isAndroid()||r.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=i();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=i();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return r.isAndroidWebView()||r.isIOSWebView()},device:t,getBrowser:function(){return r.isX5()?"X5":r.isAndroidWebView()?"Android-WebView":r.isIOSWebView()?"iOS-WebView":r.isChrome()?"Chrome":r.isFirefox()?"Firefox":r.isIpadSafari()?"iPad-Safari":r.isIOSSafari()?"iPhone-Safari":r.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function s(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=r}},t={};function r(i){var s=t[i];if(void 0!==s)return s.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,r),n.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};return(()=>{"use strict";r.d(i,{default:()=>Fr});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=r(415),n=r.n(s),a=r(424),o=r(558),l=r.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,r){const i=new URL(e);return i.searchParams.append(t,r),i.href}function g(){return Date.parse(new Date)/1e3}function p(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function m(e){return new Promise((t=>setTimeout(t,e)))}function v(){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),r=new a.h(e.byteLength);return t.copy(r),r}function E(){return location.protocol.startsWith("https")}function S(e,t,r){if(e.size<=t)return;const i=[...e.keys()];do{const t=i.shift();r&&r(e.get(t)),e.delete(t)}while(e.size>t)}function T(e,t){if(e.size<=t)return;const r=[...e.values()];do{e.delete(r.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 r=Number(t[0]),i=t[1]?Number(t[1]):-1;return{rangeStart:r,rangeEnd:i>=0?i+1:void 0}}function b(e){return e.split("?")[0]}function R(){let e=new Date,t=e.getHours(),r=e.getMinutes(),i=e.getSeconds(),s=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${s}`}function A(e){return e&&"function"==typeof e}function P(e,t,r,i,s,n){e.sendPartialBuffer(r,i,{from:s,incompletes:n})&&(i.length<r.attachments?function(e,t,r){e.addStreamListener(r,t.remotePeerId,((e,r,i,s,n)=>{i?t.sendMsgPieceAbort(s,r,!0):t.uploading&&t.send(s),n&&(t.uploading=!1)}))}(t,e,!!r.reverse):e.uploading=!1)}const w=e=>0===p(0,1)?[null,e]:[e,null];function I(e,t,r){return 1===e.length?t.length>=1&&r.length>=1?t[0].weight>r[0].weight?[t[0],e[0]]:[e[0],r[0]]:t.length>=1?[t[0],e[0]]:r.length>=1?[e[0],r[0]]:w(e[0]):[t.length>=1?t[0]:null,r.length>=1?r[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 C(e){if(crypto.subtle)try{const t=await crypto.subtle.digest("SHA-256",e),r=String.fromCharCode.apply(null,new Uint8Array(t));return btoa(r)}catch(e){}}class k{constructor(e,t){this.target=t,this.type=e}}class M extends k{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class x extends k{constructor(e=1e3,t="",r){super("close",r),this.code=e,this.reason=t,this.wasClean=!0}}const O=()=>{if("undefined"!=typeof WebSocket)return WebSocket},N={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1};class F{constructor(e,t,r={}){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=r,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 F.CONNECTING}get OPEN(){return F.OPEN}get CLOSING(){return F.CLOSING}get CLOSED(){return F.CLOSED}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?F.CLOSED:F.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=N.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 r of t)this._callEventListener(e,r);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=N.reconnectionDelayGrowFactor,minReconnectionDelay:t=N.minReconnectionDelay,maxReconnectionDelay:r=N.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=t*Math.pow(e,this._retryCount-1),i>r&&(i=r)),i}_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=N.maxRetries,connectionTimeout:t=N.connectionTimeout,WebSocket:r=O()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(i=r)||!i||2!==i.CLOSING)throw Error("No valid WebSocket class provided");var i;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new r(e,this._protocols):new r(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 x(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=N.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,r,i){this.wsAddr=`${e}?app=${t}&id=${r}&v=${i}`,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 F(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const r=B[e];this._ws.send(JSON.stringify({records:[{level:r,text:`${R()}: ${t}`}]}))}sendBatch(e){const t=[];for(let r of e)t.push({level:B[r.levelKey],text:r.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}},$=(e,t,r)=>{((e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)})(e,{value:t,duration:r,startTime:Date.now()})},H={debug:0,info:1,warn:2,error:3,none:4};const W=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 H||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in H)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:`${R()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,r,i,s=5e3){this.reportUrl&&!this.reporter&&(e&&this.logCache.unshift({levelKey:"info",message:e}),this.reporter=new U(this.reportUrl,t,r,i),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 H){const r=this[t];this[t]=i=>{e(t,i),r(i)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in H)H[e]<H[this.logLevel]?this[e]=d:this[e]=console[e]}get isDebugLevel(){return H[this.logLevel]<=2||this.onlineDebug}};let V;const q="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(V||(V=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),j=65536;function z(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class K extends(n()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||K.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},K.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=v(),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 q((()=>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 r;!t.address||t.address.endsWith(".local")?(r="Ignoring unsupported ICE candidate.",console.warn(r)):(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,q((()=>{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,q((()=>{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=j),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>j}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=z(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=z(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((r=>{const i=[];r.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((r=>{if(this.destroyed)return;const i=[];r.result().forEach((e=>{const r={};e.names().forEach((t=>{r[t]=e.stat(t)})),r.id=e.id,r.type=e.type,r.timestamp=e.timestamp,i.push(t(r))})),e(null,i)}),(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,r)=>{if(this.destroyed)return;t&&(r=[]);const i={},s={},n={};let a=!1;r.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[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 r=i[e.remoteCandidateId];r&&(r.ip||r.address)?(this.remoteAddress=r.ip||r.address,this.remotePort=Number(r.port)):r&&r.ipAddress?(this.remoteAddress=r.ipAddress,this.remotePort=Number(r.portNumber)):"string"==typeof e.googRemoteAddress&&(r=e.googRemoteAddress.split(":"),this.remoteAddress=r[0],this.remotePort=Number(r[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(r.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>j||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()}}K.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},K.channelConfig={};const Y=K;class X{constructor(e,t,r,i,s=0,n={}){this.sn=e,this.segId=t,this.data=r,this.fromPeerId=i,this.level=s,this.ext=n}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var Q=r(365),J=r.n(Q);class Z extends(n()){static get defaultPacketSize(){return u}static get VERSION(){return"8"}constructor(e,t,r,i,s,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=s,this.isInitiator=i,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,r),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,r){this.remotePeerId=r,this.channelId=this.isInitiator?`${t}-${r}`:`${r}-${t}`,r&&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:r,signalName:i}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${r} signalName ${i}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:r,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,r,i){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${i} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:r,seg_id:i}))))}addStreamListener(e,t,r){this.streamListeners.push({handler:r,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 Y({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let r=!0;(this.connected||this.notFatalClosed)&&(r=!1);let i=t.message;t.debug&&(i=`${i} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,r,i)})),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:r}=this;if("string"==typeof t){let i=JSON.parse(t);if(!i)return void r.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(i);let s,n=i.event;switch(s=n!==e.DC_PLAYLIST&&n!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${n}`,r.debug(`datachannel receive ${s} from ${this.remotePeerId}`),n){case e.DC_HAVE:if(this.emit(i.event,i),!i.sn)return;this.config.live||(i.sn<this.startSN&&(this.startSN=i.sn),i.sn>this.endSN&&(this.endSN=i.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=g(),this.timeReceivePiece=performance.now(),this.pieceMsg=i,this._prepareForBinary(i.attachments,i.seg_id,i.sn,i.size),this.emit(i.event,i);break;case e.DC_PIECE_CANCEL:r.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(i.event,i),this.sendMsgPieceAbort("transfer canceled",i.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(i.event,i);break;case e.DC_REQUEST:this._handleRequestMsg(i);break;case e.DC_PIECE_ACK:this._handlePieceAck(i.seg_id,i.size,i.miss);break;case e.DC_STATS:this._handleStats(i);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(i);break;case e.DC_METADATA:this._handleMetadata(i);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,i)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:r.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:r.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(i.event,i.fatal||!1);break;default:this.emit(i.event,i)}}else{if(!t)return void r.error("datachannel on data is undefined!");if(!this.downloading){const i=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return r.warn(i),void this.emit(e.DC_ERROR,!1,i)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,r)=>{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 r=JSON.stringify(t);return r.length>u?(this.logger.error("string to send is too large"),!1):this.send(r,!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 r=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,r)}return!1}sendMsgHave(t,r,i={}){const s=i.reverse||void 0;delete i.reverse,this.sendJson({event:s?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:r,...i})}sendPieceNotFound(t,r,i={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:r||void 0,sn:t,...i})}sendPeers(t){this.sendJson({event:e.DC_PEERS,peers:t})}sendPeersRequest(){this.sendJson({event:e.DC_GET_PEERS})}sendMsgStats(t,r={}){const i={event:e.DC_STATS,total_conns:t,...r};this.sendJson(i)}sendMsgPlaylist(t,r,i){const s=this.playlistMap.get(t);if(s&&s.seq>=i)return;const n={event:e.DC_PLAYLIST,url:t,data:r,seq:i};this.playlistMap.set(t,{data:r,seq:i}),this.sendJson(n)}sendMsgSignal(t,r,i){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:r,data:i})}sendMsgSignalReject(t,r,i,s=!1){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:r,reason:i,fatal:s})}sendMetaData(t,r,i,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.15.5",sequential:r,peers:i,region:s})}sendPartialBuffer(e,t,r={}){if(!this.sendMsgPiece(e,r))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 r={...e,ext:t};return this.sendJson(r)}sendBuffer(t,r,i,s={}){const n=s.reverse||void 0;if(delete s.reverse,!i)return void this.logger.error("sendBuffer payload is undefined!");let a=i.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:r,sn:t,level:s.level,size:a,reverse:n};if(delete s.level,!this.sendMsgPiece(h,s))return;const u=function(e,t,r,i){let s=[];if(i){let n;for(let i=0;i<r-1;i++)n=e.slice(i*t,(i+1)*t),s.push(n);n=e.slice(e.byteLength-i,e.byteLength),s.push(n)}else{let i;for(let n=0;n<r;n++)i=e.slice(n*t,(n+1)*t),s.push(i)}return s}(i,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,r,i=!1,s={}){const n={event:e.DC_REQUEST,seg_id:t,sn:r,...s,urgent:i};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${t} in queue`),i?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}requestDataBySN(t,r=!1,i={}){const s={event:e.DC_REQUEST,sn:t,...i,urgent:r};this.downloading?(this.logger.info(`add req ${t} in queue`),r?this.sendReqQueue.unshift(s):this.sendReqQueue.push(s)):this._realRequestData(s)}_sendBufferArray(e,t=!1){const r=t?e.reverse():e;for(let e=0;e<r.length;e++)this.send(r[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:r}=t;r(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 r={event:e.DC_CLOSE,fatal:t};this.sendJson(r),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:r,reverse:i}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let s=i?this.remainAttachments+1:r-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:r}=e;r(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(i)}}_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:r,seq:i}=e;this.playlistMap.set(t,{data:r,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const r=this.playlistMap.get(e);return r.seq<=t||r.seq>t+2?null:r}_handleMetadata(t){const{logger:r}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,r.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const i=t.channel;if(this.channel!==i){const t=`peer channel ${i} not matched!`;return r.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){r.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:i}=this.config;if(i&&t.token!==i)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,r.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,r.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,r,i){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(r/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),i>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${i}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:r})}_prepareForBinary(e,t,r,i){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=r,this.expectedSize=i}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let r=a.h.concat(this.bufArr);const i=r.byteLength;if(i===this.expectedSize){let t=r.buffer;const i=new X(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,i,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${i}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,r=performance.now()-this.timeSendRequest;if((e||!(r<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,r,i=!1){const s=this.datasToSend.length;if(!i&&!this.uploading&&0===s)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(r,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 re={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class ie 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,r=()=>{this.curTsUri&&function(e,t,r,i=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=i,n.onreadystatechange=e=>{if(4===n.readyState){const e=n.status;206===e||200===e&&t?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),r&&r(n,e),n.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((i=>{e.httpRangeSupported=!1,t&&t.warn(i),this.rangeRequestTimer=setTimeout(r,6e4)})).finally((()=>{t&&t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(r,0)}initLogger(){const{config:e}=this;e.showSlogan&&"en"==("zh-CN"===(navigator.language||navigator.userLanguage)?"cn":"en")&&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 W(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 A(t)?(r,i)=>`${e}-${t(r,i)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,r=`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:i}=t;if(i){let s;"object"==typeof i?(i.main||(i.main=r),s=i.main):"string"==typeof i&&(s=i,t.wsSignalerAddr={main:s}),s===r&&(s=void 0),s&&!t.wsSignalerAddr.backup&&(e=l().parseURL(s).netLoc.substring(2))}else t.wsSignalerAddr={main:r,byDefault:!0};return e}get commonBrowserInfo(){const e=J().getPlatform(),t=J().getNetType()||"wifi";this.netType=t;const{main:r,backup:i,byDefault:s}=this.config.wsSignalerAddr||{};return{signal:r,custom_signal:!s||void 0,signal2:i,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",r=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,r)};e?self.removeEventListener(t,r):self.addEventListener(t,r)}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 ie.version}static isSupported(){const e=v();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,r){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${r}`);let i=4;return t<=2?i=1.5:t<=3?i=2:t<=4?i=2.5:t<=5?i=3:t<=6&&(i=3.5),i}emitEvent(e,...t){this.emit(e,...t);const r=re[e];r&&A(this.config[r])&&this.config[r](...t)}}ie.version="2.15.5",ie.protocolVersion=ee.VERSION;const se=ie;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 r;if(e&&("string"==typeof e?(r=document.querySelector(e),oe(r)||(r=function(e){const t=document.getElementById(e);if(oe(t))return t;if(!t)return null;const r=t.getElementsByTagName("*");for(let e=0;e<r.length;e++)if(oe(r[e]))return r[e];return null}(e))):e instanceof HTMLMediaElement&&(r=e)),!r){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?r=e[0]:(t&&(r=e.find((e=>e.src===t))),r||(r=e.find((e=>e.currentTime>0))))}return r}function oe(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function le(e,t,r,i=0,s=0){const n=u;let a=i,o=s||r-1;const l=Math.floor(r/n),h=r%n>0?l+1:l;if(e>=0&&(a+=(e+1)*n),t>=0&&t<h){o-=r%n+(h-t-1)*n}return{rangeStart:a,rangeEnd:o+1}}function he(e,t){return`${e}-${t}`}function ue(e,t,r,i){let s=r.split("?")[0];return s.startsWith("http")&&(s=s.split("://")[1]),i?`${s}|${i}`:`${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:!0,trickleICE:!0,announceLocation:"eu",trackerZone:void 0,geoIpPreflight:!0,ICEPreflight:!0,useDiskCache:!0,startFromSegmentOffset:3,getStats:function(e,t,r){},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,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)})),r=(i=ge,s="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(s)}),i))));var i,s;return Promise.race([t,r])}const me={};async function ve(e,t,r=!0){const i=me[e]||{};i.promise||(i.promise=new Promise((e=>i.resolve=e)),me[e]=i,Ee(e,t,i.resolve,r));const s=await i.promise;return delete i.promise,s}const ye={};async function Ee(e,t,r,i){if(!ye[e]){const i=indexedDB.open(e);return i.onupgradeneeded=()=>{const e=i.result;t.forEach((t=>{e.createObjectStore(t)}))},void r(ye[e]=await pe(i))}if(i)try{t.forEach((t=>{ye[e].transaction(t)})),r(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,r,i)}else r(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,r=Te()){return r("readwrite",(r=>(r.put(t,e),pe(r.transaction))))}function be(e,t=Te()){return t("readwrite",(t=>(t.delete(e),pe(t.transaction))))}function Re(e=Te()){return e("readwrite",(e=>(e.clear(),pe(e.transaction))))}function Ae(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},pe(e.transaction)}const Pe="size";class we 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 r=e.browserInfo.device;this.isPC=r===J().device.PC_WEB||r===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 r=this.stores;let i;try{i=function(e,t){let r=ve(e,t);return t.map((i=>(s,n)=>r.then((a=>{try{const e=a.transaction(i,s).objectStore(i);return n(e)}catch(a){r=ve(e,t),r.then((e=>n(e.transaction(i,s).objectStore(i))))}}))))}(this.channel,r)}catch(e){return void t(e)}this._createStores(i),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return Le(Pe,0,this.metaStore)}currBufSize(){return new Promise((async(t,r)=>{try{const i=await _e(Pe,this.metaStore);if(isNaN(i))return this.engine.emit(e.BM_FATAL_ERROR),void r("size is NaN");t(i)}catch(e){r(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:r}=this;if(_(t.data))return new Promise((i=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),this.countErrors=0,i()})).catch((e=>{this._handleFataError(),e&&(r.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}`)}))),i()}))}));r.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(Pe,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(e){this.destroyed||this.currBufSize().then((t=>{Le(Pe,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){Re(this.segmentsStore),e?this._initMetaStore():Re(this.metaStore),this.overflowed=!1}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const Ie=we;const De=class extends Ie{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((r=>{void 0!==t?_e(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?r(!0):r(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),r(!1)})):r(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let r;try{r=await _e(e,this.id2SnStore)}catch(e){return null}return new Promise((i=>{void 0!==r?_e(r,this.segmentsStore).then((r=>{if(this.countErrors=0,r&&r.length>0){const s=r.find((t=>t.segId===e));if(!s)return void i(null);if(!_(s.data))return t.error(`getSegById ${s.sn} is not buffer`),void i(null);i(s)}else i(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),i(null)})):i(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:r,size:i}=e;return Le(t,r,this.id2SnStore),new Promise(((s,n)=>{_e(r,this.segmentsStore).then((async a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(await this._segmentToCache(e)),Le(r,a,this.segmentsStore).then((()=>{this._increaseBufSize(i),s(e)})).catch((e=>{n(e)}))):s(e):Le(r,[await this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(i),s(e)})).catch((e=>{n(e)}))})).catch((e=>{n(e)}))}))}async _trimDisk(t,r=!1){if(this.isCleared||this.destroyed)return;let i=this.maxBufSize;const{logger:s}=this;r&&(i=t-104857600,i<0&&(i=0)),t<i||(s.warn(`_trimDisk currentSize ${t} upBound ${i}`),function(e=Te()){return e("readonly",(e=>{if(e.getAllKeys)return pe(e.getAllKeys());const t=[];return Ae(e,(e=>t.push(e.key))).then((()=>t))}))}(this.segmentsStore).then((async r=>{const n=r.sort(((e,t)=>e-t));let a=0;do{if(a++>10){s.warn("too much loops in SegmentStore");break}const r=n.shift();if(void 0===r){s.warn("lastSN not found");continue}if(r>=this.loadingSN){s.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const i=n[0],o=await _e(r,this.segmentsStore);if(!o){s.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),be(r,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:r,segId:t.segId,next:i,level:t.level})})),t-=l,s.info(`pop sn ${r} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=i)})))}async _segmentToCache(e){const{ext:t={}}=e;let r=t.hash;r||(r=await C(e.data));const i={data:e.data,level:e.level,segId:e.segId,sn:e.sn,fromPeerId:e.fromPeerId,ext:{}};return r&&(i.ext.hash=r),i}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}Re(this.id2SnStore).catch((e=>{}))}};class Ce extends(n()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const r=e.browserInfo.device;if(this.maxBufSize=r===J().device.PC_WEB||r===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 ke=Ce;const Me=class extends ke{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,r)=>{const i=this.id2Sn.get(e);this._segPool.has(i)?t(this._segPool.get(i).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((r,i)=>{if(!this._segPool.has(t))return void r(null);const s=this._segPool.get(t).find((t=>t.segId===e));r(s||null)}))}getSegIdBySN(e){return new Promise(((t,r)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}async _addSeg(t){const{logger:r}=this,{segId:i,sn:s,size:n,ext:a={}}=t;if(this.id2Sn.set(i,s),a.hash||(a.hash=await C(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){r.error("too much loops in SegmentCache");break}const t=l.shift();if(void 0===t){r.error("lastSN not found");continue}const i=l[0],s=this._segPool.get(t);if(!s){r.error("lastSeg not found");continue}let n=0;s.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(t),s.forEach((r=>{this.id2Sn.delete(r.segId),this.emit(e.BM_LOST,{sn:t,segId:r.segId,next:i,level:r.level})})),r.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 xe=r(832),Oe=r.n(xe);function Ne(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}const Fe=function(e,t,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof t&&(r=t,t=void 0),null!=t&&(r.code=t);try{return Ne(e,r)}catch(t){r.message=e.message,r.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),Ne(new i,r)}};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,$e=432e5,He="TRACKER_EXPT",We="IPAPI_ERROR",Ve="uY2R",qe="LmNv",je="uYnll",ze="bQ==",Ke="Z3o",Ye="aGsuc3d",Xe="hcm1j",Qe="bG91ZC",Je="5uZXQ=",Ze=Symbol("httpDownloaded"),et=Symbol("p2pDownloaded"),tt=Symbol("p2pUploaded");class rt extends(n()){constructor(e,t,r,i,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=Ye+Xe+Qe+Je;break;case"us":n="dXMuaGR0dmNsb3VkLmNvbQ==";break;case"cn":n=Ke+Ve+je+qe+ze;break;default:n="ZXUuaGR0dmNsb3VkLmNvbQ=="}this.engine=e,this.key=t||void 0,Array.isArray(i)&&(i=i[Math.floor(Math.random()*i.length)]),this.baseUrl=i||`https://${self.atob(n)}/v1`,this.channelId=self.btoa(r),this.timestamp=g(),this.health=new Be;const o=l().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,""),function(e,t){function r(e,t,r,i,s){return h(r-219,s)}var i,s,n=e();function a(e,t,r,i,s){return h(s- -994,e)}function o(e,t,r,i,s){return h(i-233,t)}function l(e,t,r,i,s){return h(s-305,r)}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(r(0,0,225,0,216))/5)+-parseInt((i=-180,s=-173,h(s- -181,i)))/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(r(0,0,226,0,216))/12))break;n.push(n.shift())}catch(e){n.push(n.shift())}}(d);function h(e,t){var r=d();return(h=function(e,t){return r[e-=0]})(e,t)}const u=function(e,t,r,i,s,n){let a=location.hostname;a===h(-922- -923,-915)&&n&&(a=n+"."+a);return 13,Oe()(a+"2.15.5"+r+i+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.15.5",v:u,announce:this.announce,k:at(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[et]=0,this[tt]=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,r)=>{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 r=G(Ue);e.info("found local geo data"),t(r)}else fetch(self.atob("aHR0cHM6Ly9wcm8uaXAtYXBpLmNvbS9qc29uP2ZpZWxkcz0yMTgxODI2JmtleT1YT3BpYW5zUmdZeEdUaG8=")).then((e=>e.json())).then((e=>{if("success"!==e.status){const t=new Error(`preflight status ${e.status}`);throw Fe(t,We)}{const r=e.mobile?$e:Ge;$(Ue,e,r),t(e)}})).catch((e=>{r(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(Fe(new Error("request timeout"),We))}),600)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(t.code!==He){const t=G(Ue);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:r,isp:i,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:r,isp:i,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,r)=>{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 Fe(new Error(`server response code is ${e.status}`),He,{retry:t})}return e.json()})).then((e=>{if(!this.engine)throw Fe(new Error("runtime error"),He,{retry:!1});const r=e.data;if(r.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:r}=e.data;throw Fe(new Error(r),He,{retry:t>=5e3})}if(r.info&&console.info(`${r.info}`),r.warn&&console.warn(`${r.warn}`),r.min_conns||(r.min_conns=8),(!r.rejected||r.rejected&&r.share_only)&&r.id&&r.report_interval&&r.peers){if(this.peerId=this.id=r.id,r.report_interval<20&&(r.report_interval=20),this.btStats(r.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&&r.asn){const{country:e,asn:t,mobile:i,isp:s,lat:n,lon:a}=r;this.announceInfo={...this.announceInfo,country:e,asn:t},$(Ue,{countryCode:e,as:`AS${t}`,mobile:i,isp:s,lat:n,lon:a,status:"success"},i?$e:Ge)}t(r)}else this.engine&&(this.engine.p2pEnabled=!1)})).catch((t=>{e.error(`btAnnounce error ${t}`);const i=t.code||He,s=!t.code||t.retry;r(Fe(t,i,{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((r=>{let i;if(i=r?JSON.parse(r):{ret:0,data:{}},-1===i.ret)clearInterval(this.heartbeater),t.error(`${i.data.msg} code ${i.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:r=0,failConns:i=0,rebuffers:s=0,requests:n=0,errsInternalExpt:a=0}=this.lastStats||{};this[Ze]>=e&&(this[Ze]-=e),this[et]>=t&&(this[et]-=t),this[tt]>=r&&(this[tt]-=r),this.failConns>=i&&(this.failConns-=i),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:r}=this.engine,{asn:i,country:s}=this.announceInfo;let n={exclusions:e,asn:i,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((r=>{-1===r.ret?t(r.data.msg):e(r.data)})).catch((e=>{r.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 r=Math.round(e/1024);this[et]+=r,this.totalP2PDownloaded+=r,this.health.recordP2p(r),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",r,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[tt]+=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:r}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:r,p2pDownloadSpeed:this.speed});const{getStats:i}=this.config;A(i)&&i(t,r,e,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let r={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[et])||0,share:Math.round(this[tt])||0,asn:e,country:t},i={};this.engine.getExtraForStats&&(i=this.engine.getExtraForStats()),r=Object.assign({},r,i),this.lastStats=JSON.parse(JSON.stringify(r)),Object.keys(r).forEach((e=>{0===r[e]&&delete r[e]}));const{logger:s}=this.engine;return s.isDebugLevel&&s.info(`report ${JSON.stringify(r)}`),this.exptMsg&&(r.exptMsg="2.15.5 "+this.exptMsg),r}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":at(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const it=rt;function st(e,t){const r=nt();return(st=function(e,t){return r[e-=0]})(e,t)}function nt(){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(nt=function(){return e})()}function at(e){if(!e)return;const t=st(-822- -830,-826);let r="".split("").reverse().join("");const i=t.length;for(let s=0;s<e.length;s++){const n=e.charCodeAt(s)^t.charCodeAt(s%i);r+=String.fromCharCode(n)}return self.btoa(r)}!function(e,t){const r=e();function i(e,t,r,i,s){return st(e-92,s)}function s(e,t,r,i,s){return st(s-930,r)}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,st(n- -999,a)))/5+parseInt(i(94,0,0,0,91))/6+-parseInt(i(93,0,0,0,92))/7+-parseInt(i(102,0,0,0,107))/8)break;r.push(r.shift())}catch(e){r.push(r.shift())}var n,a}(nt);class ot 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 m(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 lt=class{constructor(e,t,r,i="main"){this.logger=e,this.config=t,this.wsAddr=r,this.serverVersion=0,this.pingInterval=95e3,this.name=i,this.normalClosed=!1,this.lastSendTs=performance.now(),this.pollingClient=new ot(e,r);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 F(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 r=JSON.stringify(e);t.push(r)},t.addEventListener("message",(e=>{let t=e.data;const r=JSON.parse(t),i=r.action;if("pong"!==i){if("ver"!==i)return"close"===i?(this.logger.warn(`server close signal ${this.name} reason ${r.reason}`),void this.close()):void(this.onmessage&&this.onmessage(r,this.name));this.serverVersion=r.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 ot(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,r){this._send({action:"debug",details:t,ping:r||void 0,to:e})}sendSignal(e,t){const r={action:"signal",to:e,data:t};this._send(r)}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let r of t)this.sendSignal(e,r)}sendReject(e,t,r){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const i={action:"reject",to:e,reason:t,fatal:r};this._send(i)}_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===F.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)this.onmessage(t,this.name)}}},ht=class{constructor(e,t,r,i){this.logger=e,this.config=t,this.mainAddr=r,this.backupAddr=i,this.mainWS=this._init(r),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(i,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let r=new lt(this.logger,this.config,e,t);return r.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},r.onmessage=e=>{this.onmessage&&this.onmessage(e,r.name)},r.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},r.onerror=e=>{this.onerror&&this.onerror(e)},r}sendSignalBatch(e,t,r){if(r){const i=this._getWSByName(r);i&&i.sendSignalBatch(e,t)}else this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected&&this.backupWS.sendSignalBatch(e,t)}sendSignal(e,t,r){this.sendSignalBatch(e,[t],r)}sendReject(e,t,r,i){if(i){const s=this._getWSByName(i);if(s)return void s.sendReject(e,t,r)}this.mainConnected?this.mainWS.sendReject(e,t,r):this.backupConnected?this.backupWS.sendReject(e,t,r):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,r){this.mainConnected&&this.mainWS.sendDebug(e,t,r)}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 ut=function(e,t,r=40){var i=null,s=!1,n=r;return function(r=!1){if(r)return clearTimeout(i),void(s=!1);s||(s=!0,i=setTimeout((function(){e.call(t,n),s=!1,i=null}),1e3*n),n*=1.1)}};class dt{constructor(e,t,r=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=r,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 ct=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,r=0,i="";for(const s of e){if("="===s)break;const e=this.CHARSET.indexOf(s);for(t=t<<this.BITS_PER_BASE64_CHAR|e,r+=this.BITS_PER_BASE64_CHAR;r>=this.BITS_PER_BYTE;){r-=this.BITS_PER_BYTE;i+=(t>>r&(1<<this.BITS_PER_BYTE)-1).toString(16).padStart(2,"0").toUpperCase()}}let s="";for(let e=0;e<i.length;e++)s+=i[e],e%2==1&&e!==i.length-1&&(s+=":");return s}},ft="typ host",gt="generation 0",pt="network-cost",mt="rport",vt="0.0.0.0",yt={V:"v=",O:"o=",S:"s=",C:"c=",A:"a=",M:"m=",T:"t="},Et={U:"ice-ufrag:",P:"ice-pwd:",F:"fingerprint:",C:"candidate:",S:"sctp-port:",M:"max-message-size:"},St={1:"sha-1",2:"sha-224",3:"sha-256",4:"sha-384",5:"sha-512",6:"md5",7:"md2",8:"token"},Tt={P:`${ft} ${gt} ${pt} 999`,W:`${mt} 0 ${gt} ${pt} 999`,H:ft,S:"typ srflx",R:mt,A:"raddr",V:vt,F:"ufrag",G:`${mt} 0 ${gt}`,N:pt,E:"network-id",C:"tcptype active",Q:`${gt}`,U:"udp",T:"tcp"},_t={P:"application",U:"UDP/DTLS/SCTP",S:"DTLS/SCTP",D:"webrtc-datachannel"},Lt={4:"IP4",6:"IP6"},bt={0:vt},Rt=e=>(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in Tt&&(e=Tt[e]),e))).join(" "));function At(e,t){let r=e.split("~"),i=[];r=r.map((e=>{let t=e.slice(0,1),r=e.slice(1);if(t in yt&&(t=yt[t]),"a="===t){let e=r.slice(0,1);const t=r.slice(1);e in Et&&(e=Et[e],r=e+t)}return t+r})),i.push("v=0"),i.push("s=-"),i.push("t=0 0"),i.push("a=msid-semantic: WMS");let s=0;r.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),r=[];r.push("-");const s=t.shift();if(s&&r.push(s),0===t.length)r.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&r.push(e),0===t.length)r.push("IN IP4 127.0.0.1");else{r.push("IN");const e=t.shift();e&&r.push(e);const i=t.shift();i&&r.push(i)}}i.splice(1,0,`o=${r.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(Pt,(e=>_t[e]))}(e),i.push(e),i.push("a=setup:"+(t?"actpass":"active")),i.push(`a=mid:${s}`),void s++;if(e.startsWith("a=candidate:"))return e=Rt(e),void i.push(e);if(e.startsWith("a=fingerprint:")){let[t,r]=e.slice(14).split(" ");return t in St&&(t=St[t]),r=ct.decode(r),void i.push(`a=fingerprint:${t} ${r}`)}if(e.startsWith("c=")){let[t,r]=e.slice(2).split(" ");return t in Lt&&(t=Lt[t]),r in bt&&(r=bt[r]),void i.push(`c=IN ${t} ${r}`)}"I"!==e?"Z"!==e?"B"!==e?i.push(e):i.push("a=sendrecv"):i.push("a=ice-options:ice2,trickle"):i.push("a=ice-options:trickle")}}));const n=i.length-1;return i.splice(n,0,`a=group:BUNDLE ${Array.from(Array(s).keys()).join(" ")}`),i.join("\r\n")}const Pt=new RegExp(Object.keys(_t).join("|"),"g");class wt extends(n()){constructor(e,t,r,i){super(),this.engine=e,this.logger=e.logger,this.config=i,this.connected=!1,this.scheduler=r,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set;const s=J().isMobile();this.peerPool=new dt(e,i,15),this.signalerWs=null,this.fetcher=t,this.peers=[],this.requestPeersQueue=[],this.minConns=5,this.stuns=[],this.requestMorePeers=ut(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:r,fetcher:i}=this,{btAnnounce:s,btAnnouncePreflight:n}=i,{wsSignalerAddr:a,wifiOnly:o,geoIpPreflight:l}=r;(l?n:s).call(i).then((e=>{const{scheduler:r}=this;if(!r)return;t.peerId=this.peerId=e.id,this.minConns=e.min_conns,r.minConns=this.minConns;const s=e.peers;r.notifyPeersLoaded(s.length),s.length>this.gotSignalFails.limit&&(this.gotSignalFails.limit=s.length),t.netType=i.announceInfo.netType,(e.wifi_only||o)&&t.isMobileNet&&(r.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.15.5"),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((r=>{if(this.scheduler&&("TRACKER_EXPT"===r.code&&t.emitEvent(e.EXCEPTION,r),this.scheduler.notifyPeersLoaded(0),r.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 r=t.intermediator;this.signalerWs.connected||r&&this.DCMap.has(r)?(e.debug(`create DataChannel ${t.id} intermediator ${r}`),this._createDatachannel(t.id,!0,r)):e.info(`skip peer ${t.id} without intermediator`)}else e.info("no peers after filter")}_handleSendSignal(e,t){const r=e.remotePeerId;if(e.intermediator){const i=this.DCMap.get(e.intermediator);if(i){let s=!0;for(let e of t)i.sendMsgSignal(r,this.peerId,e)||(s=!1);if(s)return;this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,this.signalerWs.sendSignalBatch(r,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 r=e.to_peer_id||e.to,i=e.from_peer_id||e.from,s=e.action;if(r&&i&&s)if(r!==this.peerId){this.logger.info(`relay signal for ${i}`);const n=this.DCMap.get(r);if(n){if("signal"!==s)return void n.sendMsgSignalReject(r,i,e.reason,e.fatal);if(n.sendMsgSignal(r,i,e.data))return}t.sendMsgSignal(i,r)}else"signal"===s?this._handleSignalMsg(i,e,t.remotePeerId):this._handSignalRejected(i,e)})).on(e.DC_GET_PEERS,(()=>{const e=g(),r=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?15:22)&&!e.super));if(r&&r.length>0){const i=[];r.forEach((r=>{if(r.remotePeerId===t.remotePeerId||r.remotePeerId===this.peerId)return;if(!this.config.live&&(r.currentPos-t.currentPos>600||r.currentPos<t.currentPos))return;e-r.timeJoin>50&&i.push({id:r.remotePeerId,...r.region})})),this.logger.info(`send ${i.length} peers to ${t.remotePeerId}`),t.sendPeers(i)}})).on(e.DC_PEERS,(e=>{const r=e.peers;this.logger.info(`receive ${r.length} peers from ${t.remotePeerId}`),r&&r.length>0&&(r.forEach((e=>{e.intermediator=t.remotePeerId,e.region||(e.region={})})),this.requestPeersQueue.push(...r)),this.requestPeersWaitCount--,this.requestPeersWaitCount<=0&&this._handleRequestedPeers()})).once(e.DC_ERROR,((e,r)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${r}`),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 ${r}`),this._doSignalFusing(this.scheduler.peersNum),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:r,data:i})=>{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))),r&&e&&h&&(this.failedDCMap.set(o,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!e&&h&&!l&&this._tryBackupSignal(t,o,i))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:r}=this;t.isInitiator||r.handshakePeer(t),r.handleMetaData(t,e);const i=this.DCMap.size>=this.maxConnsActive;this.requestMorePeers(i),t.intermediator&&this.peersIncrement++,this._doSignalFusing(r.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,r,i,s){const n=(e,t)=>{let r=`${e}?id=${this.peerId}&p=web&v=2.15.5`;return this.config.signalCompact&&(r=`${r}&c=1`),t&&(r=`${r}&token=${t}`),r};let a,o=n(t,i);if(r&&r!==t){let e=n(r,s);a=new ht(this.logger,this.config,o,e)}else a=new lt(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this.engine.emitEvent("serverConnected",!0),this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let r=e.action;const i=e.from_peer_id||e.from;if(i)switch(r){case"signal":this._handleSignalMsg(i,e,null,t);break;case"reject":this._handSignalRejected(i,e);break;default:this.logger.warn(`Signal websocket unknown action ${r}`)}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,Fe(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const r=`signaling ${e} rejected`;this.logger.warn(`${r}, reason ${t.reason}`);const i=this.DCMap.get(e);i&&!i.connected&&(i.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,r),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,r,i="main"){return!(!(this.signalerWs.backupConnected&&e&&r.length>0&&"main"===i)||e.useBackupSignal)&&(e.useBackupSignal=!0,e.signalName="backup",e.intermediator=void 0,this.signalerWs.sendSignalBatch(t,r,"backup"),!0)}_handleSignalMsg(e,t,r,i){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"}`,r,i,!0);this._handleSignal(e,t.data,r,i)}else{const t=this.DCMap.get(e);if(!t)return;if(this._tryBackupSignal(t,e,t.signalMsgs,i))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(),r||this.notFoundDCSet.add(e)}}_handleSignal(e,t,r,i){let s=t;"string"==typeof s?s=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:Rt(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),r="O"===e[0];return{type:r?"offer":"answer",sdp:At(t,r)}})(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,r)}}else{if("answer"===n){const t=`${e} type wrong ${n}`;return a.warn(t),this._sendSignalReject(e,t,r,i),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,r,i)}o=this._createDatachannel(e,!1,r)}o&&(i&&(o.signalName=i),o.receiveSignal(s,t))}_createDatachannel(e,t,r){if(!this.fetcher)return;let i;if(t&&this.peerPool.available)i=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${i.signalMsgs.length}`),i.intermediator=r,i.assignPeerId(this.peerId,e);else{let s=this.config.trickleICE;this.overloaded&&(s=!1),i=new ee(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:r,trickle:!r&&s})}return this.DCMap.set(e,i),this._setupDC(i),i}_sendSignalReject(e,t,r,i,s){if(r){const i=this.DCMap.get(r);if(i&&i.sendMsgSignalReject(e,this.peerId,t,s))return}this.signalerWs.sendReject(e,t,s,i)}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this,r=this.scheduler.peersNum;r>=this.maxConnsActive||(t.info(`requestMorePeers after delay ${e}, peersIncrement ${this.peersIncrement}`),r<3||r<this.minConns&&this.peersIncrement<=3&&!this.gotPeersFromTracker?this._requestPeersFromServer(r):this._requestPeersFromPeers(r)||this._requestPeersFromServer(r),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 r=[],i=new Set;for(let t of e)i.has(t.id)||(i.add(t.id),r.push(t));const{asn:s,country:n}=t;if(!s||!n||r.length<2)return r;const a=r.filter((e=>!e.asn&&!e.country)),o=r.filter((e=>e.country===n&&e.asn!==s)),l=r.filter((e=>e.asn===s&&e.country===n)),h=r.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 r=this.DCMap.get(e);return!!r&&(r.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=g();for(let t of this.DCMap.values()){const r=e-t.timeJoin;e-t.timeJoin>30&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${r} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}}const It=wt;class Dt 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,r=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(r=this.makeChannelId(e,t));return{channelIdMaker:r,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:r,config:i}=this;if(self.indexedDB&&i.useDiskCache&&!i.live){const e=new De(this,i);try{await e.setupStore(),this.bufMgr=e}catch(e){r.warn(e),this.bufMgr=new Me(this,i)}}else this.bufMgr=new Me(this,i);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,(()=>{r.warn("SegmentStoreFatalError, switch to SegmentCache"),this.bufMgr.destroy(),this.bufMgr=new Me(this,i),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,r){const{logger:i,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()}})),r.live||this.media&&(r.pos=Math.round(this.media.currentTime)),r.tag=void 0===s.tag?this.generateTag():s.tag;let n=new it(this,s.token,encodeURIComponent(e),s.announce||"",r);this.fetcher=n,this.tracker=new It(this,n,t,s),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?ue:he)}_onHlsError(e,r){if(!r||!this.hlsjs)return;const{logger:i,tracker:s}=this;if(!i)return;const n=`${r.type} details ${r.details} reason ${r.reason}`;if(r.fatal?i.error(n):i.warn(n),"networkError"===r.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:a}=this.browserInfo,o=`${a||""} hlsjs ${this.hlsjsVersion} ${location.href}`,l=this.hlsjs.constructor.ErrorDetails;switch(r.details){case l.BUFFER_STALLED_ERROR:if("HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),s&&s.scheduler){const e=s.scheduler;i.warn(`buffered: ${1e3*e.getBufferedDuration()} fragLoading ${e.fragLoading} isCritical ${e.isCritical()}`)}break;case l.INTERNAL_EXCEPTION:if(r.event&&"demuxerWorker"!==r.event){r.error||(r.error={});const e=`${r.error.message} event ${r.event} ${o}`;this.fetcher&&r.fatal&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=e),i.error(`INTERNAL_EXCEPTION event ${r.event} err ${r.error.message}`),this.emitEvent(t.EXCEPTION,Fe(r.error,"HLSJS_EXPT")),i.report(e,r.event,this.peerId,"2.15.5")}break;default:if(r.fatal||r.details===l.FRAG_PARSING_ERROR){"mediaError"===r.type&&s&&s.scheduler&&s.scheduler.disconnectLoadingPeer().finally((()=>{s.scheduler.clearCache()}));const e=`${r.type} ${r.details} ${r.err||""} ${o}`;i.report(e,r.details,this.peerId,"2.15.5")}}}}class Ct{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 kt{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[kt.ElementaryStreamTypes.AUDIO]:!1,[kt.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 r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new Ct,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}}class Mt{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 xt=/^(\d+)x(\d+)$/,Ot=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class Nt{constructor(e){"string"==typeof e&&(e=Nt.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 r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}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=xt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,r={};for(Ot.lastIndex=0;null!==(t=Ot.exec(e));){let e=t[2],i='"';0===e.indexOf(i)&&e.lastIndexOf(i)===e.length-1&&(e=e.slice(1,-1)),r[t[1]]=e}return r}}const Ft=Nt,Bt={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 Ut=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Gt=/#EXT-X-MEDIA:(.*)/g,$t=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),Ht=/(?:(?:#(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?/,Wt=/\.(mp4|m4s|m4v|m4a)$/i;class Vt{static findGroup(e,t){if(!e)return null;let r=null;for(let i=0;i<e.length;i++){const s=e[i];s.id===t&&(r=s)}return r}static convertAVC1ToAVCOTI(e){let t,r=e.split(".");return r.length>2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let r,i=[];function s(e,t){["video","audio"].forEach((r=>{const i=e.filter((e=>function(e,t){const r=Bt[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)));if(i.length){const s=i.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${r}Codec`]=s.length>0?s[0]:i[0],e=e.filter((e=>-1===i.indexOf(e)))}})),t.unknownCodecs=e}for(Ut.lastIndex=0;null!=(r=Ut.exec(e));){const e={},n=e.attrs=new Ft(r[1]);e.url=Vt.resolve(r[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=Vt.convertAVC1ToAVCOTI(e.videoCodec)),i.push(e)}return i}static parseMasterPlaylistMedia(e,t,r,i=[]){let s,n=[],a=0;for(Gt.lastIndex=0;null!==(s=Gt.exec(e));){const e={},o=new Ft(s[1]);if(o.TYPE===r){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=r,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=Vt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),i.length){const t=Vt.findGroup(i,e.groupId);e.audioCodec=t?t.codec:i[0].codec}e.id=a++,n.push(e)}}return n}static parseLevelPlaylist(e,t){let r,i,s=0,n=0,a=new Mt(t),o=new Ct,l=0,h=null,u=new kt,d=null;for($t.lastIndex=0;null!==(r=$t.exec(e));){const e=r[1];if(e){u.duration=parseFloat(e);const t=(" "+r[2]).slice(1);u.title=t||null,u.tagList.push(t?["INF",e,t]:["INF",e])}else if(r[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=(" "+r[3]).slice(1),qt(u,h),a.fragments.push(u),h=u,n+=u.duration,u=new kt}}else if(r[4]){if(u.rawByteRange=(" "+r[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(u.lastByteRangeEndOffset=e)}}else if(r[5])u.rawProgramDateTime=(" "+r[5]).slice(1),u.tagList.push(["PROGRAM-DATE-TIME",u.rawProgramDateTime]),null===d&&(d=a.fragments.length);else{for(r=r[0].match(Ht),i=1;i<r.length&&void 0===r[i];i++);const e=(" "+r[i+1]).slice(1),n=(" "+r[i+2]).slice(1);switch(r[i]){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 Ft(e),f=c.enumeratedString("METHOD"),g=c.URI,p=c.hexadecimalInteger("IV");f&&(o=new Ct,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 i=new Ft(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(i)&&(a.startTimeOffset=i);break;case"MAP":let h=new Ft(e);u.relurl=h.URI,u.rawByteRange=h.BYTERANGE,u.baseurl=t,u.sn="initSegment",a.initSegment=u,u=new kt,u.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${r}`)}}}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=>Wt.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),u=new kt,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 r=e[t];for(let i=t-1;i>=0;i--){const t=e[i];t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(a.fragments,d),a}}function qt(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 jt={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},zt=(e,t,r,i,s=!1)=>{const[n,a,o]=Kt(e,t,r,i);return s&&n.length>=1?w(n[0]):n.length>=2?[n[0],n[1]]:I(n,a,o)},Kt=(e,t,r,i)=>{const s=[],{COMPLETE:n,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=jt;return[n,a,o].forEach((n=>{s.push(Yt(e,n,t,r,i))})),s},Yt=(e,t,r,i,s)=>e.filter((e=>e.bitset.hasWithId(r,i,s,t)));class Xt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const r=Number(e);if(r<0)continue;const i=new Map;if(t[e])for(let r of t[e])i.set(r,{state:jt.COMPLETE,segId:void 0,size:void 0});this.levelMap.set(r,i)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,r,i=jt.ANY){if(t<0)return!1;const s=this._createOrGetSet(t).get(e);return!!s&&((!r||!s.segId||s.segId===r)&&(i===jt.ANY||s.state===i))}has(e,t,r=jt.ANY){return this.hasWithId(e,t,void 0,r)}hasCompleteOr(e,t,r=jt.COMPLETE){const i=this._createOrGetSet(t).get(e);return!!i&&(i.state===jt.COMPLETE||i.state===r)}getObj(e,t){let r=this._createOrGetSet(t).get(e);return r||(r={}),r}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,r,i,s){if("number"!=typeof(n=e)||n%1!=0)return;var n;this._createOrGetSet(t).set(e,{state:i,segId:r,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,r)=>{e[r]=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[r,i]of e)i.state===jt.COMPLETE&&t.push(r);return t}}class Qt{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 r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);1===t?r.delete(e):r.set(e,t-1)}}incre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);r.set(e,t+1)}else r.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 Jt=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 er extends(n()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Jt,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 r=g();this.getPeers().forEach((i=>{t>this.minConns+1&&(r-i.dataExchangeTs>120||r-i.gotStatsTs>=83)?(this.logger.warn(`close dead peer ${i.remotePeerId} level ${i.currentLevel}`),i.close(!1),t--):i.connected&&i.sendMsgStats(t,e)}))}),4e4)}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}requestPeers(){const e=g();let t=0;for(let r of this.getPeers())r.mobileNet||r.super||(e-r.gotPeersTS<60?this.logger.warn(`${r.remotePeerId} just got peers, ignored`):(r.sendPeersRequest(),r.gotPeersTS=e,t++));return t}chokePeerRequest(t){const r={event:e.DC_CHOKE};t?t.sendJson(r):this._broadcastToPeers(r)}unchokePeerRequest(t){const r={event:e.DC_UNCHOKE};t?t.sendJson(r):this._broadcastToPeers(r)}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 r=this.peerManager.getPeerIds();this._peersStats(r);const{asn:i,country:s}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${s||""} asn ${i||""}, now has ${r.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(),r=t.filter((e=>e.downloading));e.warn(`downloading: ${r.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of r)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:r,level:i})=>{this._broadcastLost(e,t,i),this.onBufferManagerLost(e,t,r,i)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,r,i,s){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:r||void 0,level:i},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:r}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),r.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{r.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 r of this.getPeers())t&&r===t||r.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;A(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(r=this.loadedPeerNum)?3:.5*r+1.67);var r;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const r=this.requestingMap.get(e);if(r)return void r.removeStreamListener(t);const i=this.segmentBuilderMap.get(e);i&&i.removeStreamListener(t)}setTargetPeersFromGroup(e,t,r,i){if(e.hasReversePeer){if((r=t.concat(r)).length>0)return this.targetPeers.forwardPeer=r[0],!0}else if(e.hasForwardPeer&&(i=t.concat(i)).length>0)return this.targetPeers.reversePeer=i[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=I(t,r,i),this.targetPeers.some((e=>!!e)))}}const tr=er;class rr 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 ir=0,sr=1,nr=2,ar=3;class or 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,r)=>{e+=`${r}: ${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 lr=/(\d+)-(\d+)\/(\d+)/;function hr(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class ur{constructor(e){this.fetchSetup=e.fetchSetup||dr,this.xhrSetup=e.xhrSetup,this.controller=new self.AbortController,this.stats=D(),this.packetSize=u,this.fakeXhr=new or}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,r){const i=this.stats;i.trequest=i.loading.start;let s=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal);const n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o=8e3,maxLoadTimeMs:l=2e4}=t.loadPolicy||{},h=r.onUpdate,u=r.onBodyStart;this.context=e,this.config=t,this.callbacks=r,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),s=function(e,t){e.withCredentials&&(t.credentials="include");for(let[r,i]of e.headers)t.headers.set(r,i);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"),r.onTimeout&&r.onTimeout(i,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(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout&&r.onTimeout(i,e,this.response)}),l-(a-i.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new cr(t||"fetch, bad network response",e,s)}i.tfirst=i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=lr.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Number.isFinite(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(s.headers)||i.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"!==i.total?(u&&u(i.total,o),this.loadProgressively(s,i,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),i.tload=i.loading.end=Math.max(performance.now(),i.loading.first);const n=t[a];n&&(i.loaded=i.total=n);const o={url:s.url,data:t,code:s.status};r.onProgress&&r.onProgress(i,e,t,s),r.onSuccess&&r.onSuccess(o,i,e,s)})).catch((t=>{if(clearTimeout(this.requestTimeout),i.aborted)return;const s=t&&t.code||0,n=t?t.message:null;r.onError&&r.onError({code:s,text:n},e,t?t.details:null,i)}))}loadProgressively(e,t,r,i){const s=e.body.getReader();let n=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>s.read().then((({value:r,done:s})=>{const{fakeXhr:c}=this;if(c.readyState!==c.LOADING&&(c.readyState=c.LOADING,c.emit("readystatechange")),r&&(n+=r.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),i(e,!0)}else{const e=function(e,t){const r=e.byteLength-t,i=[];let s=t,n=Math.floor(r/u),o=r%u;for(let t=0;t<n;t++){const t=(0,a.h)(u);e.copy(t,0,s,s+u),i.push(t),s+=u}if(o>0){const t=(0,a.h)(o);e.copy(t,0,s,s+o),i.push(t)}return i}(l,o*this.packetSize);for(let t=0;t<e.length;t++)i(e[t],t===e.length-1)}const t=l.buffer,{fakeXhr:r}=this,{status:s,statusText:h,url:d}=e;return r.readyState=r.DONE,r.responseText=s,r.status=h,r.responseURL=d,r.responseType="arraybuffer",r.response=t,r.emit("readystatechange"),r._emitEvent("load"),r._emitEvent("loadend"),Promise.resolve(t)}if(t.loaded+=r.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,r]),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++,i(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function dr(e,t){return new self.Request(e.url,t)}class cr extends Error{constructor(e,t,r){super(e),this.code=t,this.details=r}}class fr extends(n()){constructor(e,t,r=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=r,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,r=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let i of r){const{handler:r}=i;r(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,r){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:r,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:r}=this.pieceMsg,i=i=>i.filter((i=>i.peerId!==e||(i.handler(t,r,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=i(this.forwardStreamListeners),this.reverseStreamListeners=i(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let r=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-r)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=r+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,r){return t?this.setReversePeer(e,r):this.setForwardPeer(e,r)}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:r,level:i}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(r,i,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(r,i,t),this.reverseCanceled=!0)}detachPeers(){this._detachPeer(this.forwardPeer),this._detachPeer(this.reversePeer)}destroy(){clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),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(){this._cancelP2p(),this.httpLoader&&(this.logger.warn("abort syn httpLoader"),this.httpLoader.abort(),this.httpLoader=void 0)}_detachPeer(t){if(!t)return;const r=t===this.reversePeer?this.reverseEvents:this.forwardEvents;r&&r&&t.off(e.DC_PIECE_DATA,r.onPieceData).off(e.DC_PIECE,r.onPiece).off(e.DC_PIECE_NOT_FOUND,r.onPieceNotFound).off(e.DC_PIECE_ABORT,r.onPieceAbort)}_receivePacket(t,r,i,s=!0){const{seg_id:n,sn:o,level:l,size:h,ext:u}=this.pieceMsg,d=r-1;if(this.bufArr[d]?(this.logger.warn(`syn bufArr ${n} already has ${d} size ${i.byteLength}`),this.bufArr[d]=i):(s?this.p2pLoaded+=i.byteLength:this.httpLoaded+=i.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]=i,t?this.reverseOffset=d:this.forwardOffset=d,this._notifyStreamListeners(t,i,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 r=new X(o,n,t,this.getFromPeerId(),l,u);this.emit(e.SYN_OUTPUT,r,{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,ir),this._disconnectPeers()}}_disconnectPeers(){[this.forwardPeer,this.reversePeer].forEach((t=>{t&&t.emit(e.DC_ERROR,!0)}))}_checkPieceSize(e){const{size:t,seg_id:r,sn:i}=this.pieceMsg;return!e||!t||e===t||(this.logger.warn(`checkPieceSize ${r||i} size not match ${t} ${e}`),!1)}_setupPeer(t,r,i){const{logger:s}=this;0===this.timeStart&&(this.timeStart=performance.now()),i&&!this.pieceMsg.size&&(this.pieceMsg.size=i);const n=(r,i,n,a,o,l)=>{if(this.destroyed)return;if(!this._validateMsg(r,l.level,i))return void s.error(`onPieceData ${i||r} size ${n.byteLength} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(a<this.pieceMsg.attachments&&n.byteLength!==u)return s.error(`${i} dataSn ${a} size is ${n.byteLength}`),this.emit(e.SYN_ERROR,this.pieceMsg,ir),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:r,size:i,sn:n,level:a,seg_id:o,ext:l={}}=e;let h=!0;(i<=999||!this._validateMsg(n,a,o))&&(s.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),h=!1),this._checkPieceSize(i)||(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:i,attachments:r,ext:l},this.reverseOffset=r,this.bufArr=new Array(r),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};r?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,r=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:i,size:s,attachments:n}=this.pieceMsg;if(!s||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${i} url ${this.url}`),void this.emit(e.SYN_ERROR,this.pieceMsg,ir);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(r){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const r=e.currentLoadSpeed(),i=t.currentLoadSpeed();return r===i?e.timeSendRequest-t.timeSendRequest:r-i})).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,ar)}shouldWaitForRemain(e){return!this.isEmpty&&this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed,r=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${r}`),t>=r}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 r,i;return t.length<this.pieceMsg.attachments?(r=this.isFull?"WaitPartialDouble":"WaitPartialSingle",i=1):(r=this.isFull?"SynFullDouble":"SynFullSingle",i=0),{from:r,incompletes:i,bufferList:t}}_loadRemainBufferByHttp(){if(this.rangeRequesting)return;const{size:t,seg_id:r}=this.pieceMsg,{logger:i}=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;i.info(`listeners ${this.streamListeners} continue download ${r} from ${this.url} range: ${o.rangeStart}-${o.rangeEnd}`),this.hasPartialBuffer||(o={});const u=new ur({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,r,s)=>{if(!this.destroyed){if(s)return i.warn("httpLoader aborted"),void(this.alreadyOutput||this.emit(e.SYN_ERROR,this.pieceMsg,sr));if(r){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&&i.warn(`range request fileSize ${s}`),this.destroyed)return;const{size:n}=this.pieceMsg;if(c=t,t!==n||0!==s&&s!==n){let r=!1;s>0&&s!==n?(i.error(`onBodyStart fileSize ${s} != ${n}`),r=!0):t!==l&&(i.error(`onBodyStart size ${t} != expectedSize ${l}`),r=!0),r&&this.emit(e.SYN_ERROR,this.pieceMsg,sr)}else i.warn(`syn range request ${r} resp whole ts`),g=0},onError:t=>{this.destroyed||(i.error(`httpLoader error ${t.text}`),this.emit(e.SYN_ERROR,this.pieceMsg,sr))},onTimeout:()=>{this.destroyed||(i.warn("httpLoader timeout"),this.emit(e.SYN_ERROR,this.pieceMsg,nr))}};u.load(d,{timeout:15e3},p)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class gr extends fr{constructor(e,r,i,s,n,a=!1,o){super(e,r,a,o),this.pieceMsg={event:t.DC_PIECE,sn:i,level:s,seg_id:n},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,r){const{sn:i,seg_id:s,attachments:n}=this.pieceMsg,a=e&&0===r||!e&&r===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:r}=e;r(i,s,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,r){return(!this.pieceMsg.seg_id||r===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}}class pr{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,r,i,s){if(this.meanHttpSpeed<=0)return!1;if(r>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*s>=e)return!1;return((s+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-r)*r<i}_cal(e,t){return.4*e+.6*t}}class mr extends tr{constructor(e,t){super(e,t),this.prefetchOnly=t.prefetchOnly,this.bitset=new Xt(t.live||!1),this.bitCounts=new Qt,this.requestingMap=new rr,this.segmentBuilderMap=new rr,this.allowP2pLimit=t.httpLoadTime+1.5,this.playlistInfo=new Map,this.gotPlaylist=!1,this.targetPeers={},this.sequential=!0,this.coordinator=new pr,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:r}=this.engine.fetcher.announceInfo;e.sendMetaData(this.bitset.allArray(),!0,this.peersNum,{asn:t,country:r},this.isMobileNet)}_receiveDCHave(e,t,r,i){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:r,level:i,complete:s,seg_id:n,size:a}=t,o=s?jt.COMPLETE:jt.PARTIAL_FORWARD;e.bitset.add(r,i,n,o,a),this._receiveDCHave(r,i,n,e),e.isAvailableUrgently&&this._handleDCHave(e,r,i,n,a,o)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:r,level:i,seg_id:s,size:n}=t;e.bitset.hasCompleteOr(r,i,jt.PARTIAL_REVERSE)||e.bitset.add(r,i,s,jt.PARTIAL_REVERSE,n),this._receiveDCHave(r,i,s,e),e.isAvailableUrgently&&this._handleDCHave(e,r,i,s,n,jt.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:r,level:i}=t;e.bitset.has(r,i)&&(e.bitset.delete(r,i),this.bitCounts.decre(r,i))})).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?jt.PARTIAL_REVERSE:jt.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:r,level:i}=t,s=de(r,i);this.removeStreamListener(s,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:r,level:i}=t;e.bitset.delete(r,i),this.bitCounts.decre(r,i),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:r}=this,{sn:i,level:s,reverse:n}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(i));const o=()=>{this.bitset.delete(i,s),e.sendPieceNotFound(i,a,{level:s}),this._broadcastLost(i,a,s,e)},l=await this.bufMgr.getSegById(a),h=de(i,s),u=this.requestingMap.get(h);let d=!1;u&&u.isDownloading&&(d=!0);const c=this.segmentBuilderMap.get(h);if(l)if(r.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)r.info(`peer request ${i} wait from builder, sent ${c.bufferList.length}`),P(e,c,c.pieceMsg,c.bufferList,c.source,1);else if(d){r.info(`syn had ${u.loadedPackets} packets, wait remain from upstream ${u.getFromPeerId()}`);const t={...u.pieceMsg,reverse:n},{from:i,incompletes:s,bufferList:a}=u.getStreamInfo(n);P(e,u,t,a,i,s)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new Xt(this.config.live,t.field);for(let e in t.field){const r=Number(e);if(r<0)continue;t.field[r].forEach((e=>{this.bitset.has(e,r)||this.bitCounts.incre(e,r)}))}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 r=Number(e),i=t[r];i&&i.forEach((e=>{this.bitCounts.decre(e,r)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,r,i){const{logger:s,config:n}=this;let a=1e3*(i-n.httpLoadTime);this.allowP2pLimit=n.httpLoadTime+1.5,s.info(`bufferedDuration ${1e3*i} 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!==r)return s.warn(`syn segId ${n} not match ${r}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,r,i);if(!l.shouldWaitForRemain(a)){if(s.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const i=this.peerManager.getPeersOrderByWeight();let[n,o,h]=Kt(i,e,t,r);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,r,i)}_searchAvailablePeers(e,t,r,i){if(i<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const s=this.peerManager.getPeersOrderByWeight(),[n,a]=zt(s,e,t,r);return this.targetPeers={forwardPeer:n,reversePeer:a},[n,a].some((e=>!!e))}reportTraffic(e,t,r){const{fetcher:i}=this.engine;i&&(e>0&&i.reportFlow(e),t>0&&i.reportDCTraffic(t,r))}notifyAllPeers(e,t,r,i,s=jt.COMPLETE){if(!r)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,r)=>`${e}-${t}-${r}`)(e,t,s);let o;s!==jt.PARTIAL_REVERSE&&(o=s===jt.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,r,{level:t,reverse:s===jt.PARTIAL_REVERSE,complete:o,size:i}),h.notifySet.add(a),n&&T(h.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:r}=this;if(!this.hasPeers)return;const i=t.live;if(this.fragLoading)return void e.info("loading urgently, skip prefetch");const{currentLevel:s}=r;if(0===this.bitCounts.size(s))return;if(!i&&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(!i){const t=this.requestingMap.size,r=this.requestingMap.activePeers;if(r>=o)return void e.warn(`requestingMap size ${t} activePeers ${r}`);o-=r}if(this.getBufferedDuration()<this.allowP2pLimit){if(!i)return;o=1}let u=0,d=this.loadingSN+1;if(this.prefetchOnly&&(d+=2),!i)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&&(i||!(d>l))&&!(i&&d>this.loadingSN+2);){if(this.bitset.has(d,s)){d++;continue}const t=de(d,s),r=this.requestingMap.get(t);if(this.bitCounts.has(d,s)){if(r){for(let e of n)if(e.bitset.has(d,s)){const{state:t,segId:i,size:n}=e.bitset.getObj(d,s);if(this._trySetPeerForSyn(r,e,i,d,s,n,t))break}}else{let r=[null,null];if(i)r=zt(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 i;i=t===jt.COMPLETE?0===p(0,1):t===jt.PARTIAL_REVERSE,r[i?1:0]=e;break}if(r.some((e=>!!e))){const i=new gr(this.coordinator,this.logger,d,s,void 0,this.httpRangeSupported);this._setupSynthesizer(i),this.requestingMap.set(t,i),r.forEach(((t,r)=>{if(t&&a<o){const n=1===r,o=t.bitset.getSize(d,s);i.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,r,i){this.currLostSN=e,r&&(this.nextLostSN=r),this.bitset.delete(e,i),this.bitCounts.delete(e,i)}onBufferManagerSegAdded(e){const{sn:t,segId:r,level:i,size:s}=e;this.notifyAllPeers(t,i,r,s),this.updateLoaded(t,i,r)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[r,i]of this.requestingMap.internalMap){const s=r.split("-"),n=Number(s[1]),a=Number(s[0]);i.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),i.deletePeer(t),this.bitCounts.decre(n,a),t.bitset.delete(n,a))}}updateLoaded(e,t,r){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,r,jt.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 r=function(e){const t=e.split("\n");let r=0,i=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){r=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&i++;return r+i-1}(t);if(!this.isMobileNet)for(let i of this.getPeers())i.sendMsgPlaylist(e,t,r);this.playlistInfo.set(e,{seq:r,data:t})}async getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t,data:r}=this.playlistInfo.get(e),i=()=>{for(let r of this.getPeers()){const i=r.getLatestPlaylist(e,t);if(i)return this.playlistInfo.set(e,i),this.gotPlaylist=!0,i}return null};let s=i();return!s&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await m(240),this.gotPlaylist=!1,s=i()),s}getBufferedDuration(){const{config:e}=this;let{media:t,currentSrc:r}=this.engine;if(!t||t.src!==r&&0===t.currentTime){if(this.logger.info("try get video element"),t=ae(this.config.mediaElem,r),!t)return 4;this.engine.media=t}let i=function(e){let t=0,r=e.currentTime,i=e.buffered;for(let e=i.length-1;e>=0;e--)if(r>=i.start(e)&&r<=i.end(e)){t=i.end(e)-r;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return i}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,r,i,s,n){if(this.logger.info(`syn output ${e} http ${t} p2p ${r} time ${i}`),!this.config.validateSegment(e,new Uint8Array(s)))return!1;if(n){const t=await C(s);if(t&&t!==n)return this.logger.warn(`${e} computedHash ${t} != hash ${n}`),!1}return!0}_handleSynError(e,t,r,i){const{logger:s,config:n}=this;s.warn(`SYN_ERROR ${t}-${r} code ${i}`),i!==ir&&e.hasPartialBuffer&&r>this.loadingSN?s.warn(`syn abort ${r} with partial buffer`):this.requestingMap.delete(de(r,t)),n.live&&this.checkPeers()}_notifySynthesizer(e,t,r,i,s,n,a=!0){const o=this.requestingMap.get(de(r,i));o&&this._trySetPeerForSyn(o,e,t,r,i,s,n,a)}_trySetPeerForSyn(e,t,r,i,s,n,a,o=!1){const{logger:l}=this,h=e.segId;if(r&&h&&r!==h)return l.warn(`notifySynthesizer segId ${r} 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(r,i,!0,{level:s,reverse:e}):t.requestDataBySN(i,!1,{level:s,reverse:e})}function d(){return a===jt.PARTIAL_FORWARD||a===jt.COMPLETE}function c(){return a===jt.PARTIAL_REVERSE||a===jt.COMPLETE}return!1}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:r}=this.config;t||r||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,r={level:e};if(t&&!this.config.live){const{currentTime:e}=t;r.pos=Math.round(e)}return r}checkSynthesizer(e,t){const r=de(e,t),i=this.requestingMap.get(r);i&&(0===i.streamListeners?(this.logger.info(`destroy syn ${r} without listeners`),this.requestingMap.delete(r)):this.logger.info(`keep syn ${r} with listeners`))}setupSynForLoad(e,t,r,i,s){const{forwardPeer:n,reversePeer:a}=this.targetPeers,o=de(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(i):(l=new gr(this.coordinator,this.logger,e,t,r,this.httpRangeSupported,i),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(r,e,!0,{level:t}),a&&l.setReversePeer(a)&&a.requestDataById(r,e,!0,{level:t,reverse:!0})),l.setTimeout(l.isEmpty?0:s,!0)}async disconnectLoadingPeer(e){let t=e;if(!t){const e=await this.bufMgr.getSegById(this.loadingSegId);e&&e.fromPeerId&&(t=e.fromPeerId)}t&&(this.logger.warn(`disconnect loading peer ${t}`),t.split(":").forEach((e=>{const t=this.peerManager.getPeer(e);t&&t.close(!0)})))}}class vr{constructor(t,r,i,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:i,sn:t,level:r,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,r){this.streamListeners.push({handler:r,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:r}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((i=>i.peerId!==e||(i.handler(t,r,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let r of this.streamListeners){const{handler:i}=r;i(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:r}=this.pieceMsg;for(let i of this.streamListeners){const{handler:s}=i;s(t,r,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const yr=/^age:\s*[\d.]+\s*$/im;function Er(e,t,r,i){if(!e)return!1;const s=i&&i.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(s)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,n):n}const Sr=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,r){this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===r&&!this.stats.aborted)return s(r,t.url)})).catch((e=>{if(this.loader===r&&!this.stats.aborted)return r.open("GET",t.url,!0),s(r,t.url)})).then((()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)})).catch((e=>{this.callbacks.onError({code:r.status,text:e.message},t,r,i)})):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=r.loadPolicy;if(i)for(const t in i)e.setRequestHeader(t,i[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),r.timeout=s&&Number.isFinite(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const i=t.readyState,s=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.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-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,n="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const s=n||t.response;if(null!=s){r.loading.end=Math.max(self.performance.now(),r.loading.first);const n="arraybuffer"===t.responseType?s.byteLength:s.length;if(r.loaded=r.total=n,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(r,e,s,t),!this.callbacks)return;const o={url:t.responseURL,data:s,code:i};return void this.callbacks.onSuccess(o,r,e,t)}}const a=s.loadPolicy.errorRetry;Er(a,r.retry,!1,{url:e.url,data:void 0,code:i})?this.retry(a):this.callbacks.onError({code:i,text:t.statusText},e,t,r)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Er(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:r}=this;this.retryDelay=function(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}(e,r.retry),r.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&&yr.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 Tr=class extends mr{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=A(t.segmentBypass)?t.segmentBypass:()=>!1,!0===t.httpStreamEnabled?this.streamEnabled=hr()&&t.live:this.streamEnabled=!1}async handleGetMediaData(e,r){const{logger:i,engine:s,config:n}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return i.warn(`cannot get frag ${a}`),r.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 i.info(`bypass frag ${a}`),r.postMessage({action:t.SW_GET_MEDIA});if(s.segmentLoadCount<n.startFromSegmentOffset)return this._loadFragByHttp(l,r,d,a,o,1e3*this.fragloadTimeout,!1);const c=d===this.loadingSegId;if(c&&(i.warn(`duplicate request ${d}`),this.prefetchOnly))return r.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.data.byteLength,l.fromPeerId=f.fromPeerId,i.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(),r.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:f.data}});if(this.fragLoading=!0,this.prefetchOnly)return i.info(`prefetchOnly, skip p2p load ${d}`),this._loadFragByHttp(l,r,d,a,o,1e3*this.fragloadTimeout);let g=this.getBufferedDuration();g>this.fragloadTimeout&&(g=this.fragloadTimeout),i.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const m=de(h,u);if(this.resolveMap.has(h)||c){let e=this.requestingMap.get(m);if(e||c){e&&this.httpRangeSupported&&(i.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let s=setTimeout((()=>{i.info(`notify seg ${h} timeout`),s=-1,r.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{s<0||e&&e.level===u&&(clearTimeout(s),i.info(`notify seg ${e.sn}`),r.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else i.warn(`${h} is requesting, fallback`),r.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,u,d,g)){await this._loadFragByP2p(l,r,h,d,a,u,o,p)||(i.warn(`p2p timeout switch to http load ${d}`),this._loadFragByHttp(l,r,d,a,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,r,d,a,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,r,i,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 ur(g):new Sr(g);let m={url:c,responseType:"arraybuffer",...L(n)};const v={timeout:a,loadPolicy:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4}},E={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,r.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,r.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 ${i} time ${h} speed ${o.byteLength/h}`),!await this.bufMgr.hasSegOfId(i)){const e=y(o).buffer,t=new X(l,i,e,"",u);await this.bufMgr.putSeg(t),this.reportTraffic(o.byteLength,0,0)}this.segmentBuilderMap.delete(d),e.segId=i,e.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:s,sn:l,level:u,segId:i,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(),r.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,i,t,jt.PARTIAL_FORWARD),e=new vr(l,u,i,t),this.segmentBuilderMap.has(d)||this.segmentBuilderMap.set(d,e))},E.onUpdate=(t,r,s)=>{if(s)return this.logger.warn(`loadFragByHttp ${i} aborted`),void this.segmentBuilderMap.delete(d);e&&e.receiveBytes(t,r)}}p.load(m,v,E)}async _loadFragByP2p(e,r,i,s,n,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${i} segId ${s} level ${a}`);const u=await this.load(i,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(i,s,o,l,a,u.ext);h.info(`bufMgr putSeg ${i} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:n,sn:i,level:a,segId:s,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(),r.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 ${i} segId ${s}`),r.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:d.data}}),!0)}notifySWMessage(e,r,i){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(r,i);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,r,i,s,n){const{logger:a,config:o}=this;let l={...L(s),proxied:!0,url:i,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,r,t,l,n);const h=new Promise((i=>{const s={resolve:i,sn:e,level:r,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,r)=>{const{config:i,logger:s}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:u,time:d,http:c,p2p:f}=r,g=this.resolveMap.has(a);g&&(this.fragLoading=!1);const p=await this._handleSynOutput(n,c,f,d,o,h.hash),m=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?m: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(m)}})).on(t.SYN_ERROR,((t,r)=>{const{sn:i,level:s}=t;if(this.resolveMap.has(i)){const e=this.resolveMap.get(i);this.resolveMap.delete(i),e.resolve()}this._handleSynError(e,s,i,r)}))}_handleDCHave(e,t,r,i,s,n){this._notifySynthesizer(e,i,t,r,s,n,this.resolveMap.has(t)),this.config.live&&q((()=>{this.checkPeers()}))}},_r="2.13.0";class Lr extends Dt{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},r=null){super(e,r),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=Lr.name,Lr.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),r&&(r.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),r.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:i,signalId:s,browserInfo:n}=this.setup();if(this.onLevelLoaded=e=>{const{config:r}=this,a=e.live;r.live=a,this.segmentLoadCount=0,this.targetDuration=e.averagetargetduration,this.browserInfo={...n,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${i(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||(r.startSN=e.startSN,r.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:r,startSN:i}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,r,i)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,r)=>{this.multiBitrate=e.length>1,this.currentSrc=r,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:r,data:i}=e.data;if(!r)return;if(r===t.SW_DEBUG){const{level:e,text:t}=i;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 ${r}`),s.postMessage({action:r,pong:!0}),!this.p2pEnabled||!i)return s.postMessage({action:r});if(r===t.SW_GET_PLAYLIST)this.handleGetPlaylist(i,s);else{if(!this.scheduler)return s.postMessage({action:r});this.scheduler.notifySWMessage(r,i,s)}}else this.logger&&this.logger.error(`sender not found in action ${r}`)}}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 r=null;const i=()=>{r||(r=setTimeout((()=>{t()}),2500))},s=()=>{null!=r&&(clearTimeout(r),r=null)};return e.addEventListener("waiting",i),e.addEventListener("playing",s),()=>{e.removeEventListener("waiting",i),e.removeEventListener("playing",s)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,r,i=!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 r=e.split("."),i=t.split("."),s=0;s<Math.max(r.length,i.length);s++){var n=parseInt(r[s]||0),a=parseInt(i[s]||0);if(n<a)return-1;if(n>a)return 1}return 0}(u,_r)?(console.warn(`hls-proxy.js version should >= ${_r}`),r.postMessage({action:t.SW_GET_PLAYLIST})):this.bypassLevels.indexOf(b(a))>=0?(console.warn("bypass audio track"),n&&n.warn("bypass audio track"),r.postMessage({action:t.SW_GET_PLAYLIST})):(r.postMessage({action:t.SW_GET_PLAYLIST,data:{active:!0,debug:n&&n.isDebugLevel,text:l,redirectedUrl:o}}),this._parsePlaylist(l,b(a),o,i),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!s.live&&t()){const r=new URL(e.scope);this.pathname=r.pathname+h;const i=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;n&&(n.error(t),n.report(t,"SWKeepAlive",this.peerId,"2.15.5"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,r)=>{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=>{r(e)}))}))).catch((e=>{i(e)})):i("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,r,i,s=!1){const n=r;i&&(r=i);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let i=0;const o=Vt.parseLevelPlaylist(e,r);this.levels.length>0?(i=this.levels.indexOf(b(o.url)),-1===i?(this.restartP2p(),this.currentSrc=n,i=0):this.currentLevelIndex=i):(""!==this.currentSrc&&n!==this.currentSrc&&this.restartP2p(),this.currentSrc=n,this.levels=[b(r)]),this.emit(t.LEVEL_LOADED,o),a.live&&S(this.fragMap,200),o.fragments.forEach((e=>{e.level=i;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const r=e.byteRange;2===r.length&&(t=`${t}|bytes=${r[0]}-${r[1]-1}`),this.fragMap.set(t,e)})),!s&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(b(r),e)}else{const i=Vt.parseMasterPlaylist(e,r);""!==this.currentSrc&&this.restartP2p(),i.length>0&&(i.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=i.map((e=>b(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{Vt.parseMasterPlaylistMedia(e,r,t).forEach((e=>{e.url&&this.bypassLevels.push(b(e.url))}))}))),this.emit(t.MANIFEST_PARSED,i,n)}this._setupSegmentId()}async handleGetPlaylist(e,r){const{config:i,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:i,seq:n}=t;return s&&s.info(`got playlist from peer seq ${n}`),void this.handlePlaylist({text:i,...e},r,!0)}}try{const{text:i,redirectedUrl:n}=await this._loadPlaylistByHttp(a);if(!function(e){return 0===e.indexOf("#EXTM3U")}(i))return s&&s.warn(`not m3u8: ${i}`),r.postMessage({action:t.SW_GET_PLAYLIST});this.handlePlaylist({text:i,redirectedUrl:n,...e},r)}catch(e){r.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"),Cr.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,r)=>{const{serviceWorker:i}=navigator;i||r(e),i.getRegistration().then((i=>{i?i.unregister().then(t).catch(r):r(e)}))}))}async _init(e,t){const{logger:r,config:i}=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(i.mediaElem)}),3e3);let s=new Tr(this,i);s.fragMap=this.fragMap;try{await super._init(e,s,t)}catch(e){return void(r&&r.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 It&&(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),r=await fetch(t);return{text:await r.text(),redirectedUrl:r.redirected?r.url:void 0}}}const br=Lr;function Rr(e,t,r="main"){return"main"!==r}function Ar(e,t,r){let i,s,n;const a=performance.now();n=a,s=r?n-r.getMeanTimeToLoaded(t):a-200,i=s-100,e.trequest=i,e.tfirst=s,e.tload=n,e.loading={first:i,start:s,end:n},e.loaded=t,e.total=t}const Pr=class extends mr{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,r){const{logger:i,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=r,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,r)=>{const{config:i,logger:s}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:u,time:d,http:c,p2p:f}=r,g=this.criticalSeg&&this.criticalSeg.segId===n,p=await this._handleSynOutput(n,c,f,d,o,h.hash),m=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=m,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(m)})).on(t.SYN_ERROR,((t,r)=>{const{sn:i,level:s}=t;this.criticalSeg&&this.criticalSeg.sn===i&&(this.criticalSeg=null,this.callbacks.onTimeout({},this.context,null)),this._handleSynError(e,s,i,r)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:r,segId:i})=>{this.criticalSeg&&this.criticalSeg.segId===i&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:r},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:r,level:i})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,r&&this.checkSynthesizer(e,i)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:r,level:i})=>{this.fragLoading=!1,r||this.checkSynthesizer(e,i)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,r,i,s,n){this._notifySynthesizer(e,i,t,r,s,n,this.criticalSeg&&this.criticalSeg.segId===i),this.config.live&&q((()=>{this.checkPeers()}))}};class wr extends Dt{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=wr.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:r,signalId:i,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,r,i,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:r}=this,{fragments:i,averagetargetduration:s,startSN:n}=t.details;r.httpLoadTime=this.determineHttpLoadTime(i,s,n)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,r)=>{this._setupSegmentId();const i=r.levels.length;this.multiBitrate=i>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,r,i,s,n={}){const{config:a}=this;a.live=t,this.browserInfo={...r,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${i(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:r,config:i}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const s=new Pr(this,i);try{await super._init(e,s,t)}catch(e){return void r.error(e)}this.hlsjs.config.fLoader=function(e,t,r,i){const s=i.httpStreamEnabled&&hr()&&i.live;return class extends(n()){constructor(n){super(),this.logger=r,this.isHlsV0=i.isHlsV0,this.bufMgr=e.bufMgr,this.httpLoader=s||this.isHlsV0?new ur(n):new Sr(n),this.p2pEnabled=i.p2pEnabled,this.isLive=i.live,this.scheduler=e,this.fetcher=t,this.segmentId=i.segmentId,this.blockTypes=i.p2pBlackList,this.stats=this.httpLoader.stats||D(),this.enableWorker=n.enableWorker,this.segmentBypass=A(i.segmentBypass)?i.segmentBypass:()=>!1,this.prefetchOnly=i.prefetchOnly,this.startFromSegmentOffset=i.startFromSegmentOffset}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,r){const{logger:i,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,this.httpLoader.load(e,t,r));if(!n||!Number.isInteger(l)||Rr(0,this.blockTypes,h)||this.segmentBypass(n,u))return i.info(`HTTP load blockType ${n}`),c();if(this.fetcher.increMediaRequests(),this.isLive&&s.requestedSet.has(d))return i.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){i.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 Ar(this.stats,g.size,s.coordinator),a.loaded=g.size,a.loadByP2P=!0,a.fromPeerId=g.fromPeerId,void q((()=>{!this.isHlsV0&&r.onProgress&&r.onProgress(this.stats,e,n.data),r.onSuccess(n,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&s.hasAndSetTargetPeer(l,o,d,f)?this.loadFragByP2p(e,t,r,d,f):(i.info(`fragLoader load ${d} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,r,d))}loadFragByHttp(e,t,r,i){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;r.onUpdate=(t,r,s)=>{if(s)return n.warn(`loadFragByHttp ${i} aborted`),void o.delete(d);e&&e.receiveBytes(t,r)},r.onBodyStart=t=>{!e&&t>0&&(e=new vr(h,u,i,t),o.has(d)||o.set(d,e),a.notifyAllPeers(h,u,i,t,jt.PARTIAL_FORWARD))}}const c=r.onSuccess;r.onSuccess=async(e,t,r)=>{a.coordinator.addLoaderHttpSpeed(t.tload-t.tfirst,t.loaded);const{data:s}=e;let l=t.tload-t.trequest;if(n.info(`HTTP loaded ${i} time ${l} speed ${t.total/l}`),!await this.bufMgr.hasSegOfId(i)){const e=y(s).buffer,t=new X(h,i,e,this.fetcher.peerId,u);await this.bufMgr.putSeg(t)}o.delete(d),this.fetcher.reportFlow(t.total),c(e,t,r)};const f=r.onProgress;f&&(r.onProgress=(e,t,r)=>{l.loaded=e.total,f(e,t,r&&this.enableWorker?y(r).buffer:r)}),e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,r)}loadFragByP2p(t,r,i,s,n){const{logger:a}=this,o=t.frag;let l;l=r.loadPolicy?r.loadPolicy.maxTimeToFirstByteMs:r.timeout,(!l||l>1e3*n)&&(l=1e3*n),t.defaultTimeout=l,this.scheduler.load(t,r,i);const h=i.onSuccess,u=i.onTimeout;i.onTimeout=(e,t)=>{a.warn(`P2P timeout switched to HTTP load ${o.relurl} at ${o.sn}`),i.onSuccess=h,this.loadFragByHttp(t,r,i,s),i.onTimeout=u},i.onSuccess=async(t,r,n)=>{const{data:l}=t;if(Ar(r=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(r.total),o.loaded=r.loaded,a.info(`${o.loadByP2P?"P2P":"HTTP"} loaded segment id ${s}`),!this.isHlsV0&&i.onProgress&&i.onProgress(r,n,l),h(t,r,n)}}}}(s,this.fetcher,r,i),i.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,r){return class extends(n()){constructor(i){super(),this.logger=t,this.xhrLoader=new i.loader(i),this.p2pEnabled=r.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||D()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,r){const{logger:i}=this,{url:s}=e,n=b(s),a=r.onSuccess;if(r.onSuccess=(e,t,r)=>{this.scheduler&&!r.loadedByPeer&&this.scheduler.broadcastPlaylist(n,e.data),a(e,t,r)},this.scheduler&&this.scheduler.playlistInfo.has(n)){const t=await this.scheduler.getPlaylistFromPeer(n);if(t&&t.data){const{data:n,seq:a}=t;i.info(`got playlist from peer seq ${a}`),Ar(this.stats,n.length);let o={url:s,data:n};return e.loadedByPeer=!0,void q((()=>{r.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,r)}}}(s,r,i))}_onFragLoading(e,r){const i=r.frag;let{sn:s,level:n,segId:a}=i;if(!Rr(i.url,this.config.p2pBlackList,i.type)&&Number.isInteger(s)){if(this.logger&&this.logger.info("loading frag "+s),this.bufMgr&&(this.bufMgr.loadingSN=s),!a){let e;i._byteRange&&(e="bytes="+i._byteRange[0]+"-"+i._byteRange[1]);let t=i.url;this._setupSegmentId(),a=i.segId=this.config.segmentId(String(n),i.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:s,segId:a,byHttp:i.loadByHTTP,level:n})}}_onLevelUpdated(e,t){const{details:r}=t,{hlsjs:i,config:s}=this,{targetduration:n,live:a,fragments:o}=r,l=o.length;if(a&&i&&"main"===o[0].type&&!(l<=4)&&(s.isHlsV0||!i.userConfig.liveSyncDuration&&!i.userConfig.liveSyncDurationCount)){const e=l<=9?l-1:l-2;i.config.liveSyncDurationCount!==e&&(i.config.liveSyncDurationCount=e)}}_onFragLoaded(e,r){if(this.segmentLoadCount++,!this.p2pEnabled)return;const{frag:i}=r;this.curTsUri=i.url;const{sn:s,segId:n,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:u,url:d}=i,{config:c,logger:f}=this;this.tracker&&this.tracker.scheduler&&(T(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(n)),Rr(i.url,c.p2pBlackList,i.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,r){const{frag:i}=r;if(!Rr(i.url,this.config.p2pBlackList,i.type)){this.logger&&this.logger.info("frag changed: "+i.sn);const{sn:e,duration:r}=i;this.emit(t.FRAG_CHANGED,{sn:e,duration:r})}}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 r=e?"off":"on";t[r](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[r](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[r](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[r](this.HLSEvents.ERROR,this._onHlsError),t[r](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,r=e.ports[0];if(r)return r.postMessage({action:t,pong:!0}),r.postMessage({action:t,data:{bypass:!0}})}}}const Ir=wr;class Dr{static get Events(){return t}static get TrackerZone(){return se.TrackerZone}static isSupported(){return se.isSupported()&&(ne()||br.isServiceWorkerSupported())}static isServiceWorkerSupported(){return br.isServiceWorkerSupported()}static isMSESupported(){return ne()}static getBrowser(){return J().getBrowser()}static get ServiceWorkerEngine(){return br}static get HlsjsEngine(){return Ir}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return Dr.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:r}={}){const{serviceWorker:i}=navigator;return!i||r?Promise.resolve():i.getRegistration().then((r=>r||Promise.race([i.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,r)=>{const i=e.installing||e.waiting||e.active,s=()=>"activated"===i.state&&(i.removeEventListener("statechange",s),t(e),!0);s()||i.addEventListener("statechange",s)}))}(e))).catch((()=>{Promise.resolve()})),m(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const r=()=>{this._realEngine=new Ir(t,e)},i=()=>{this._realEngine=new br(e,t)};"1"!==c("_sw")?e.proxyFirst&&t?br.isServiceWorkerSupported()?i():r():!e.proxyOnly&&ne()&&t?r():i():i()}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 A(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return A(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return se.version}}Dr.version=se.version,Dr.protocolVersion=ee.VERSION,"object"==typeof self&&(self.P2PEngineHls=Dr);const Cr=Dr;var kr=r(917),Mr=r.n(kr);const xr={maxBufferLength:12},Or={maxBufferLength:40};class Nr extends(Mr()){static get P2PEvents(){return Cr.Events}static get P2pEngine(){return Cr}constructor(e={}){let t=e.p2pConfig||{};const r=!1===t.live?Or:xr;let i=JSON.parse(JSON.stringify(r));i.maxBufferSize=0,i.enableWorker=!1;for(let t in e)"p2pConfig"!==t&&(i[t]=e[t]);super(i),this._restartEvent=()=>{this.restartP2P()},Cr.isSupported()&&(this._p2pEngine=new Cr({...t,hlsjsInstance:this}),this._p2pEngine.on(Cr.Events.RESTART_P2P,this._restartEvent)),this.on(Mr().Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(Cr.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(Cr.Events.RESTART_P2P,this._restartEvent))}}Nr.engineVersion=Cr.version,Nr.protocolVersion=Cr.protocolVersion,Nr.WEBRTC_SUPPORT=Cr.isSupported();const Fr=Nr})(),i=i.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,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.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(r,i){function s(r){e.removeListener(t,n),i(r)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",s),r([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&p(e,"error",t,r)}(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,r,i){var s,n,a,h;if(o(r),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),a=n[t]),void 0===a)a=n[t]=r,++e._eventsCount;else if("function"==typeof a?a=n[t]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),(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,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},s=u.bind(i);return s.listener=r,i.wrapFn=s,s}function c(e,t,r){var i=e._events;if(void 0===i)return[];var s=i[t];return void 0===s?[]:"function"==typeof s?r?[s.listener||s]:[s]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(s):g(s,s.length)}function f(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function g(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function p(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);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){i.once&&e.removeEventListener(t,s),r(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=[],r=1;r<arguments.length;r++)t.push(arguments[r]);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)i(l,this,t);else{var h=l.length,u=g(l,h);for(r=0;r<h;++r)i(u[r],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 r,i,s,n,a;if(o(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length-1;n>=0;n--)if(r[n]===t||r[n].listener===t){a=r[n].listener,s=n;break}if(s<0)return this;0===s?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,s),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var s,n=Object.keys(r);for(i=0;i<n.length;++i)"removeListener"!==(s=n[i])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);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 r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.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 r.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=i.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=r.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=r.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}()},917:e=>{!function t(r){var i;i=function(){"use strict";function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,c(i.key),i)}}function i(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function s(e,t,r){return(t=c(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}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 r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function u(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?h(Object(r),!0).forEach((function(t){s(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):h(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,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 r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=typeof i)return i;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,r)}function r(){return function(e,t,r){if(l())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var s=new(e.bind.apply(e,i));return r&&d(s,r.prototype),s}(e,arguments,a(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),d(r,e)},f(e)}function g(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var p,m,v={exports:{}},y=(p||(p=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new s(i,n||e,a),l=r?r+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 i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,s=[];if(0===this._eventsCount)return s;for(i in e=this._events)t.call(e,i)&&s.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,n=i.length,a=new Array(n);s<n;s++)a[s]=i[s].fn;return a},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,s,n,a){var o=r?r+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,i),!0;case 4:return u.fn.call(u.context,t,i,s),!0;case 5:return u.fn.call(u.context,t,i,s,n),!0;case 6:return u.fn.call(u.context,t,i,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,i);break;case 4:u[h].fn.call(u[h].context,t,i,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,r){return n(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return n(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,s){var n=r?r+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||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],u=o.length;l<u;l++)(o[l].fn!==t||s&&!o[l].once||i&&o[l].context!==i)&&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=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(v)),v.exports),E=g(y),S={exports:{}},T=(m||(m=1,function(e,t){var r,i,s,n,a;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.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 r.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=i.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=r.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(e){var t=r.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}(S)),S.exports),_=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=b},b=Number.MAX_SAFE_INTEGER||9007199254740991,R=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}({}),P=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}({}),w="manifest",I="level",D="audioTrack",C="subtitleTrack",k="main",M="audio",x="subtitle",O=function(){function e(e,t,r){void 0===t&&(t=0),void 0===r&&(r=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_=r}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*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}(),N=function(){function e(e,t,r,i){void 0===i&&(i=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_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new O(e),this.fast_=new O(t),this.defaultTTFB_=i,this.ttfb_=new O(e)}var t=e.prototype;return t.update=function(e,t){var r=this.slow_,i=this.fast_,s=this.ttfb_;r.halfLife!==e&&(this.slow_=new O(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new O(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new O(e,s.getEstimate(),s.getTotalWeight()))},t.sample=function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},t.sampleTTFB=function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,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(){},i(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 r="["+e+"]:";this.trace=B,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)},B=function(){},U={trace:B,debug:B,log:B,warn:B,info:B,error:B};function G(){return n({},U)}function H(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):B}(e,r)}var $=G();function W(e,t,r){var i=G();if("object"==typeof console&&!0===e||"object"==typeof e){var s=["debug","log","info","warn","error"];s.forEach((function(t){i[t]=H(t,e,r)}));try{i.log('Debug logs enabled for "'+t+'" in hls.js version 1.6.5')}catch(e){return G()}s.forEach((function(t){$[t]=H(t,e)}))}else n($,i);return i}var V,q,j=$,z=q?V:(q=1,V=void 0),K=g(z);function Y(e,t){if(void 0===t&&(t=!1),"undefined"!=typeof TextDecoder){var r=new TextDecoder("utf-8").decode(e);if(t){var i=r.indexOf("\0");return-1!==i?r.substring(0,i):r}return r.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}var X=function(e){for(var t="",r=0;r<e.length;r++){var i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t},Q=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}},J="audio",Z="video",ee="audiovideo",te=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=ne(this,"stats"))&&(t.enumerable=!0,Object.defineProperty(this,"stats",t))}var t=e.prototype;return t.setByteRange=function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]},t.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[J]=null,e[Z]=null,e[ee]=null},i(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={})[J]=null,e[Z]=null,e[ee]=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 Q),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=T.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}])}();function re(e){return"initSegment"!==e.sn}var ie=function(e){function t(t,r){var i;return(i=e.call(this,r)||this)._decryptdata=null,i._programDateTime=null,i._ref=null,i._bitrate=void 0,i.rawProgramDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.playlistOffset=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=t,i}o(t,e);var r=t.prototype;return r.addStart=function(e){this.setStart(this.start+e)},r.setStart=function(e){this.start=e,this._ref&&(this._ref.start=e)},r.setDuration=function(e){this.duration=e,this._ref&&(this._ref.duration=e)},r.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},r.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},r.setElementaryStreamInfo=function(e,t,r,i,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,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:s,partial:n}},i(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange){var t=this.byteRange[0],r=this.byteRange[1];if(_(t)&&_(r))return r-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)return this._decryptdata=this.levelkeys[t[0]].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=_(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=Object.keys(this.levelkeys),r=t.length;if(r>1||1===r&&this.levelkeys[t[0]].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){_(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return re(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(te),se=function(e){function t(t,r,i,s,n){var a;(a=e.call(this,i)||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=r,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),i(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)}}])}(te);function ne(e,t){var r=Object.getPrototypeOf(e);if(r)return Object.getOwnPropertyDescriptor(r,t)||ne(r,t)}var ae=Math.pow(2,32)-1,oe=[].push,le={video:1,audio:2,id3:3,text:4};function he(e){return String.fromCharCode.apply(null,e)}function ue(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function de(e,t){var r=fe(e,t);return r<0?4294967296+r:r}function ce(e,t){var r=de(e,t);return(r*=Math.pow(2,32))+de(e,t+4)}function fe(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ge(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function pe(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,s=0;s<i;){var n=de(e,s),a=n>1?s+n:i;if(he(e.subarray(s+4,s+8))===t[0])if(1===t.length)r.push(e.subarray(s+8,a));else{var o=pe(e.subarray(s+8,a),t.slice(1));o.length&&oe.apply(r,o)}s=a}return r}function me(e){var t=[],r=e[0],i=8,s=de(e,i);i+=4;var n=0,a=0;0===r?(n=de(e,i),a=de(e,i+4),i+=8):(n=ce(e,i),a=ce(e,i+8),i+=16),i+=2;var o=e.length+a,l=ue(e,i);i+=2;for(var h=0;h<l;h++){var u=i,d=de(e,u);u+=4;var c=2147483647&d;if(1==(2147483648&d)>>>31)return j.warn("SIDX has hierarchical references (not supported)"),null;var f=de(e,u);u+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+c-1}}),o+=c,i=u+=4}return{earliestPresentationTime:n,timescale:s,version:r,referencesCount:l,references:t}}function ve(e){for(var t=[],r=pe(e,["moov","trak"]),i=0;i<r.length;i++){var s=r[i],n=pe(s,["tkhd"])[0];if(n){var a=n[0],o=de(n,0===a?12:20),l=pe(s,["mdia","mdhd"])[0];if(l){var h=de(l,0===(a=l[0])?12:20),d=pe(s,["mdia","hdlr"])[0];if(d){var c=he(d.subarray(8,12)),f={soun:J,vide:Z}[c],g=ye(pe(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 pe(e,["moov","mvex","trex"]).forEach((function(e){var r=de(e,4),i=t[r];i&&(i.default={duration:de(e,12),flags:de(e,20)})})),t}function ye(e){var t,r=e.subarray(8),i=r.subarray(86),s=he(r.subarray(4,8)),n=s,a="enca"===s||"encv"===s;if(a){var o=pe(r,[s])[0];pe(o.subarray("enca"===s?28:78),["sinf"]).forEach((function(e){var t=pe(e,["schm"])[0];if(t){var r=he(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=pe(e,["frma"])[0];i&&(n=he(i))}}}))}var l=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":var h=pe(i,["avcC"])[0];h&&h.length>3&&(n+="."+Te(h[1])+Te(h[2])+Te(h[3]),t=Ee("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var u=pe(r,[s])[0],d=pe(u.subarray(28),["esds"])[0];if(d&&d.length>7){var c=4;if(3!==d[c++])break;c=Se(d,c),c+=2;var f=d[c++];if(128&f&&(c+=2),64&f&&(c+=d[c++]),4!==d[c++])break;c=Se(d,c);var g=d[c++];if(64!==g)break;if(n+="."+Te(g),c+=12,5!==d[c++])break;c=Se(d,c);var p=d[c++],m=(248&p)>>3;31===m&&(m+=1+((7&p)<<3)+((224&d[c])>>5)),n+="."+m}break;case"hvc1":case"hev1":var v=pe(i,["hvcC"])[0];if(v&&v.length>12){var y=v[1],E=["","A","B","C"][y>>6],S=31&y,T=de(v,2),_=(32&y)>>5?"H":"L",L=v[12],b=v.subarray(6,12);n+="."+E+S,n+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(T).toString(16).toUpperCase(),n+="."+_+L;for(var R="",A=b.length;A--;){var P=b[A];(P||R)&&(R="."+P.toString(16).toUpperCase()+R)}n+=R}t=Ee("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Ee(n,i)||n;break;case"vp09":var w=pe(i,["vpcC"])[0];if(w&&w.length>6){var I=w[4],D=w[5],C=w[6]>>4&15;n+="."+_e(I)+"."+_e(D)+"."+_e(C)}break;case"av01":var k=pe(i,["av1C"])[0];if(k&&k.length>2){var M=k[1]>>>5,x=31&k[1],O=k[2]>>>7?"H":"M",N=(64&k[2])>>6,F=(32&k[2])>>5,B=2===M&&N?F?12:10:N?10:8,U=(16&k[2])>>4,G=(8&k[2])>>3,H=(4&k[2])>>2,$=3&k[2];n+="."+M+"."+_e(x)+O+"."+_e(B)+"."+U+"."+G+H+$+"."+_e(1)+"."+_e(1)+"."+_e(1)+".0",t=Ee("dav1",i)}}return{codec:n,encrypted:a,supplemental:t}}function Ee(e,t){var r=pe(t,["dvvC"]),i=r.length?r[0]:pe(t,["dvcC"])[0];if(i){var s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return e+"."+_e(s)+"."+_e(n)}}function Se(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function Te(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function _e(e){return(e<10?"0":"")+e}function Le(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function be(e,t){var r=[],i=t.samples,s=t.timescale,n=t.id,a=!1;return pe(i,["moof"]).map((function(o){var l=o.byteOffset-8;pe(o,["traf"]).map((function(o){var h=pe(o,["tfdt"]).map((function(e){var t=e[0],r=de(e,4);return 1===t&&(r*=Math.pow(2,32),r+=de(e,8)),r/s}))[0];return void 0!==h&&(e=h),pe(o,["tfhd"]).map((function(h){var u=de(h,4),d=16777215&de(h,0),c=0,f=!!(16&d),g=0,p=!!(32&d),m=8;u===n&&(!!(1&d)&&(m+=8),!!(2&d)&&(m+=4),!!(8&d)&&(c=de(h,m),m+=4),f&&(g=de(h,m),m+=4),p&&(m+=4),"video"===t.type&&(a=Re(t.codec)),pe(o,["trun"]).map((function(n){var o=n[0],h=16777215&de(n,0),u=!!(1&h),d=0,f=!!(4&h),p=!!(256&h),m=0,v=!!(512&h),y=0,E=!!(1024&h),S=!!(2048&h),T=0,_=de(n,4),L=8;u&&(d=de(n,L),L+=4),f&&(L+=4);for(var b=d+l,R=0;R<_;R++){if(p?(m=de(n,L),L+=4):m=c,v?(y=de(n,L),L+=4):y=g,E&&(L+=4),S&&(T=0===o?de(n,L):fe(n,L),L+=4),t.type===Z)for(var A=0;A<y;){var P=de(i,b);Ae(a,i[b+=4])&&Pe(i.subarray(b,b+P),a?2:1,e+T/s,r),b+=P,A+=P+4}e+=m/s}})))}))}))})),r}function Re(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Ae(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6==(31&t)}function Pe(e,t,r,i){var s=we(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){j.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===s[u++]){var d=ue(s,u);if(u+=2,49===d){var c=de(s,u);if(u+=4,1195456820===c){var f=s[u++];if(3===f){var g=s[u++],p=64&g,m=p?2+3*(31&g):0,v=new Uint8Array(m);if(p){v[0]=g;for(var y=1;y<m;y++)v[y]=s[u++]}i.push({type:f,payloadType:a,pts:r,bytes:v})}}}}}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++];i.push({payloadType:a,pts:r,uuid:E.join(""),userData:Y(L),userDataBytes:L})}}}function we(e){for(var t=e.byteLength,r=[],i=1;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return e;var s=t-r.length,n=new Uint8Array(s),a=0;for(i=0;i<s;a++,i++)a===r[0]&&(a++,r.shift()),n[i]=e[a];return n}function Ie(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}var De=function(){return/\(Windows.+Firefox\//i.test(navigator.userAgent)},Ce={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 ke(e,t){var r=Ce[t];return!!r&&!!r[e.slice(0,4)]}function Me(e,t,r){return void 0===r&&(r=!0),!e.split(",").some((function(e){return!xe(e,t,r)}))}function xe(e,t,r){var i;void 0===r&&(r=!0);var s=Ie(r);return null!=(i=null==s?void 0:s.isTypeSupported(Oe(e,t)))&&i}function Oe(e,t){return t+"/mp4;codecs="+e}function Ne(e){if(e){var t=e.substring(0,4);return Ce.video[t]}return 2}function Fe(e){var t=De();return e.split(",").reduce((function(e,r){var i=t&&Re(r)?9:Ce.video[r];return i?(2*i+e)/(e?3:2):(Ce.audio[r]+e)/(e?2:1)}),0)}var Be={},Ue=/flac|opus|mp4a\.40\.34/i;function Ge(e,t){return void 0===t&&(t=!0),e.replace(Ue,(function(e){return function(e,t){if(void 0===t&&(t=!0),Be[e])return Be[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i<r.length;i++){var s;if(xe(r[i],"audio",t))return Be[e]=r[i],r[i];if("mp3"===r[i]&&null!=(s=Ie(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)}))}function He(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function $e(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function We(e){var t=Ie(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function Ve(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var qe=["NONE","TYPE-0","TYPE-1",null],je=["SDR","PQ","HLG"];function ze(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i<t/2?r?"v2":"YES":""}var Ke=function(){function e(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}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}(),Ye=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 r=null==(t=e.supplemental)?void 0:t.videoCodec;r&&r!==e.videoCodec&&(this.codecSet+=","+r.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 Xe(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return Xe(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),-1===i.indexOf(t)&&i.push(t)}},t.addFallback=function(){},i(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 Xe(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}var Qe=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,i){if(e&&(i=e(r,i)),"object"==typeof i&&null!==i){if(t.has(i))return;t.add(i)}return i}}(t))};function Je(e,t){j.log('[abr] start candidates with "'+e+'" ignored because '+t)}function Ze(e){return e.reduce((function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function et(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}var tt=function(e){function t(t){var r;return(r=e.call(this,"abr",t.logger)||this).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,i=r,s=i.fragCurrent,n=i.partCurrent,a=i.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=r._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var m=p>-1&&p!==g,v=!!e||m;if(v||!l.paused&&l.playbackRate&&l.readyState){var y=a.mainForwardBufferInfo;if(v||null!==y){var E=r.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(!(c<=Math.max(E,d/(2*S)*1e3))){var T=y?y.len/S:0,L=u.loading.first?u.loading.first-u.loading.start:-1,b=u.loaded&&L>-1,R=r.getBwEstimate(),A=a.levels,w=A[g],I=Math.max(u.loaded,Math.round(d*(s.bitrate||w.averageBitrate)/8)),D=b?c-L:c;D<1&&b&&(D=Math.min(c,8*u.loaded/R));var C=b?1e3*u.loaded/D:0,k=E/1e3,M=C?(I-u.loaded)/C:8*I/R+k;if(!(M<=T)){var x,O=C?8*C:R,N=!0===(null==(t=(null==e?void 0:e.details)||r.hls.latestLevelDetails)?void 0:t.live),F=r.hls.config.abrBandWidthUpFactor,B=Number.POSITIVE_INFINITY;for(x=g-1;x>f;x--){var U=A[x].maxBitrate,G=!A[x].details||N;if((B=r.getTimeToLoadFrag(k,O,d*U,G))<Math.min(T,d+k))break}if(!(B>=M||B>10*d)){b?r.bwEstimator.sample(c-Math.min(E,L),u.loaded):r.bwEstimator.sampleTTFB(c);var H=A[x].maxBitrate;r.getBwEstimate()*F>H&&r.resetEstimator(H);var $=r.findBestLevel(H,f,x,0,T,1,1);$>-1&&(x=$),r.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: "+T.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: "+(_(R)?0|R:"Unknown")+" bps\n New BW estimate: "+(0|r.getBwEstimate())+" bps\n Switching to level "+x+" @ "+(0|H)+" bps"),a.nextLoadLevel=a.nextAutoLevel=x,r.clearTimer();var W=function(){if(r.clearTimer(),r.fragCurrent===s&&r.hls.loadLevel===x&&x>0){var e=r.getStarvationDelay();if(r.warn("Aborting inflight request "+(x>0?"and switching down":"")+"\n Fragment duration: "+s.duration.toFixed(3)+" s\n Time to underbuffer: "+e.toFixed(3)+" s"),s.abortRequests(),r.fragCurrent=r.partCurrent=null,x>f){var t=r.findBestLevel(r.hls.levels[f].bitrate,f,x,0,e,1,1);-1===t&&(t=f),r.hls.nextLoadLevel=r.hls.nextAutoLevel=t,r.resetEstimator(r.hls.levels[t].bitrate)}}};m||M>2*B?W():r.timer=self.setInterval(W,1e3*B),a.trigger(P.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:u})}}}}}}}},r.hls=t,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}o(t,e);var r=t.prototype;return r.resetEstimator=function(e){e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},r.initEstimator=function(){var e=this.hls.config;return new N(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},r.registerListeners=function(){var e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.FRAG_LOADING,this.onFragLoading,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(P.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.FRAG_LOADING,this.onFragLoading,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(P.ERROR,this.onError,this))},r.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},r.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},r.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},r.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},r.onFragLoading=function(e,t){var r,i=t.frag;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},r.onLevelSwitching=function(e,t){this.clearTimer()},r.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 r=t.frag,i=this.fragCurrent,s=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var n=performance.now(),a=s?s.stats:r.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)}}},r.getTimeToLoadFrag=function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)},r.onLevelLoaded=function(e,t){var r=this.hls.config,i=t.stats.loading,s=i.end-i.first;_(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},r.onFragLoaded=function(e,t){var r=t.frag,i=t.part,s=i?i.stats:r.stats;if(r.type===k&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var n=i?i.duration:r.duration,a=this.hls.levels[r.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(r.bitrateTest){var h={stats:s,frag:r,part:i,id:r.type};this.onFragBuffered(P.FRAG_BUFFERED,h),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part,s=null!=i&&i.stats.loaded?i.stats:r.stats;if(!s.aborted&&!this.ignoreFragment(r)){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(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},r.ignoreFragment=function(e){return e.type!==k||"initSegment"===e.sn},r.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},r.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},r.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,s=r.config,n=r.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,i,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,i,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=r.levels[n],m=r.loadLevelObj;return m&&(null==p?void 0:p.bitrate)<m.bitrate?n:r.loadLevel},r.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r},r.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},r.findBestLevel=function(e,t,r,i,s,n,a){var o,l=this,h=i+s,u=this.lastLoadedFragLevel,d=-1===u?this.hls.firstLevel:u,c=this.fragCurrent,f=this.partCurrent,g=this.hls,p=g.levels,m=g.allAudioTracks,v=g.loadLevel,y=g.config;if(1===p.length)return 0;var E,S=p[d],T=!(null==(o=this.hls.latestLevelDetails)||!o.live),L=-1===v||-1===u,b="SDR",R=(null==S?void 0:S.frameRate)||0,A=y.audioPreference,P=y.videoPreference,w=(this.audioTracksByGroup||(this.audioTracksByGroup=Ze(m)),-1);if(L){if(-1!==this.firstSelection)return this.firstSelection;var I=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce((function(e,t,r){if(!t.codecSet)return e;var i=t.audioGroups,s=e[t.codecSet];s||(e[t.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,t.bitrate);var n=Math.min(t.height,t.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,t.frameRate),s.minIndex=Math.min(s.minIndex,r),s.maxScore=Math.max(s.maxScore,t.score),s.fragmentError+=t.fragmentError,s.videoRanges[t.videoRange]=(s.videoRanges[t.videoRange]||0)+1,e}),{})}(p,0,t,r)),D=function(e,t,r,i,s){for(var n=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.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,m=0,v=[],y=function(e,t){var r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){var s="SDR"!==(i=t.allowedVideoRanges||je.slice(0)).join("")&&!t.videoCodec;(r=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}())||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}(t,s),E=y.preferHDR,S=y.allowedVideoRanges,T=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--;)T();c=_(c)?c:0,f=_(f)?f:0;var b=Math.max(1080,c),R=Math.max(30,f);g=_(g)?g:r,r=Math.max(g,r),d||(t=void 0);var A=n.length>1;return{codecSet:n.reduce((function(t,i){var s=e[i];if(i===t)return t;if(v=d?S.filter((function(e){return s.videoRanges[e]>0})):[],A){if(s.minBitrate>r)return Je(i,"min bitrate of "+s.minBitrate+" > current estimate of "+r),t;if(!s.hasDefaultAudio)return Je(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Je(i,'audio codec preference "'+o+'" not found'),t;if(a&&!h){if(!s.channels[a])return Je(i,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(s.channels)+")"),t}else if((!o||h)&&u&&0===s.channels[2])return Je(i,"no renditions with stereo sound found"),t;if(s.minHeight>b)return Je(i,"min resolution of "+s.minHeight+" > maximum of "+b),t;if(s.minFramerate>R)return Je(i,"min framerate of "+s.minFramerate+" > maximum of "+R),t;if(!v.some((function(e){return s.videoRanges[e]>0})))return Je(i,"no variants with VIDEO-RANGE of "+Qe(v)+" found"),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Je(i,'video codec preference "'+l+'" not found'),t;if(s.maxScore<m)return Je(i,"max score of "+s.maxScore+" < selected max of "+m),t}return t&&(Fe(i)>=Fe(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,m=s.maxScore,i)}),void 0),videoRanges:v,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}(I,b,e,A,P),C=D.codecSet,k=D.videoRanges,M=D.minFramerate,x=D.minBitrate,O=D.minIndex,N=D.preferHDR;w=O,E=C,b=N?k[k.length-1]:k[0],R=M,e=Math.max(e,x),this.log("picked start tier "+Qe(D))}else E=null==S?void 0:S.codecSet,b=null==S?void 0:S.videoRange;for(var F,B=f?f.duration:c?c.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,G=[],H=function(){var t,o=p[$],c=$>d;if(!o)return 0;if((E&&o.codecSet!==E||b&&o.videoRange!==b||c&&R>o.frameRate||!c&&R>0&&R<o.frameRate||o.supportedResult&&(null==(t=o.supportedResult.decodingInfoResults)||!t[0].smooth))&&(!L||$!==w))return G.push($),0;var g,m=o.details,y=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||B;g=c?a*e:n*e;var S=B&&i>=2*B&&0===s?o.averageBitrate:o.maxBitrate,A=l.getTimeToLoadFrag(U,g,S*y,void 0===m);if(g>=S&&($===u||0===o.loadError&&0===o.fragmentError)&&(A<=U||!_(A)||T&&!l.bitrateTestDelay||A<h)){var P=l.forcedAutoLevel;return $===v||-1!==P&&P===v||(G.length&&l.trace("Skipped level(s) "+G.join(",")+" of "+r+' max with CODECS and VIDEO-RANGE:"'+p[G[0]].codecs+'" '+p[G[0]].videoRange+'; not compatible with "'+E+'" '+b),l.info("switch candidate:"+d+"->"+$+" adjustedbw("+Math.round(g)+")-bitrate="+Math.round(g-S)+" ttfb:"+U.toFixed(1)+" avgDuration:"+y.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+A.toFixed(1)+" firstSelection:"+L+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+v)),L&&(l.firstSelection=$),{v:$}}},$=r;$>=t;$--)if(0!==(F=H())&&F)return F.v;return-1},r.deriveNextAutoLevel=function(e){var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)},i(t,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,r,t,0,s,1,1);if(n>-1)return n;var a=this.hls.firstLevel,o=Math.min(Math.max(a,r),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(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var s=this.hls.levels;if(s.length>Math.max(e,i)&&s[e].loadError<=s[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(F),rt=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,r){if(null!==this.queues&&null!==this.tracks){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}},t.appendBlocker=function(e){var t=this;return new Promise((function(r){var i={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(i,e)}))},t.prependBlocker=function(e){var t=this;return new Promise((function(r){if(t.queues){var i={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(i)}}))},t.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(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 r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;var s=null==(i=this.tracks[e])?void 0:i.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,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer"+(i.updating?" updating":"")+(r.ended?" ended":"")+(r.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}(),it=function(e,t){for(var r=0,i=e.length-1,s=null,n=null;r<=i;){var a=t(n=e[s=(r+i)/2|0]);if(a>0)r=s+1;else{if(!(a<0))return n;i=s-1}}return null};function st(e,t,r,i,s){void 0===r&&(r=0),void 0===i&&(i=0),void 0===s&&(s=.005);var n=null;if(e){n=t[1+e.sn-t[0].sn]||null;var a=e.endDTS-r;a>0&&a<15e-7&&(r+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===nt(r,i,n)||function(e,t,r){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var i=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),r);return e.start<=i}return!1}(n,e,Math.min(s,i))))return n;var o=it(t,nt.bind(null,r,i));return!o||o===e&&n?n:o}function nt(e,t,r){if(void 0===e&&(e=0),void 0===t&&(t=0),r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function at(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function ot(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 lt(e,t){var r=ot(t);return e.default[(r?"timeout":"error")+"Retry"]}function ht(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function ut(e){return u(u({},e),{errorRetry:null,timeoutRetry:null})}function dt(e,t,r,i){if(!e)return!1;var s=null==i?void 0:i.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(s)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,n):n}var ct=function(e){function t(t){var r;return(r=e.call(this,"error-controller",t.logger)||this).hls=void 0,r.playlistError=0,r.penalizedRenditions={},r.hls=t,r.registerListeners(),r}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(P.ERROR,this.onError,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.ERROR,this.onError,this),e.off(P.ERROR,this.onErrorOut,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this))},r.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},r.startLoad=function(e){},r.stopLoad=function(){this.playlistError=0},r.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===k?e.level:this.hls.loadLevel},r.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},r.onLevelUpdated=function(){this.playlistError=0},r.onError=function(e,t){var r;if(!t.fatal){var i=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!=(r=t.frag)&&r.gap)return void(t.errorAction=ft());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,o=t.parent===k?t.level:i.loadLevel;return void(t.details===A.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(a=n.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o)));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 l=i.loadLevelObj;if(l&&(s.type===D&&l.hasAudioGroup(s.groupId)||s.type===C&&l.hasSubtitleGroup(s.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var h=i.loadLevelObj,u=null==h?void 0:h.attrs["HDCP-LEVEL"];return void(u?t.errorAction={action:2,flags:2,hdcpLevel:u}:this.keySystemError(t));case A.BUFFER_ADD_CODEC_ERROR:case A.REMUX_ALLOC_ERROR:case A.BUFFER_APPEND_ERROR:var d;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(d=t.level)?d:i.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=ft())}t.type===R.KEY_SYSTEM_ERROR&&this.keySystemError(t)}},r.keySystemError=function(e){var t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)},r.getPlaylistRetryOrSwitchAction=function(e,t){var r=lt(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(dt(r,i,ot(e),e.response))return{action:5,flags:0,retryConfig:r,retryCount:i};var s=this.getLevelSwitchAction(e,t);return r&&(s.retryConfig=r,s.retryCount=i),s},r.getFragRetryOrSwitchAction=function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],s=t.config,n=s.fragLoadPolicy,a=s.keyLoadPolicy,o=lt(e.details.startsWith("key")?a:n,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(i&&(e.details!==A.FRAG_GAP&&i.fragmentError++,dt(o,l,ot(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(e,r);return o&&(h.retryConfig=o,h.retryCount=l),h},r.getLevelSwitchAction=function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var s,n,a=e.details;i.loadError++,a===A.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,h=r.loadLevel,u=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var c,f=null==(s=e.frag)?void 0:s.type,g=(f===M&&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 i.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,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r})),m=null!=(n=e.context)?n:{},v=m.type,y=m.groupId,E=function(){var t=(S+h)%l.length;if(t!==h&&t>=u&&t<=d&&0===l[t].loadError){var r,s,n=l[t];if(a===A.FRAG_GAP&&f===k&&e.frag){var c=l[t].details;if(c){var m=st(e.frag,c.fragments,e.frag.start);if(null!=m&&m.gap)return 0}}else{if(v===D&&n.hasAudioGroup(y)||v===C&&n.hasSubtitleGroup(y))return 0;if(f===M&&null!=(r=i.audioGroups)&&r.some((function(e){return n.hasAudioGroup(e)}))||f===x&&null!=(s=i.subtitleGroups)&&s.some((function(e){return n.hasSubtitleGroup(e)}))||g&&i.audioCodec===n.audioCodec||!g&&i.audioCodec!==n.audioCodec||p&&i.codecSet===n.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(c=E())||1!==c););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}},r.onErrorOut=function(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.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()},r.sendAlternateToPenaltyBox=function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.flags,s=r.hdcpLevel,n=r.nextAutoLevel;switch(i){case 0:this.switchLevel(e,n);break;case 2:s&&(t.maxHdcpLevel=qe[qe.indexOf(s)-1],r.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')}r.resolved||this.switchLevel(e,n)}},r.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 r=Ve(e.mimeType),i=this.hls.levels,s=i.length;s--;)i[s][e.sourceBufferName+"Codec"]===r&&this.hls.removeLevel(s)},t}(F);function ft(e){var t={action:0,flags:0};return e&&(t.resolved=!0),t}var gt={length:0,start:function(){return 0},end:function(){return 0}},pt=function(){function e(){}return e.isBuffered=function(t,r){if(t)for(var i=e.getBuffered(t),s=i.length;s--;)if(r>=i.start(s)&&r<=i.end(s))return!0;return!1},e.bufferedRanges=function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]},e.timeRangesToArray=function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t},e.bufferInfo=function(t,r,i){if(t){var s=e.bufferedRanges(t);if(s.length)return e.bufferedInfo(s,r,i)}return{len:0,start:r,end:r,bufferedIndex:-1}},e.bufferedInfo=function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var i=-1,s=[];if(r)for(var n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(i=n);var a=s.length;if(a){var o=s[a-1].end;e[n].start-o<r?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===i&&t>=f&&t<=g&&(i=c),t+r>=f&&t<g)u=f,h=(d=g)-t;else if(t+r<f){l=f;break}}return{len:h,start:u||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:i}},e.getBuffered=function(e){try{return e.buffered||gt}catch(e){return j.log("failed to get media.buffered",e),gt}},e}(),mt=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,vt="HlsJsTrackRemovedError",yt=function(e){function t(t){var r;return(r=e.call(this,t)||this).name=vt,r}return o(t,e),t}(f(Error)),Et=function(e){function t(t,r){var i,s;return(i=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,i.fragmentTracker=void 0,i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.blockedAudioAppend=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,s=t.mediaSource;e&&i.log("Media source opened"),r&&s&&(s.removeEventListener("sourceopen",i._onMediaSourceOpen),r.removeEventListener("emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(P.MEDIA_ATTACHED,{media:r,mediaSource:s}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){i.log("Media source closed")},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource ("+r+" > "+t+")")},i.hls=t,i.fragmentTracker=r,i.appendSource=(s=Ie(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}o(t,e);var r=t.prototype;return r.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},r.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},r.registerListeners=function(){var e=this.hls;e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.BUFFER_RESET,this.onBufferReset,this),e.on(P.BUFFER_APPENDING,this.onBufferAppending,this),e.on(P.BUFFER_CODECS,this.onBufferCodecs,this),e.on(P.BUFFER_EOS,this.onBufferEos,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.FRAG_PARSED,this.onFragParsed,this),e.on(P.FRAG_CHANGED,this.onFragChanged,this),e.on(P.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.BUFFER_RESET,this.onBufferReset,this),e.off(P.BUFFER_APPENDING,this.onBufferAppending,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.BUFFER_EOS,this.onBufferEos,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.FRAG_PARSED,this.onFragParsed,this),e.off(P.FRAG_CHANGED,this.onFragChanged,this),e.off(P.ERROR,this.onError,this)},r.transferMedia=function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};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===r?n(i,o.tracks):this.sourceBuffers.forEach((function(t){var r=t[0];r&&(i[r]=n({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null})),{media:t,mediaSource:r,tracks:i}},r.initTracks=function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},r.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},r.onManifestParsed=function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(i+" bufferCodec event(s) expected."),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()},r.onMediaAttaching=function(e,t){var r=this.media=t.media,i=Ie(this.appendSource);if(this.transferData=this.overrides=void 0,r&&i){var s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),s)this._objectUrl=r.src,this.attachTransferred();else{var a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&n instanceof o,St(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,a),r.load()}catch(e){r.src=a}else r.src=a}r.addEventListener("emptied",this._onMediaEmptied)}},r.assignMediaSource=function(e){var t,r;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(r=e.constructor)?void 0:r.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))},r.attachTransferred=function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,s=r.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=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: "+Qe(i,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+Qe(s,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!function(e,t){var r=Object.keys(e),i=Object.keys(t),s=r.length,n=i.length;return!s||!n||s===n&&!r.some((function(e){return-1===i.indexOf(e)}))}(s,i)){r.mediaSource=null,r.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(i)+'") start time: '+u+" currentTime: "+l),this.onMediaDetaching(P.MEDIA_DETACHING,{}),this.onMediaAttaching(P.MEDIA_ATTACHING,r),void(t.currentTime=u))}this.transferData=void 0,n.forEach((function(t){var r=t,i=s[r];if(i){var n=i.buffer;if(n){var a=e.fragmentTracker,o=i.id;if(a.hasFragments(o)||a.hasParts(o)){var l=pt.getBuffered(n);a.detectEvictedFragments(r,l,o,null,!0)}var h=Tt(r),u=[r,n];e.sourceBuffers[h]=u,n.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},r.onMediaDetaching=function(e,t){var r=this,i=!!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 "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.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),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&St(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(P.MEDIA_DETACHED,t)},r.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];r&&e.resetBuffer(r)})),this.initTracks()},r.resetBuffer=function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},r.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[Tt(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)},r.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new rt(this.tracks)},r.onBufferCodecs=function(e,t){var r=this,i=this.tracks,s=Object.keys(t);this.log('BUFFER_CODECS: "'+s+'" (current SB count '+this.sourceBufferCount+")");var n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&s.some((function(e){return!i[e]}));n||a?this.warn('Unsupported transition between "'+Object.keys(i)+'" and "'+s+'" SourceBuffers'):(s.forEach((function(e){var s,n,a,o=t[e],l=o.id,h=o.codec,u=o.levelCodec,d=o.container,c=o.metadata,f=o.supplemental,g=i[e],p=null==(s=r.transferData)||null==(n=s.tracks)?void 0:n[e],m=null!=p&&p.buffer?p:g,v=(null==m?void 0:m.pendingCodec)||(null==m?void 0:m.codec),y=null==m?void 0:m.levelCodec;g||(g=i[e]={buffer:void 0,listeners:[],codec:h,supplemental:f,container:d,levelCodec:u,metadata:c,id:l});var E=He(v,y),S=null==E?void 0:E.replace(mt,"$1"),T=He(h,u),_=null==(a=T)?void 0:a.replace(mt,"$1");T&&E&&S!==_&&("audio"===e.slice(0,5)&&(T=Ge(T,r.appendSource)),r.log("switching codec "+v+" to "+T),T!==(g.pendingCodec||g.codec)&&(g.pendingCodec=T),g.container=d,r.appendChangeType(e,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())},r.appendChangeType=function(e,t,r){var i=this,s=t+";codecs="+r,n={label:"change-type="+s,execute:function(){var n=i.tracks[e];if(n){var a=n.buffer;null!=a&&a.changeType&&(i.log("changing "+e+" sourceBuffer type to "+s),a.changeType(s),n.codec=r,n.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(n,e,this.isPending(this.tracks[e]))},r.blockAudio=function(e){var t,r=this,i=e.start,s=i+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(i,k))?void 0:t.gap)){var n={label:"block-audio",execute:function(){var e,t=r.tracks.video;(r.lastVideoAppendEnd>s||null!=t&&t.buffer&&pt.isBuffered(t.buffer,s)||!0===(null==(e=r.fragmentTracker.getAppendedFrag(s,k))?void 0:e.gap))&&(r.blockedAudioAppend=null,r.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}},r.unblockAudio=function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))},r.onBufferAppending=function(e,t){var r=this,i=this.tracks,s=t.data,n=t.type,a=t.parent,o=t.frag,l=t.part,h=t.chunkMeta,u=h.buffering[n],d=o.sn,c=self.performance.now();u.start=c;var f=o.stats.buffering,g=l?l.stats.buffering:null;0===f.start&&(f.start=c),g&&0===g.start&&(g.start=c);var p=i.audio,m=!1;"audio"===n&&"audio/mpeg"===(null==p?void 0:p.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var v=this.tracks.video,y=null==v?void 0:v.buffer;if(y&&"initSegment"!==d){var E=l||o,S=this.blockedAudioAppend;if("audio"!==n||"main"===a||this.blockedAudioAppend){if("video"===n){var T=E.end;if(S){var _=S.frag.start;(T>_||T<this.lastVideoAppendEnd||pt.isBuffered(y,_))&&this.unblockAudio()}this.lastVideoAppendEnd=T}}else{var L=E.start+.05*E.duration,b=y.buffered,w=this.currentOp("video");b.length||w?!w&&!pt.isBuffered(y,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(E):this.blockAudio(E)}}var I=(l||o).start,D={label:"append-"+n,execute:function(){if(u.executeStart=self.performance.now(),m){var e=r.tracks[n];if(e){var t=e.buffer;if(t){var i=I-t.timestampOffset;Math.abs(i)>=.1&&(r.log("Updating audio SourceBuffer timestampOffset to "+I+" (delta: "+i+") sn: "+d+")"),t.timestampOffset=I)}}}r.appendExecutor(s,n)},onStart:function(){},onComplete:function(){var e=self.performance.now();u.executeEnd=u.end=e,0===f.first&&(f.first=e),g&&0===g.first&&(g.first=e);var t={};r.sourceBuffers.forEach((function(e){var r=e[0],i=e[1];r&&(t[r]=pt.getBuffered(i))})),r.appendErrors[n]=0,"audio"===n||"video"===n?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(P.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:t})},onError:function(e){var t,i={type:R.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=r.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR)i.details=A.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&r.mediaSourceOpenOrEnded&&!s)i.errorAction=ft(!0);else if(e.name===vt&&0===r.sourceBufferCount)i.errorAction=ft(!0);else{var a=++r.appendErrors[n];r.warn("Failed "+a+"/"+r.hls.config.appendErrorMaxRetry+' times to append segment in "'+n+'" sourceBuffer ('+(s||"no media error")+")"),(a>=r.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}r.hls.trigger(P.ERROR,i)}};this.append(D,n,this.isPending(this.tracks[n]))},r.getFlushOp=function(e,t,r){var i=this;return this.log('queuing "'+e+'" remove '+t+"-"+r),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){i.hls.trigger(P.BUFFER_FLUSHED,{type:e})},onError:function(s){i.warn("Failed to remove "+t+"-"+r+' from "'+e+'" SourceBuffer',s)}}},r.onBufferFlushing=function(e,t){var r=this,i=t.type,s=t.startOffset,n=t.endOffset;i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.append(r.getFlushOp(t,s,n),t)}))},r.onFragParsed=function(e,t){var r=this,i=t.frag,s=t.part,n=[],a=s?s.elementaryStreams:i.elementaryStreams;a[ee]?n.push("audiovideo"):(a[J]&&n.push("audio"),a[Z]&&n.push("video")),0===n.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);var t=s?s.stats:i.stats;r.hls.trigger(P.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})}),n).catch((function(e){r.warn("Fragment buffered callback "+e),r.stepOperationQueue(r.sourceBufferTypes)}))},r.onFragChanged=function(e,t){this.trimBuffers()},r.onBufferEos=function(e,t){var r,i=this;this.sourceBuffers.forEach((function(e){var r=e[0];if(r){var s=i.tracks[r];t.type&&t.type!==r||(s.ending=!0,s.ended||(s.ended=!0,i.log(r+" buffer reached EOS")))}}));var s=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,r=e[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)}))&&(s?(this.log("Queueing EOS"),this.blockUntilOpen((function(){i.tracksEnded();var e=i.mediaSource;e&&"open"===e.readyState?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(P.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(P.BUFFERED_TO_END,void 0)))},r.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}}))},r.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())},r.updateDuration=function(){var e=this,t=this.getDurationAndRange();t&&this.blockUntilOpen((function(){return e.updateMediaSource(t)}))},r.onError=function(e,t){if(t.details===A.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;_(i)&&i!==t.frag.level&&this.resetAppendErrors()}},r.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},r.trimBuffers=function(){var e=this.hls,t=this.details,r=this.media;if(r&&null!==t&&this.sourceBufferCount){var i=e.config,s=r.currentTime,n=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(_(a)&&a>=0){var o=Math.max(a,n),l=Math.floor(s/n)*n-o;this.flushBackBuffer(s,n,l)}if(_(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){var h=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),u=Math.max(h,n),d=Math.floor(s/n)*n+u;this.flushFrontBuffer(s,n,d)}}},r.flushBackBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(e){var t=e[0],s=e[1];if(s){var n=pt.getBuffered(s);if(n.length>0&&r>n.start(0)){var a;i.hls.trigger(P.BACK_BUFFER_REACHED,{bufferEnd:r});var o=i.tracks[t];if(null!=(a=i.details)&&a.live)i.hls.trigger(P.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=o&&o.ended)return void i.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");i.hls.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:t})}}}))},r.flushFrontBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(t){var s=t[0],n=t[1];if(n){var a=pt.getBuffered(n),o=a.length;if(o<2)return;var l=a.start(o-1),h=a.end(o-1);if(r>l||e>=l&&e<=h)return;i.hls.trigger(P.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}}))},r.getDurationAndRange=function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&r.setLiveSeekableRange){var s=Math.max(0,t.fragmentStart);return{duration:1/0,start:s,end:Math.max(s,i)}}return{duration:1/0}}var n=null==(e=this.overrides)?void 0:e.duration;if(n)return _(n)?{duration:n}:null;var a=this.media.duration;return i>(_(r.duration)?r.duration:0)&&i>a||!_(a)?{duration:i}:null},r.updateMediaSource=function(e){var t=e.duration,r=e.start,i=e.end,s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==t&&(_(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),s.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to "+s.duration+". Setting seekable range to "+r+"-"+i+"."),s.setLiveSeekableRange(r,i)))},r.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+Qe(r)),this.tracksReady){var i,s=null==(i=this.transferData)?void 0:i.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}},r.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(r){var i=r[0],s=r[1];if(i){var n=e.tracks[i];t[i]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}})),this.hls.trigger(P.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var r=t[0];e.executeNext(r)}))}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}},r.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var s=i,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":"")+" "+Qe(n));try{var l=r.addSourceBuffer(o),h=Tt(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(P.ERROR,{type:R.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()},r.getTrackCodec=function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&Me(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),s=0;s<i.length;s++)ke(i[s],"video")||r.push(i[s]);return t&&r.push(t),r.join(",")}(i,r));var s=He(i,e.levelCodec);return s?"audio"===t.slice(0,5)?Ge(s,this.appendSource):s:""},r.trackSourceBuffer=function(e,t){var r=this,i=t.buffer;if(i){var s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,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 i=t.removedRanges;null!=i&&i.length&&r.hls.trigger(P.BUFFER_FLUSHED,{type:e})}))}},r.onSBUpdateStart=function(e){var t=this.currentOp(e);t&&t.onStart()},r.onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)},r.onSBUpdateError=function(e,t){var r,i=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(r=this.mediaSource)?void 0:r.readyState));this.error(""+i,t),this.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var s=this.currentOp(e);s&&s.onError(i)},r.removeExecutor=function(e,t,r){var i=this.media,s=this.mediaSource,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!i||!s||!a)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(e);var o=_(i.duration)?i.duration:1/0,l=_(s.duration)?s.duration:1/0,h=Math.max(0,t),u=Math.min(r,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)},r.appendExecutor=function(e,t){var r=this.tracks[t],i=null==r?void 0:r.buffer;if(!i)throw new yt("Attempting to append to the "+t+" SourceBuffer, but it does not exist");r.ending=!1,r.ended=!1,i.appendBuffer(e)},r.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)}},r.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],r=e[1];return t&&r.updating}))},r.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var r=t[0];return r&&!!e.currentOp(r)}))},r.isPending=function(e){return!!e&&!e.buffer},r.blockBuffers=function(e,t){var r=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 i=this.operationQueue,s=t.map((function(e){return r.appendBlocker(e)}));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then((function(t){i===r.operationQueue&&(e(),r.stepOperationQueue(r.sourceBufferTypes))}))},r.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;i&&!i.updating&&t.shiftAndExecuteNext(e)}))},r.append=function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)},r.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},r.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},r.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},r.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},r.addBufferListener=function(e,t,r){var i=this.tracks[e];if(i){var s=i.buffer;if(s){var n=r.bind(this,e);i.listeners.push({event:t,listener:n}),s.addEventListener(t,n)}}},r.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach((function(e){r.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},i(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,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var r,i,s=t[0];return s&&(!(null!=(r=e.tracks[s])&&r.ended)||(null==(i=e.tracks[s])?void 0:i.ending))}))}},{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,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,r){return t+(e.isPending(e.tracks[r])?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 St(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function Tt(e){return"audio"===e?1:0}var _t=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(P.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.BUFFER_CODECS,this.onBufferCodecs,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListener=function(){var e=this.hls;e.off(P.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this)},t.onFpsDropLevelCapping=function(e,t){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.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 r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&_(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,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+r+": "+e[r].height+"p@"+e[r].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var s=i.filter((function(e,i){return r.isLevelAllowed(e)&&i<=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 r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.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,r){if(null==e||!e.length)return-1;for(var i,s,n=e.length-1,a=Math.max(t,r),o=0;o<e.length;o+=1){var l=e[o];if((l.width>=a||l.height>=a)&&(i=l,!(s=e[o+1])||i.width!==s.width||i.height!==s.height)){n=o;break}}return n},i(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)}}])}(),Lt=/^(\d+)x(\d+)$/,bt=/(.+?)=(".*?"|.*?)(?:,|$)/g,Rt=function(){function e(t,r){"string"==typeof t&&(t=e.parseAttrList(t,r)),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 r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}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 r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var r=this[e];return(r?r.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=Lt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var r,i={};for(bt.lastIndex=0;null!==(r=bt.exec(e));){var s=r[1].trim(),n=r[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));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":j.warn(e+": attribute "+s+" is missing quotes")}i[s]=n}return i},i(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function At(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var Pt=i((function(e,t,r){var i;if(void 0===r&&(r=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!=(i=null==t?void 0:t.tagOrder)?i:r,t){var s=t.attr;for(var a in s)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==s[a]){j.warn('DATERANGE tag attribute: "'+a+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=a;break}e=n(new Rt({}),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"]);_(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?(j.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(_(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&&_(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)}}]),wt=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}return e.prototype.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1},i(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&_(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(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){var e;return null!=(e=this.fragments)&&e.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 r=e.length;r--;)if(e[r].index>t)return e[r].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 It(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Dt(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)}}var Ct=function(){function e(e,t,r,i,s){void 0===i&&(i=[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=r,this.keyFormatVersions=i,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!It(e)}e.clearKeyUriToKeyIdMap=function(){};var t=e.prototype;return t.isSupported=function(){if(this.method){if(It(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1},t.getDecryptData=function(t){if(!this.encrypted||!this.uri)return null;if(It(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&(j.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0);var r=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t);return new e(this.method,this.uri,"identity",this.keyFormatVersions,r)}return this},e}(),kt=/#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,Mt=/#EXT-X-MEDIA:(.*)/g,xt=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ot=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Nt=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("|")),Ft=function(){function e(){}return e.findGroup=function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}},e.resolve=function(e,t){return T.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.isMediaPlaylist=function(e){return xt.test(e)},e.parseMasterPlaylist=function(t,r){var i,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},n=[];for(kt.lastIndex=0;null!=(i=kt.exec(t));)if(i[1]){var a,o=new Rt(i[1],s),l=i[2],h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,r)},u=o.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),$t(o.CODECS,h);var d=o["SUPPLEMENTAL-CODECS"];d&&(h.supplemental={},$t(d,h.supplemental)),null!=(a=h.unknownCodecs)&&a.length||n.push(h),s.levels.push(h)}else if(i[3]){var c=i[3],f=i[4];switch(c){case"SESSION-DATA":var g=new Rt(f,s),p=g["DATA-ID"];p&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[p]=g);break;case"SESSION-KEY":var m=Gt(f,r,s);m.encrypted&&m.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(m)):j.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+f+'"');break;case"DEFINE":break;case"CONTENT-STEERING":var v=new Rt(f,s);s.contentSteering={uri:e.resolve(v["SERVER-URI"],r),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":s.startTimeOffset=Ht(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,r,i){var s,n={},a=i.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(Mt.lastIndex=0;null!==(s=Mt.exec(t));){var h=new Rt(s[1],i),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,m=h.CHARACTERISTICS,v=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,r):""};if(g&&(y.assocLang=g),p&&(y.channels=p),m&&(y.characteristics=m),v&&(y.instreamId=v),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Wt(y,E,"audioCodec"),Wt(y,E,"textCodec")}c.push(y)}}return n},e.parseLevelPlaylist=function(e,t,r,i,s,a){var o,l,h,u,d,c={url:t},f=new wt(t),g=f.fragments,p=[],m=null,v=0,y=0,E=0,S=0,T=0,L=null,b=new ie(i,c),R=-1,A=!1,P=null;if(Ot.lastIndex=0,f.m3u8=e,f.hasVariableRefs=!1,"#EXTM3U"!==(null==(o=Ot.exec(e))?void 0:o[0]))return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;null!==(l=Ot.exec(e));){A&&(A=!1,(b=new ie(i,c)).playlistOffset=E,b.start=E,b.sn=v,b.cc=S,T&&(b.bitrate=T),b.level=r,m&&(b.initSegment=m,m.rawProgramDateTime&&(b.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),P&&(b.setByteRange(P),P=null)));var w=l[1];if(w){b.duration=parseFloat(w);var I=(" "+l[2]).slice(1);b.title=I||null,b.tagList.push(I?["INF",w,I]:["INF",w])}else if(l[3]){if(_(b.duration)){b.playlistOffset=E,b.start=E,u&&jt(b,u,f),b.sn=v,b.level=r,b.cc=S,g.push(b);var D=(" "+l[3]).slice(1);b.relurl=D,Vt(b,L,p),L=b,E+=b.duration,v++,y=0,A=!0}}else{if(!(l=l[0].match(Nt))){j.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);var C=(" "+l[h]).slice(1),k=(" "+l[h+1]).slice(1),M=l[h+2]?(" "+l[h+2]).slice(1):null;switch(C){case"BYTERANGE":L?b.setByteRange(k,L):b.setByteRange(k);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=k,b.tagList.push(["PROGRAM-DATE-TIME",k]),-1===R&&(R=g.length);break;case"PLAYLIST-TYPE":f.type&&zt(f,C,l),f.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?zt(f,C,l):g.length>0&&Kt(f,C,l),v=f.startSN=parseInt(k);break;case"SKIP":f.skippedSegments&&zt(f,C,l);var x=new Rt(k,f),O=x.decimalInteger("SKIPPED-SEGMENTS");if(_(O)){f.skippedSegments+=O;for(var N=O;N--;)g.push(null);v+=O}var F=x.enumeratedString("RECENTLY-REMOVED-DATERANGES");F&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(F.split("\t")));break;case"TARGETDURATION":0!==f.targetduration&&zt(f,C,l),f.targetduration=Math.max(parseInt(k),1);break;case"VERSION":null!==f.version&&zt(f,C,l),f.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":case"DEFINE":break;case"ENDLIST":f.live||zt(f,C,l),f.live=!1;break;case"#":(k||M)&&b.tagList.push(M?[k,M]:[k]);break;case"DISCONTINUITY":S++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([C]);break;case"BITRATE":b.tagList.push([C,k]),T=1e3*parseInt(k),_(T)?b.bitrate=T:T=0;break;case"DATERANGE":var B=new Rt(k,f),U=new Pt(B,f.dateRanges[B.ID],f.dateRangeTagCount);f.dateRangeTagCount++,U.isValid||f.skippedSegments?f.dateRanges[U.id]=U:j.warn('Ignoring invalid DATERANGE tag: "'+k+'"'),b.tagList.push(["EXT-X-DATERANGE",k]);break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?zt(f,C,l):g.length>0&&Kt(f,C,l),f.startCC=S=parseInt(k);break;case"KEY":var G=Gt(k,t,f);if(G.isSupported()){if("NONE"===G.method){u=void 0;break}u||(u={}),u[G.keyFormat]&&(u=n({},u)),u[G.keyFormat]=G}else j.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+k+'"');break;case"START":f.startTimeOffset=Ht(k);break;case"MAP":var H=new Rt(k,f);if(b.duration){var $=new ie(i,c);qt($,H,r,u),m=$,b.initSegment=m,m.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=m.rawProgramDateTime)}else{var W=b.byteRangeEndOffset;if(W){var V=b.byteRangeStartOffset;P=W-V+"@"+V}else P=null;qt(b,H,r,u),m=b,A=!0}m.cc=S;break;case"SERVER-CONTROL":d&&zt(f,C,l),d=new Rt(k),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&&zt(f,C,l);var q=new Rt(k);f.partTarget=q.decimalFloatingPoint("PART-TARGET");break;case"PART":var z=f.partList;z||(z=f.partList=[]);var K=y>0?z[z.length-1]:void 0,Y=y++,X=new Rt(k,f),Q=new se(X,b,c,Y,K);z.push(Q),b.duration+=Q.duration;break;case"PRELOAD-HINT":var J=new Rt(k,f);f.preloadHint=J;break;case"RENDITION-REPORT":var Z=new Rt(k,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(Z);break;default:j.warn("line parsed but not handled: "+l)}}}L&&!L.relurl?(g.pop(),E-=L.duration,f.partList&&(f.fragmentHint=L)):f.partList&&(Vt(b,L,p),b.cc=S,f.fragmentHint=b,u&&jt(b,u,f)),f.targetduration||(f.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));var ee=g.length,te=g[0],re=g[ee-1];if((E+=f.skippedSegments*f.targetduration)>0&&ee&&re){f.averagetargetduration=E/ee;var ne=re.sn;f.endSN="initSegment"!==ne?ne:0,f.live||(re.endList=!0),te&&void 0===f.startCC&&(f.startCC=te.cc),R>0&&(function(e,t){for(var r=e[t],i=t;i--;){var s=e[i];if(!s)return;s.programDateTime=r.programDateTime-1e3*s.duration,r=s}}(g,R),te&&p.unshift(te))}else f.endSN=0,f.startCC=0;return f.fragmentHint&&(E+=f.fragmentHint.duration),f.totalduration=E,p.length&&f.dateRangeTagCount&&te&&Bt(p,f),f.endCC=S,f},e}();function Bt(e,t){var r=e.length;if(r)for(var i=e[r-1],s=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges),a=n.length;a--;){var o=t.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=i.ref;for(var h=r;h--;){var u=Ut(t,l,e,h,s);if(-1!==u){o.tagAnchor=t.fragments[u].ref;break}}}}function Ut(e,t,r,i,s){var n=r[i];if(n){var a,o=n.programDateTime;if((t>=o||0===i)&&t<=o+1e3*(((null==(a=r[i+1])?void 0:a.start)||s)-n.start)){var l=r[i].sn-e.startSN,h=e.fragments;if(h.length>r.length)for(var u=(r[i+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 Gt(e,t,r){var i,s,n=new Rt(e,r),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,u=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&j.error("Invalid IV: "+n.IV);var d=o?Ft.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Ct(a,d,u,c,l)}function Ht(e){var t=new Rt(e).decimalFloatingPoint("TIME-OFFSET");return _(t)?t:null}function $t(e,t){var r=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var i=r.filter((function(t){return ke(t,e)}));i.length&&(t[e+"Codec"]=i.map((function(e){return e.split("/")[0]})).join(","),r=r.filter((function(e){return-1===i.indexOf(e)})))})),t.unknownCodecs=r}function Wt(e,t,r){var i=t[r];i&&(e[r]=i)}function Vt(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function qt(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function jt(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||i.push(e)}function zt(e,t,r){e.playlistParsingError=new Error("#EXT-X-"+t+" must not appear more than once ("+r[0]+")")}function Kt(e,t,r){e.playlistParsingError=new Error("#EXT-X-"+t+" must appear before the first Media Segment ("+r[0]+")")}function Yt(e,t){var r=t.startPTS;if(_(r)){var i,s=0;t.sn>e.sn?(s=r-e.start,i=e):(s=e.start-r,i=t),i.duration!==s&&i.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 Xt(e,t,r,i,s,n){i-r<=0&&(j.warn("Fragment should have a positive duration",t),i=r+t.duration,n=s+t.duration);var a=r,o=i,l=t.startPTS,h=t.endPTS;if(_(l)){var u=Math.abs(l-r);_(t.deltaPTS)?t.deltaPTS=Math.max(u,t.deltaPTS):t.deltaPTS=u,a=Math.max(r,l),r=Math.min(r,l),s=Math.min(s,t.startDTS),o=Math.min(i,h),i=Math.max(i,h),n=Math.max(n,t.endDTS)}var d=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=a,t.startDTS=s,t.endPTS=i,t.minEndPTS=o,t.endDTS=n;var c,f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;var g=f-e.startSN,p=e.fragments;for(p[g]=t,c=g;c>0;c--)Yt(p[c],p[c-1]);for(c=g;c<p.length-1;c++)Yt(p[c],p[c+1]);return e.fragmentHint&&Yt(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function Qt(e,t){if(e!==t){for(var r,i=null,s=e.fragments,a=s.length-1;a>=0;a--){var o=s[a].initSegment;if(o){i=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(i?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(i&&!d&&u&&(d=t.fragments[h]=u),u&&d){if(r(u,d,h,o),u.url&&u.url!==d.url)return void(t.playlistParsingError=Jt("media sequence mismatch "+d.sn+":",e,t,0,d));if(u.cc!==d.cc)return void(t.playlistParsingError=Jt("discontinuity sequence mismatch ("+u.cc+"!="+d.cc+")",e,t,0,d))}}}(e,t,(function(e,s,n,a){if((!t.startCC||t.skippedSegments)&&s.cc!==e.cc){for(var o=e.cc-s.cc,l=n;l<a.length;l++)a[l].cc+=o;t.endCC=a[a.length-1].cc}_(e.startPTS)&&_(e.endPTS)&&(s.setStart(s.startPTS=e.startPTS),s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.setDuration(e.endPTS-e.startPTS),s.duration&&(r=s),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(s.elementaryStreams=e.elementaryStreams),s.loader=e.loader,e.hasStats&&(s.stats=e.stats),e.initSegment&&(s.initSegment=e.initSegment,i=e.initSegment)}));var l=t.fragments,h=t.fragmentHint?l.concat(t.fragmentHint):l;if(i&&h.forEach((function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)})),t.skippedSegments){if(t.deltaUpdateFailed=l.some((function(e){return!e})),t.deltaUpdateFailed){j.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var u=t.skippedSegments;u--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t){var r=t.dateRanges,i=t.recentlyRemovedDateranges,s=n({},e);i&&i.forEach((function(e){delete s[e]}));var a=Object.keys(s).length;return a&&Object.keys(r).forEach((function(e){var t=s[e],i=new Pt(r[e].attr,t);i.isValid?(s[e]=i,t||(i.tagOrder+=a)):j.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+Qe(r[e].attr)+'"')})),s}(e.dateRanges,t));var d=e.fragments.filter((function(e){return e.rawProgramDateTime}));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var c=1;c<h.length;c++)null===h[c].programDateTime&&Vt(h[c],h[c-1],d);Bt(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,g=tr(e,t.startSN-1);t.startCC=null!=(f=null==g?void 0:g.cc)?f:l[0].cc}!function(e,t,r){if(e&&t)for(var i=0,s=0,n=e.length;s<=n;s++){var a=e[s],o=t[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?r(a,o):i--}}(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),r?Xt(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):Zt(e,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var p=t.advancedDateTime;if(t.advanced&&p){var m=t.edge;t.driftStart||(t.driftStartTime=p,t.driftStart=m),t.driftEndTime=p,t.driftEnd=m}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Jt(e,t,r,i,s){return new Error(e+" "+s.url+"\nPlaylist starting @"+t.startSN+"\n"+t.m3u8+"\n\nPlaylist starting @"+r.startSN+"\n"+r.m3u8)}function Zt(e,t,r){void 0===r&&(r=!0);var i=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,n=i>=0,a=0;if(n&&i<s.length)a=s[i].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&r)a=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}!function(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,a)}function er(e,t){void 0===t&&(t=1/0);var r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var s=1e3*i[i.length-1].duration;s<r&&(r=s)}}else r/=2;return Math.round(r)}function tr(e,t,r){if(!e)return null;var i=e.fragments[t-e.startSN];return i||((i=e.fragmentHint)&&i.sn===t?i:t<e.startSN&&r&&r.sn===t?r:null)}function rr(e,t,r){return e?ir(e.partList,t,r):null}function ir(e,t,r){if(e)for(var i=e.length;i--;){var s=e[i];if(s.index===r&&s.fragment.sn===t)return s}return null}function sr(e){e.forEach((function(e,t){var r;null==(r=e.details)||r.fragments.forEach((function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}var nr=function(e){function t(t){var r;return(r=e.call(this,"content-steering",t.logger)||this).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=t,r.registerListeners(),r}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.ERROR,this.onError,this))},r.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},r.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)}},r.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},r.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},r.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},r.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},r.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},r.onManifestLoaded=function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},r.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},r.onError=function(e,t){var r=t.errorAction;if(2===(null==r?void 0:r.action)&&1===r.flags){var i=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&&i?n=this.getPathwayForGroupId(o,h,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&i&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),r.resolved=this.pathwayId!==n),r.resolved||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+n+" levels: "+(i?i.length:i)+" priorities: "+Qe(s)+" penalized: "+Qe(this.penalizedPathways))}},r.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t},r.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},r.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(e){i-r[e]>3e5&&delete r[e]}));for(var s=0;s<e.length;s++){var n=e[s];if(!(n in r)){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,sr(t),this.hls.trigger(P.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}}}},r.getPathwayForGroupId=function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),s=0;s<i.length;s++)if(t===D&&i[s].hasAudioGroup(e)||t===C&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return r},r.clonePathways=function(e){var t=this,r=this.levels;if(r){var i={},s={};e.forEach((function(e){var n=e.ID,a=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some((function(e){return e.pathwayId===n}))){var l=t.getLevelsForPathway(a).map((function(e){var t=new Rt(e.attrs);t["PATHWAY-ID"]=n;var r=t.AUDIO&&t.AUDIO+"_clone_"+n,a=t.SUBTITLES&&t.SUBTITLES+"_clone_"+n;r&&(i[t.AUDIO]=r,t.AUDIO=r),a&&(s[t.SUBTITLES]=a,t.SUBTITLES=a);var l=or(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new Ye({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}));r.push.apply(r,l),ar(t.audioTracks,i,o,n),ar(t.subtitleTracks,s,o,n)}}))}},r.loadSteeringManifest=function(e){var t,r=this,i=this.hls.config,s=i.loader;this.loader&&this.loader.destroy(),this.loader=new s(i);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||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+n)}var a={responseType:"json",url:t.href},o=i.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,i,s,n){r.log('Loaded steering manifest: "'+t+'"');var a=e.data;if(1===(null==a?void 0:a.VERSION)){r.updated=performance.now(),r.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(e){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}r.scheduleRefresh(r.uri||s.url),l&&r.clonePathways(l);var u={steeringManifest:a,url:t.toString()};r.hls.trigger(P.STEERING_MANIFEST_LOADED,u),h&&r.updatePathwayPriority(h)}else r.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(e,t,i,s){if(r.log("Error loading steering manifest: "+e.code+" "+e.text+" ("+t.url+")"),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest "+t.url+" no longer available");var n=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,n);else{var a=r.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(n=1e3*parseFloat(o))}r.log("Steering manifest "+t.url+" rate limited")}},onTimeout:function(e,t,i){r.log("Timeout loading steering manifest ("+t.url+")"),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: "+t),this.loader.load(a,h,u)},r.scheduleRefresh=function(e,t){var r=this;void 0===t&&(t=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var t,i=null==(t=r.hls)?void 0:t.media;!i||i.ended?r.scheduleRefresh(e,1e3*r.timeToLoad):r.loadSteeringManifest(e)}),t)},i(t,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}}])}(F);function ar(e,t,r,i){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 Rt(a.attrs),a.url=a.attrs.URI=or(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=i,a}));e.push.apply(e,a)}))}function or(e,t,r,i){var s,n=i.HOST,a=i.PARAMS,o=i[r];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 lr=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(P.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(P.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListeners=function(){this.hls.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(P.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 r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var s=i-this.lastTime,n=r-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*n/s,l=this.hls;if(l.trigger(P.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:r}),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(P.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,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}(),hr=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,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,s=0;s<e.length;s++){var n=e[s];r.set(n,i),i+=n.length}return r}(t,r),this.reset(),e):new Uint8Array(0)},t.reset=function(){this.chunks.length=0,this.dataLength=0},e}();function ur(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 dr(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 cr(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,(r|=(127&e[t+2])<<7)|127&e[t+3]}function fr(e,t){for(var r=t,i=0;dr(e,t);)i+=10,i+=cr(e,t+6),ur(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(r,r+i)}function gr(e,t){return 255===e[t]&&240==(246&e[t+1])}function pr(e,t){return 1&e[t+1]?7:9}function mr(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function vr(e,t){return t+1<e.length&&gr(e,t)}function yr(e,t){if(vr(e,t)){var r=pr(e,t);if(t+r>=e.length)return!1;var i=mr(e,t);if(i<=r)return!1;var s=t+i;return s===e.length||vr(e,s)}return!1}function Er(e,t,r,i,s){if(!e.samplerate){var a=function(e,t,r,i){var s=t[r+2],n=s>>2&15;if(!(n>12)){var a=1+(s>>6&3),o=t[r+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 j.log("manifest codec:"+i+", 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:i}}var c=new Error("invalid ADTS sampling index:"+n);e.emit(P.ERROR,P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}(t,r,i,s);if(!a)return;n(e,a)}}function Sr(e){return 9216e4/e}function Tr(e,t,r,i,s){var n,a=i+s*Sr(e.samplerate),o=function(e,t){var r=pr(e,t);if(t+r<=e.length){var i=mr(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,h=o.headerLength,u=h+l,d=Math.max(0,r+u-t.length);d?(n=new Uint8Array(u-h)).set(t.subarray(r+h,t.length),0):n=t.subarray(r+h,r+u);var c={unit:n,pts:a};return d||e.samples.push(c),{sample:c,length:u,missing:d}}var f=t.length-r;return(n=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:n,pts:a},length:f,missing:-1}}function _r(e,t){return dr(e,t)&&cr(e,t+6)+10<=e.length-t}function Lr(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=1/0),function(e,t,r,i){var s=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.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 i(s,u,Math.floor(Math.min(u+Math.max(r,0),l))-u)}(e,t,r,Uint8Array)}function br(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Y(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=Y(e.data.subarray(t),!0);t+=r.length+1;var i=Y(e.data.subarray(t));return{key:e.type,info:r,data:i}}var s=Y(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 r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=Y(Lr(e.data,1,r)),s=e.data[2+r],n=e.data.subarray(3+r).indexOf(0);if(-1!==n){var a,o=Y(Lr(e.data,3+r,n));return a="--\x3e"===i?Y(Lr(e.data,4+r+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+r+n)),t.mimeType=i,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,r=Y(e.data.subarray(t),!0);t+=r.length+1;var i=Y(e.data.subarray(t));return{key:e.type,info:r,data:i}}var s=Y(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]),r=cr(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}var Ar=10,Pr=10;function wr(e){for(var t=0,r=[];dr(e,t);){var i=cr(e,t+6);e[t+5]>>6&1&&(t+=Ar);for(var s=(t+=Ar)+i;t+Pr<s;){var n=Rr(e.subarray(t)),a=br(n);a&&r.push(a),t+=n.size+Ar}ur(e,t)&&(t+=Ar)}return r}function Ir(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Dr(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function Cr(e){for(var t=wr(e),r=0;r<t.length;r++){var i=t[r];if(Ir(i))return Dr(i)}}var kr=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 Mr(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 xr=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,r,i){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,r){},t.demux=function(e,t){this.cachedData&&(e=Le(this.cachedData,e),this.cachedData=null);var r,i=fr(e,0),s=i?i.length:0,n=this._audioTrack,a=this._id3Track,o=i?Cr(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&_(o))&&(this.basePTS=Or(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:kr.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,r=s+=h.length):s=l}else _r(e,s)?(i=fr(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:kr.audioId3,duration:Number.POSITIVE_INFINITY}),r=s+=i.length):s++;if(s===l&&r!==l){var u=e.slice(r);this.cachedData?this.cachedData=Le(this.cachedData,u):this.cachedData=u}}return{audioTrack:n,videoTrack:Mr(),id3Track:a,textTrack:Mr()}},t.demuxSampleAes=function(e,t,r){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:Mr(),id3Track:this._id3Track,textTrack:Mr()}},t.destroy=function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},e}(),Or=function(e,t,r){return _(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},Nr=null,Fr=[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],Br=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ur=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Gr=[0,1,1,4];function Hr(e,t,r,i,s){if(!(r+24>t.length)){var n=$r(t,r);if(n&&r+n.frameLength<=t.length){var a=i+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(r,r+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 r=e[t+1]>>3&3,i=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==n){var a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Fr[14*(3===r?3-i:3===i?3:4)+s-1],h=Br[3*(3===r?0:2===r?1:2)+n],u=3===o?1:2,d=Ur[r][i],c=Gr[i],f=8*d*c,g=Math.floor(d*l/h+a)*c;if(null===Nr){var p=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Nr=p?parseInt(p[1]):0}return!!Nr&&Nr<=87&&2===i&&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 Vr(e,t){return t+1<e.length&&Wr(e,t)}function qr(e,t){if(t+1<e.length&&Wr(e,t)){var r=$r(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var s=t+i;return s===e.length||Vr(e,s)}return!1}var jr=function(e){function t(t,r){var i;return(i=e.call(this)||this).observer=void 0,i.config=void 0,i.observer=t,i.config=r,i}o(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,s){e.prototype.resetInitSegment.call(this,t,r,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e,t){if(!e)return!1;var r=fr(e,0),i=(null==r?void 0:r.length)||0;if(qr(e,i))return!1;for(var s=e.length;i<s;i++)if(yr(e,i))return t.log("ADTS sync word found !"),!0;return!1},r.canParse=function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&gr(e,t)&&mr(e,t)<=e.length-t}(e,t)},r.appendFrame=function(e,t,r){Er(e,this.observer,t,r,e.manifestCodec);var i=Tr(e,t,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i},t}(xr),zr=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,s){e.prototype.resetInitSegment.call(this,t,r,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:s,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=fr(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Cr(t)&&function(e,t){var r=0,i=5;t+=i;for(var s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);i>0;){a[0]=e[t];var o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,r=r?r<<o|s[0]:s[0],t+=1,i-=o}return r}(e,r)<=16)return!1;for(var i=e.length;r<i;r++)if(qr(e,r))return j.log("MPEG Audio sync word found !"),!0;return!1},r.canParse=function(e,t){return function(e,t){return Wr(e,t)&&4<=e.length-t}(e,t)},r.appendFrame=function(e,t,r){if(null!==this.basePTS)return Hr(e,t,r,this.basePTS,this.frameIndex)},t}(xr),Kr=function(){function e(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}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}(),Yr=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),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},t.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],s=r[1],n=r[2],a=r[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 m=g^g<<1^g<<2^g<<3^g<<4;m=m>>>8^255&m^99,e[f]=m,t[m]=f;var v=c[f],y=c[v],E=c[y],S=257*c[m]^16843008*m;i[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*v^16843008*f,l[m]=S<<24|S>>>8,h[m]=S<<16|S>>>16,u[m]=S<<8|S>>>24,d[m]=S,f?(f=v^c[c[c[E^v]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){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],m=g[1],v=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]]^m[c[l>>>16&255]]^v[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,r){for(var i,s,n,a,o,l,h,u,d,c,f,g,p,m,v=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,S=this.invSubMix,T=S[0],_=S[1],L=S[2],b=S[3],R=this.uint8ArrayToUint32Array_(r),A=R[0],P=R[1],w=R[2],I=R[3],D=new Int32Array(e),C=new Int32Array(D.length),k=this.networkToHostOrderSwap;t<D.length;){for(d=k(D[t]),c=k(D[t+1]),f=k(D[t+2]),g=k(D[t+3]),o=d^y[0],l=g^y[1],h=f^y[2],u=c^y[3],p=4,m=1;m<v;m++)i=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=i,l=s,h=n,u=a,p+=4;i=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],C[t]=k(i^A),C[t+1]=k(a^P),C[t+2]=k(n^w),C[t+3]=k(s^I),A=d,P=c,w=f,I=g,t+=4}return C.buffer},e}(),Xr=function(){function e(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}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}(),Qr=function(){function e(e,t){var r=(void 0===t?{}:t).removePKCS7Padding,i=void 0===r||r;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=i,i)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 r,i,s,n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(s=(i=(r=n).byteLength)&&new DataView(r.buffer).getUint8(i-1))?r.slice(0,i-s):r:n},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,r,i){var s=this;return this.useSoftware?new Promise((function(n,a){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);s.softwareDecrypt(o,t,r,i);var l=s.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)},t.softwareDecrypt=function(e,t,r,i){var s=this.currentIV,n=this.currentResult,a=this.remainderData;if(0!==i||16!==t.byteLength)return j.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Le(a,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;s&&(r=s);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Yr),l.expandKey(t);var h=n;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,h||null},t.webCryptoDecrypt=function(e,t,r,i){var s=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new Xr(this.subtle,t,i)}return this.fastAesKey.expandKey().then((function(t){return s.subtle?(s.logOnce("WebCrypto AES decrypt"),new Kr(s.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(n){return j.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+n.name+": "+n.message),s.onWebCryptoError(e,t,r,i)}))},t.onWebCryptoError=function(e,t,r,i){var s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);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,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t},t.logOnce=function(e){this.logEnabled&&(j.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),Jr=/\/emsg[-/]ID3/i,Zr=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,r,i){var s=this.videoTrack=Mr("video",1),n=this.audioTrack=Mr("audio",1),a=this.txtTrack=Mr("text",1);if(this.id3Track=Mr("id3",1),this.timeOffset=0,null!=e&&e.byteLength){var o=ve(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,m=f.codec;n.id=g,n.timescale=p,n.codec=m}a.id=le.text,s.sampleDuration=0,s.duration=n.duration=i}},t.resetContiguity=function(){this.remainderData=null},e.probe=function(e){return function(e){for(var t=e.byteLength,r=0;r<t;){var i=de(e,r);if(i>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Le(this.remainderData,e));var n=function(e){var t={valid:null,remainder:null},r=pe(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(r);this.remainderData=n.remainder,i.samples=n.valid||new Uint8Array}else i.samples=r;var a=this.extractID3Track(i,t);return s.samples=be(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=be(e,t),{videoTrack:t,audioTrack:Mr(),id3Track:i,textTrack:Mr()}},t.extractID3Track=function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var s=pe(e.samples,["emsg"]);s&&s.forEach((function(e){var s=function(e){var t=e[0],r="",i="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==he(e.subarray(h,h+1));)r+=he(e.subarray(h,h+1)),h+=1;for(r+=he(e.subarray(h,h+1)),h+=1;"\0"!==he(e.subarray(h,h+1));)i+=he(e.subarray(h,h+1)),h+=1;i+=he(e.subarray(h,h+1)),h+=1,s=de(e,12),n=de(e,16),o=de(e,20),l=de(e,24),h=28}else if(1===t){s=de(e,h+=4);var u=de(e,h+=4),d=de(e,h+=4);for(h+=4,a=Math.pow(2,32)*u+d,L(a)||(a=Number.MAX_SAFE_INTEGER,j.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=de(e,h),l=de(e,h+=4),h+=4;"\0"!==he(e.subarray(h,h+1));)r+=he(e.subarray(h,h+1)),h+=1;for(r+=he(e.subarray(h,h+1)),h+=1;"\0"!==he(e.subarray(h,h+1));)i+=he(e.subarray(h,h+1)),h+=1;i+=he(e.subarray(h,h+1)),h+=1}return{schemeIdUri:r,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Jr.test(s.schemeIdUri)){var n=ei(s,t),a=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=s.payload;i.samples.push({data:o,len:o.byteLength,dts:n,pts:n,type:kr.emsg,duration:a})}else if(r.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=ei(s,t);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:l,pts:l,type:kr.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return i},t.demuxSampleAes=function(e,t,r){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 ei(e,t){return _(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var ti=function(){function e(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Qr(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,r){var i=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),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}))}},t.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,r),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,s=32;s<e.length-16;s+=160,i+=16)r.set(e.subarray(s,s+16),i);return r},t.getAvcDecryptedUnit=function(e,t){for(var r=new Uint8Array(t),i=0,s=32;s<e.length-16;s+=160,i+=16)e.set(r.subarray(i,i+16),s);return e},t.decryptAvcSample=function(e,t,r,i,s){var n=this,a=we(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,r+1,i)}))},t.decryptAvcSamples=function(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var s=e[t].units;!(r>=s.length);r++){var n=s[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,r,i,n),this.decrypter.isSync())))return}}},e}(),ri=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}},t.getLastNalUnit=function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var s=i.units;r=s[s.length-1]}return r},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var s=r[i-1];e.pts=s.pts,e.dts=s.dts}t.samples.push(e)}},t.parseNALu=function(e,t,r){var i,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(i=t[h++],a)if(1!==a)if(i)if(1===i){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=Le(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=i?0:2;else a=i?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=Le(p.data,t))}return e.naluState=a,l},e}(),ii=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,r=e.byteLength-t,i=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");i.set(e.subarray(r,r+s)),this.word=new DataView(i.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),r=this.word>>>32-t;if(e>32&&j.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?r<<t|this.readBits(t):r},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}(),si=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var r=t.prototype;return r.parsePES=function(e,t,r,i){var s,n=this,a=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),a.forEach((function(i){var a,h;switch(i.type){case 1:var u=!1;s=!0;var d,c=i.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,r.pts,r.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,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:s=!0,Pe(i.data,1,r.pts,t.samples);break;case 7:var g,p;s=!0,l=!0;var m=i.data,v=n.readSPS(m);if(!e.sps||e.width!==v.width||e.height!==v.height||(null==(g=e.pixelRatio)?void 0:g[0])!==v.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[m];for(var y=m.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=[i.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,r.pts,r.dts));break;case 12:s=!0;break;default:s=!1}o&&s&&o.units.push(i)})),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},r.getNALuType=function(e,t){return 31&e[t]},r.readSliceType=function(e){var t=new ii(e);return t.readUByte(),t.readUEG(),t.readUEG()},r.skipScalingList=function(e,t){for(var r=8,i=8,s=0;s<e;s++)0!==i&&(i=(r+t.readEG()+256)%256),r=0===i?r:i},r.readSPS=function(e){var t,r,i,s=new ii(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),m=this.skipScalingList.bind(this);h();var v=h();if(u(5),f(3),h(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){var y=d();if(3===y&&f(1),p(),p(),f(1),c())for(r=3!==y?8:12,i=0;i<r;i++)c()&&m(i<6?16:64,s)}p();var E=d();if(0===E)d();else if(1===E)for(f(1),g(),g(),t=d(),i=0;i<t;i++)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}(ri),ni=188,ai=function(){function e(e,t,r,i){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=r,this.logger=i,this.videoParser=null}e.probe=function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset "+i),-1!==i},e.syncOffset=function(e){for(var t=e.length,r=Math.min(940,t-ni)+1,i=0;i<r;){for(var s=!1,n=-1,a=0,o=i;o<t;o+=ni){if(71!==e[o]||t-o!==ni&&71!==e[o+ni]){if(a)return-1;break}if(a++,-1===n&&0!==(n=o)&&(r=Math.min(n+18612,e.length-ni)+1),s||(s=0===oi(e,o)),s&&a>1&&(0===n&&a>2||o+ni>r))return n}i++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:le[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,r,i,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.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,r,i,s){var n;void 0===i&&(i=!1),void 0===s&&(s=!1),i||(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,m=null,v=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=Le(this.remainderData,t)).length,this.remainderData=null),E<ni&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var S=Math.max(0,e.syncOffset(t));(E-=(E-S)%ni)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var T=0,_=S;_<E;_+=ni)if(71===t[_]){var L=!!(64&t[_+1]),b=oi(t,_),R=void 0;if((48&t[_+3])>>4>1){if((R=_+5+t[_+4])===_+ni)continue}else R=_+4;switch(b){case u:L&&(d&&(n=ci(d,this.logger))&&(null===this.videoParser&&"avc"===a.segmentCodec&&(this.videoParser=new si),null!==this.videoParser&&this.videoParser.parsePES(a,h,n,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(R,_+ni)),d.size+=_+ni-R);break;case c:if(L){if(g&&(n=ci(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n)}g={data:[],size:0}}g&&(g.data.push(t.subarray(R,_+ni)),g.size+=_+ni-R);break;case f:L&&(p&&(n=ci(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(t.subarray(R,_+ni)),p.size+=_+ni-R);break;case 0:L&&(R+=t[R]+1),y=this._pmtId=li(t,R);break;case y:L&&(R+=t[R]+1);var A=hi(t,R,this.typeSupported,i,this.observer,this.logger);(u=A.videoPid)>0&&(a.pid=u,a.segmentCodec=A.segmentVideoCodec),(c=A.audioPid)>0&&(o.pid=c,o.segmentCodec=A.segmentAudioCodec),(f=A.id3Pid)>0&&(l.pid=f),null===m||v||(this.logger.warn("MPEG-TS PMT found at "+_+" after unknown PID '"+m+"'. Backtracking to sync byte @"+S+" to parse all TS packets."),m=null,_=S-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=b}}else T++;T>0&&ui(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 P={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(P),P},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,r=e.audioTrack,i=e.videoTrack,s=e.id3Track,n=e.textTrack,a=i.pesData,o=r.pesData,l=s.pesData;if(a&&(t=ci(a,this.logger))?(null===this.videoParser&&"avc"===i.segmentCodec&&(this.videoParser=new si),null!==this.videoParser&&(this.videoParser.parsePES(i,n,t,!0),i.pesData=null)):i.pesData=a,o&&(t=ci(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t)}r.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=ci(l,this.logger))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=l},t.demuxSampleAes=function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new ti(this.observer,this.config,t);return this.decrypt(i,s)},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,s=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(function(){s.samples?t.decryptAvcSamples(s.samples,0,0,(function(){r(e)})):r(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(function(){r(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 r,i,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=Le(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(r=n,i=o.length;r<i-1&&!vr(o,r);r++);if(r!==n){var d,c=r<i-1;if(d=c?"AAC PES did not start with ADTS header,offset:"+r:"No ADTS header found in AAC PES",ui(this.observer,new Error(d),c,this.logger),!c)return}if(Er(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)s=t.pts;else{if(!a)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=Sr(e.samplerate);s=a.sample.pts+f}for(var g,p=0;r<i;){if(r+=(g=Tr(e,o,r,s,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;r<i-1&&!vr(o,r);r++);}},t.parseMPEGPES=function(e,t){var r=t.data,i=r.length,s=0,n=0,a=t.pts;if(void 0!==a)for(;n<i;)if(Vr(r,n)){var o=Hr(e,r,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){},t.parseID3PES=function(e,t){if(void 0!==t.pts){var r=n({},t,{type:this._videoTrack?kr.emsg:kr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function oi(e,t){return((31&e[t+1])<<8)+e[t+2]}function li(e,t){return(31&e[t+10])<<8|e[t+11]}function hi(e,t,r,i,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=oi(e,t),h=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){di("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(!i){di("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=l);break;case 3:case 4:r.mpeg||r.mp3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){di("AC-3",n);break}case 129:n.warn("AC-3 in M2TS support not included in build");break;case 6:if(-1===a.audioPid&&h>0)for(var u=t+5,d=h;d>2;){106===e[u]&&n.warn("AC-3 in M2TS support not included in build");var c=e[u+1]+2;u+=c,d-=c}break;case 194:case 135:return ui(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:return ui(s,new Error("Unsupported HEVC in M2TS found"),void 0,n),a}t+=h+5}return a}function ui(e,t,r,i){i.warn("parsing error: "+t.message),e.emit(P.ERROR,P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function di(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function ci(e,t){var r,i,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]=Le(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var h=r[7];192&h&&(n=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&h?n-(a=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[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=r[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=(r=l[c]).byteLength;if(u){if(u>g){u-=g;continue}r=r.subarray(u),g-=u,u=0}d.set(r,o),o+=g}return i&&(i-=s+3),{data:d,pts:n,dts:a,len:i}}return null}var fi=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}(),gi=Math.pow(2,32)-1,pi=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 r=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]),i=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:r,audio:i};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,r=arguments.length,i=new Array(r>1?r-1:0),s=1;s<r;s++)i[s-1]=arguments[s];for(var n=i.length,a=n;n--;)t+=i[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(i[n],t),t+=i[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,r){r*=t;var i=Math.floor(r/(gi+1)),s=Math.floor(r%(gi+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,i>>24,i>>16&255,i>>8&255,255&i,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,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(gi+1)),s=Math.floor(r%(gi+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,i>>24,i>>16&255,i>>8&255,255&i,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 r,i,s=t.samples||[],n=new Uint8Array(4+s.length);for(r=0;r<s.length;r++)i=s[r].flags,n[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.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 r,i,s,n=[],a=[];for(r=0;r<t.sps.length;r++)s=(i=t.sps[r]).byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)s=(i=t.pps[r]).byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(i));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 r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("mp3"===r&&"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"===r)return e.box(e.types.stsd,e.STSD,e.avc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+r+"/"+t.codec+")")},e.tkhd=function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,n=t.height||0,a=Math.floor(i/(gi+1)),o=Math.floor(i%(gi+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,r>>24&255,r>>16&255,r>>8&255,255&r,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,r){var i=e.sdtp(t),s=t.id,n=Math.floor(r/(gi+1)),a=Math.floor(r%(gi+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,i.length+16+20+8+16+8+8),i)},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 r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,s,n,a,o,l,h=t.samples||[],u=h.length,d=12+16*u,c=new Uint8Array(d);for(r+=8+d,c.set(["video"===t.type?1:0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<u;i++)n=(s=h[i]).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*i);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var r=e.moov(t);return Le(e.FTYP,r)},e.hvc1=function(e){return new Uint8Array},e}();function mi(e,t){return function(e,t,r,i){var s=1e3*e*(1/9e4);return Math.round(s)}(e)}pi.types=void 0,pi.HDLR_TYPES=void 0,pi.STTS=void 0,pi.STSC=void 0,pi.STCO=void 0,pi.STSZ=void 0,pi.VMHD=void 0,pi.SMHD=void 0,pi.STSD=void 0,pi.FTYP=void 0,pi.DINF=void 0;var vi=null,yi=null;function Ei(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Si=function(){function e(e,t,r,i){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.logger=i,this.ISGenerated=!1,null===vi){var s=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);vi=s?parseInt(s[1]):0}if(null===yi){var n=navigator.userAgent.match(/Safari\/(\d+)/i);yi=n?parseInt(n[1]):0}}var t=e.prototype;return t.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},t.resetTimeStamp=function(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e},t.resetNextTimestamp=function(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},t.resetInitSegment=function(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},t.getVideoStartPts=function(e){var t=!1,r=e[0].pts,i=e.reduce((function(e,i){var s=i.pts,n=s-e;return n<-4294967296&&(t=!0,n=(s=Ti(s,r))-e),n>0?e:s}),r);return t&&this.logger.debug("PTS rollover detected"),i},t.remux=function(e,t,r,i,s,n,a,o){var l,h,u,d,c,f,g=s,p=s,m=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!m||E)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var T,_,L,b,R=this.videoTrackConfig;(R&&(t.width!==R.width||t.height!==R.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(_=R.pixelRatio)?void 0:_[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(b=R.pixelRatio)?void 0:b[1]))||!R&&S||null===this.nextAudioPts&&E)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,s,n));var A,P=this.isVideoContiguous,w=-1;if(S&&(w=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,w>0){this.logger.warn("[mp4-remuxer]: Dropped "+w+" out of "+y+" video samples due to a missing keyframe");var I=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,A=p+=(t.samples[0].pts-I)/t.inputTimeScale}else-1===w&&(this.logger.warn("[mp4-remuxer]: No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&S){var D=this.getVideoStartPts(t.samples),C=(Ti(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,C),p+=Math.max(0,-C)}if(E){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||S||o===M?p:void 0),S){var k=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,p,P,k)}}else S&&(l=this.remuxVideo(t,p,P,0));l&&(l.firstKeyFrame=w,l.independent=-1!==w,l.firstKeyFramePTS=A)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=_i(r,s,this._initPTS,this._initDTS)),i.samples.length&&(d=Li(i,s,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:c}},t.generateIS=function(e,t,r,i){var s,n,a,o,l=e.samples,h=t.samples,u=this.typeSupported,d={},c=this._initPTS,f=!c||i,g="audio/mp4";if(f&&(s=n=1/0),e.config&&l.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(g="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}d.audio={id:"audio",container:g,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):pi.initSegment([e]),metadata:{channelCount:e.channelCount}},f&&(o=e.id,a=e.inputTimeScale,c&&a===c.timescale?f=!1:s=n=l[0].pts-Math.round(a*r))}if(t.sps&&t.pps&&h.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:pi.initSegment([t]),metadata:{width:t.width,height:t.height}},f)if(o=t.id,a=t.inputTimeScale,c&&a===c.timescale)f=!1;else{var p=this.getVideoStartPts(h),m=Math.round(a*r);n=Math.min(n,Ti(h[0].dts,p)-m),s=Math.min(s,p-m)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,f?(this._initPTS={baseTime:s,timescale:a},this._initDTS={baseTime:n,timescale:a}):s=a=void 0,{tracks:d,initPTS:s,timescale:a,trackId:o}},t.remuxVideo=function(e,t,r,i){var s,a,o=e.inputTimeScale,l=e.samples,h=[],u=l.length,d=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!r||null===c){var y=t*o,E=l[0].pts-Ti(l[0].dts,l[0].pts);vi&&null!==c&&Math.abs(y-E-c)<15e3?r=!0:c=y-E}for(var S=d.baseTime*o/d.timescale,T=0;T<u;T++){var _=l[T];_.pts=Ti(_.pts-S,c),_.dts=Ti(_.dts-S,c),_.dts<l[T>0?T-1:T].dts&&(v=!0)}v&&l.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),s=l[0].dts;var L=l[l.length-1].dts-s,b=L?Math.round(L/(u-1)):g||e.inputTimeScale/30;if(r){var w=s-c,I=w>b,D=w<-1;if((I||D)&&(I?this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+mi(w)+" ms ("+w+"dts) hole between fragments detected at "+t.toFixed(3)):this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+mi(-w)+" ms ("+w+"dts) overlapping between fragments detected at "+t.toFixed(3)),!D||c>=l[0].pts||vi)){s=c;var C=l[0].pts-w;if(I)l[0].dts=s,l[0].pts=C;else for(var k=!0,M=0;M<l.length&&!(l[M].dts>C&&k);M++){var x=l[M].pts;if(l[M].dts-=w,l[M].pts-=w,M<l.length-1){var O=l[M+1].pts;k=O<=l[M].pts==O<=x}}this.logger.log("Video: Initial PTS/DTS adjusted: "+mi(C)+"/"+mi(s)+", delta: "+mi(w)+" ms")}}for(var N=0,F=0,B=s=Math.max(0,s),U=0;U<u;U++){for(var G=l[U],H=G.units,$=H.length,W=0,V=0;V<$;V++)W+=H[V].data.length;F+=W,N+=$,G.length=W,G.dts<B?(G.dts=B,B+=b/4|0||1):B=G.dts,p=Math.min(G.pts,p),m=Math.max(G.pts,m)}a=l[u-1].dts;var q,j=F+4*N+8;try{q=new Uint8Array(j)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:R.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:j,reason:"fail allocating video mdat "+j})}var z=new DataView(q.buffer);z.setUint32(0,j),q.set(pi.types.mdat,4);for(var K=!1,Y=Number.POSITIVE_INFINITY,X=Number.POSITIVE_INFINITY,Q=Number.NEGATIVE_INFINITY,J=Number.NEGATIVE_INFINITY,Z=0;Z<u;Z++){for(var ee=l[Z],te=ee.units,re=0,ie=0,se=te.length;ie<se;ie++){var ne=te[ie],ae=ne.data,oe=ne.data.byteLength;z.setUint32(f,oe),f+=4,q.set(ae,f),f+=oe,re+=4+oe}var le=void 0;if(Z<u-1)g=l[Z+1].dts-ee.dts,le=l[Z+1].pts-ee.pts;else{var he=this.config,ue=Z>0?ee.dts-l[Z-1].dts:b;if(le=Z>0?ee.pts-l[Z-1].pts:b,he.stretchShortVideoTrack&&null!==this.nextAudioPts){var de=Math.floor(he.maxBufferHole*o),ce=(i?p+i*o:this.nextAudioPts)-ee.pts;ce>de?((g=ce-ue)<0?g=ue:K=!0,this.logger.log("[mp4-remuxer]: It is approximately "+ce/90+" ms to the next segment; using duration "+g/90+" ms for the last video frame.")):g=ue}else g=ue}var fe=Math.round(ee.pts-ee.dts);Y=Math.min(Y,g),Q=Math.max(Q,g),X=Math.min(X,le),J=Math.max(J,le),h.push(Ei(ee.key,g,re,fe))}if(h.length)if(vi){if(vi<70){var ge=h[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(yi&&J-X<Q-Y&&b/Q<.025&&0===h[0].cts){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var pe=s,me=0,ve=h.length;me<ve;me++){var ye=pe+h[me].duration,Ee=pe+h[me].cts;if(me<ve-1){var Se=ye+h[me+1].cts;h[me].duration=Se-Ee}else h[me].duration=me?h[me-1].duration:b;h[me].cts=0,pe=ye}}g=K||!g?b:g,this.nextAvcDts=c=a+g,this.videoSampleDuration=g,this.isVideoContiguous=!0;var Te={data1:pi.moof(e.sequenceNumber++,s,n(e,{samples:h})),data2:q,startPTS:p/o,endPTS:(m+g)/o,startDTS:s/o,endDTS:c/o,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Te},t.getSamplesPerFrame=function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}},t.remuxAudio=function(e,t,r,i,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,m=this.nextAudioPts||-1,v=t*a,y=u.baseTime*a/u.timescale;if(this.isAudioContiguous=r=r||g.length&&m>0&&(i&&Math.abs(v-m)<9e3||Math.abs(Ti(g[0].pts-y,v)-m)<20*h),g.forEach((function(e){e.pts=Ti(e.pts-y,v)})),!r||m<0){if(g=g.filter((function(e){return e.pts>=0})),!g.length)return;m=0===s?0:i&&!f?Math.max(0,v):g[0].pts}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,S=0,T=m;S<g.length;S++){var _=g[S],L=_.pts,b=L-T,w=Math.abs(1e3*b/a);if(b<=-E*h&&f)0===S&&(this.logger.warn("Audio frame @ "+(L/a).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*b/a)+" ms."),this.nextAudioPts=m=T=L);else if(b>=E*h&&w<1e4&&f){var I=Math.round(b/h);(T=L-I*h)<0&&(I--,T+=h),0===S&&(this.nextAudioPts=m=T),this.logger.warn("[mp4-remuxer]: Injecting "+I+" audio frame @ "+(T/a).toFixed(3)+"s due to "+Math.round(1e3*b/a)+" ms gap.");for(var D=0;D<I;D++){var C=Math.max(T,0),k=fi.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);k||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),k=_.unit.subarray()),g.splice(S,0,{unit:k,pts:C}),T+=h,S++}}_.pts=T,T+=h}for(var M,x=null,O=null,N=0,F=g.length;F--;)N+=g[F].unit.byteLength;for(var B=0,U=g.length;B<U;B++){var G=g[B],H=G.unit,$=G.pts;if(null!==O)c[B-1].duration=Math.round(($-O)/o);else{if(r&&"aac"===e.segmentCodec&&($=m),x=$,!(N>0))return;N+=p;try{M=new Uint8Array(N)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:R.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:N,reason:"fail allocating audio mdat "+N})}d||(new DataView(M.buffer).setUint32(0,N),M.set(pi.types.mdat,4))}M.set(H,p);var W=H.byteLength;p+=W,c.push(Ei(!0,l,W,0)),O=$}var V=c.length;if(V){var q=c[c.length-1];this.nextAudioPts=m=O+o*q.duration;var j=d?new Uint8Array(0):pi.moof(e.sequenceNumber++,x/o,n({},e,{samples:c}));e.samples=[];var z=x/a,K=m/a,Y={data1:j,data2:M,startPTS:z,endPTS:K,startDTS:z,endDTS:K,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,Y}},e}();function Ti(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function _i(e,t,r,i){var s=e.samples.length;if(s){for(var n=e.inputTimeScale,a=0;a<s;a++){var o=e.samples[a];o.pts=Ti(o.pts-r.baseTime*n/r.timescale,t*n)/n,o.dts=Ti(o.dts-i.baseTime*n/i.timescale,t*n)/n}var l=e.samples;return e.samples=[],{samples:l}}}function Li(e,t,r){var i=e.samples.length;if(i){for(var s=e.inputTimeScale,n=0;n<i;n++){var a=e.samples[n];a.pts=Ti(a.pts-r.baseTime*s/r.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 bi,Ri=function(){function e(e,t,r,i){this.logger=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.logger=i}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(e){this.initPTS=e,this.lastEndTime=null},t.resetNextTimestamp=function(){this.isVideoContiguous=!1,this.lastEndTime=null},t.resetInitSegment=function(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(function(e,t){if(!e||!t)return e;var r=t.keyId;return r&&t.isCommonEncryption&&pe(e,["moov","trak"]).forEach((function(e){var t=pe(e,["mdia","minf","stbl","stsd"])[0].subarray(8),i=pe(t,["enca"]),s=i.length>0;s||(i=pe(t,["encv"])),i.forEach((function(e){pe(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=function(e){var t=pe(e,["schm"])[0];if(t){var r=he(t.subarray(4,8));if("cbcs"===r||"cenc"===r)return pe(e,["schi","tenc"])[0]}return null}(e);if(t){var i=t.subarray(8,24);i.some((function(e){return 0!==e}))||(j.log("[eme] Patching keyId in 'enc"+(s?"a":"v")+">sinf>>tenc' box: "+X(i)+" -> "+X(r)),t.set(r,8))}}))}))})),e}(e,i)),this.emitInitSegment=!0},t.generateInitSegment=function(e){var t=this.audioCodec,r=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=ve(e);i.audio&&(t=Pi(i.audio,J,this.logger)),i.video&&(r=Pi(i.video,Z,this.logger));var s={};i.audio&&i.video?s.audiovideo={container:"video/mp4",codec:t+","+r,supplemental:i.video.supplemental,initSegment:e,id:"main"}:i.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?s.video={container:"video/mp4",codec:r,supplemental:i.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s},t.remux=function(e,t,r,i,s,n){var a,o,l=this.initPTS,h=this.lastEndTime,u={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};_(h)||(h=this.lastEndTime=s||0);var d=t.samples;if(null==d||!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.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g,p=function(e,t,r){for(var i={},s=pe(e,["moof","traf"]),n=0;n<s.length;n++){var a=s[n],o=pe(a,["tfhd"])[0],l=de(o,4),h=t[l];if(h){var u=i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:h.timescale,type:h.type}),d=pe(a,["tfdt"])[0];if(d){var c=d[0],f=de(d,4);1===c&&(f===ae?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=ae+1,f+=de(d,8))),_(f)&&(!_(u.start)||f<u.start)&&(u.start=f)}var g=h.default,p=de(o,0)|(null==g?void 0:g.flags),m=(null==g?void 0:g.duration)||0;8&p&&(m=de(o,2&p?12:8));for(var v=pe(a,["trun"]),y=u.start||0,E=0,S=m,T=0;T<v.length;T++){var L=v[T],b=de(L,4),R=u.sampleCount;u.sampleCount+=b;var A=1&L[3],P=4&L[3],w=1&L[2],I=2&L[2],D=4&L[2],C=8&L[2],k=8,M=b;for(A&&(k+=4),P&&b&&(1&L[k+1]||void 0!==u.keyFrameIndex||(u.keyFrameIndex=R),k+=4,w?(S=de(L,k),k+=4):S=m,I&&(k+=4),C&&(k+=4),y+=S,E+=S,M--);M--;)w?(S=de(L,k),k+=4):S=m,I&&(k+=4),D&&(1&L[k+1]||void 0===u.keyFrameIndex&&(u.keyFrameIndex=u.sampleCount-(M+1),u.keyFrameStart=y),k+=4),C&&(k+=4),y+=S,E+=S;!E&&m&&(E+=m*b)}u.duration+=E}}if(!Object.keys(i).some((function(e){return i[e].duration}))){for(var x=1/0,O=0,N=pe(e,["sidx"]),F=0;F<N.length;F++){var B=me(N[F]);if(null!=B&&B.references){x=Math.min(x,B.earliestPresentationTime/B.timescale);var U=B.references.reduce((function(e,t){return e+t.info.duration||0}),0);O=Math.max(O,U+B.earliestPresentationTime/B.timescale)}}O&&_(O)&&Object.keys(i).forEach((function(e){i[e].duration||(i[e].duration=O*i[e].timescale-i[e].start)}))}return i}(d,f,this.logger),m=f.audio?p[f.audio.id]:null,v=f.video?p[f.video.id]:null,y=Ai(v,1/0),E=Ai(m,1/0),S=Ai(v,0,!0),T=Ai(m,0,!0),L=s,b=0;if(m&&(!v||!l&&E<y||l&&l.trackId===f.audio.id)?(c.trackId=f.audio.id,g=m,b=T-E):v&&(c.trackId=f.video.id,g=v,b=S-y),g){var R=g.timescale;L=g.start/R,c.timescale=R,l||(c.initPTS=g.start-s*R,this.initPTS=l={baseTime:c.initPTS,timescale:R,trackId:c.trackId})}!n&&l||!function(e,t,r,i){if(null===e)return!0;var s=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-r)>s}(l,L,s,b)&&c.timescale===l.timescale||(c.initPTS=L-s,l&&1===l.timescale&&this.logger.warn("Adjusting initPTS @"+s+" from "+l.baseTime/l.timescale+" to "+c.initPTS),this.initPTS=l={baseTime:c.initPTS,timescale:1});var A=e?L-l.baseTime/l.timescale:h;!function(e,t,r){pe(t,["moof","traf"]).forEach((function(t){pe(t,["tfhd"]).forEach((function(i){var s=de(i,4),n=e[s];if(n){var a=n.timescale||9e4;pe(t,["tfdt"]).forEach((function(e){var t=e[0],i=r*a;if(i){var s=de(e,4);if(0===t)s-=i,ge(e,4,s=Math.max(s,0));else{s*=Math.pow(2,32),s+=de(e,8),s-=i,s=Math.max(s,0);var n=Math.floor(s/(ae+1)),o=Math.floor(s%(ae+1));ge(e,4,n),ge(e,8,o)}}}))}}))}))}(f,d,l.baseTime/l.timescale);var P=A+b;b>0?this.lastEndTime=P:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var w=!!f.audio,I=!!f.video,D="";w&&(D+="audio"),I&&(D+="video");var C={data1:d,startPTS:A,startDTS:A,endPTS:P,endDTS:P,type:D,hasAudio:w,hasVideo:I,nb:1,dropped:0};u.audio=w&&!I?C:void 0,u.video=I?C:void 0;var k=null==v?void 0:v.sampleCount;if(k){var M=v.keyFrameIndex,x=-1!==M;C.nb=k,C.dropped=0===M||this.isVideoContiguous?0:x?M:k,C.independent=x,C.firstKeyFrame=M,x&&v.keyFrameStart&&(C.firstKeyFramePTS=v.keyFrameStart-l.baseTime/l.timescale),this.isVideoContiguous||(u.independent=x),this.isVideoContiguous||(this.isVideoContiguous=x),C.dropped&&this.logger.warn("fmp4 does not start with IDR: firstIDR "+M+"/"+k+" dropped: "+C.dropped+" pts: "+(C.firstKeyFramePTS||"NA"))}return u.initSegment=c,u.id3=_i(r,s,l,l),i.samples.length&&(u.text=Li(i,s,l)),u},e}();function Ai(e,t,r){return void 0===r&&(r=!1),void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Pi(e,t,r){var i=null==e?void 0:e.codec;return i&&i.length>4?i:t===J?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?Ge(i,!1):(r.warn('Unhandled audio codec "'+i+'" in mp4 MAP'),i||"mp4a"):(r.warn('Unhandled video codec "'+i+'" in mp4 MAP'),i||"avc1")}try{bi=self.performance.now.bind(self.performance)}catch(e){bi=Date.now}var wi=[{demux:Zr,remux:Ri},{demux:ai,remux:Si},{demux:jr,remux:Si},{demux:zr,remux:Si}],Ii=function(){function e(e,t,r,i,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=r,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,r,i){var s=this,n=r.transmuxing;n.executeStart=bi();var a=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var h=i||o,u=h.contiguous,d=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,p=h.initSegmentChange,m=l.audioCodec,v=l.videoCodec,y=l.defaultInitPts,E=l.duration,S=l.initSegmentData,T=function(e,t){var r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}(a,t);if(T&&It(T.method)){var _=this.getDecrypter(),L=Dt(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,r);return s.decryptionPromise=null,t})),this.decryptionPromise;var b=_.softwareDecrypt(a,T.key.buffer,T.iv.buffer,L);if(r.part>-1){var w=_.flush();b=w?w.buffer:w}if(!b)return n.executeEnd=bi(),Di(r);a=new Uint8Array(b)}var I=this.needsProbing(d,c);if(I){var D=this.configureTransmuxer(a);if(D)return this.logger.warn("[transmuxer] "+D.message),this.observer.emit(P.ERROR,P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),n.executeEnd=bi(),Di(r)}(d||c||p||I)&&this.resetInitSegment(S,m,v,E,t),(d||p||I)&&this.resetInitialTimestamp(y),u||this.resetContiguity();var C=this.transmux(a,T,g,f,r);this.asyncResult=Ci(C);var k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,n.executeEnd=bi(),C},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=bi();var i=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(i){var l=i.flush();l&&a.push(this.push(l.buffer,null,e))}var h=this.demuxer,u=this.remuxer;if(!h||!u){r.executeEnd=bi();var d=[Di(e)];return this.asyncResult?Promise.resolve(d):d}var c=h.flush(o);return Ci(c)?(this.asyncResult=!0,c.then((function(r){return t.flushRemux(a,r,e),a}))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)},t.flushRemux=function(e,t,r){var i=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: "+r.sn+(r.part>-1?" part: "+r.part:"")+" of "+(this.id===k?"level":"track")+" "+r.level);var u=this.remuxer.remux(i,s,n,a,h,l,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=bi()},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i,s){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(e,t,r,i),a.resetInitSegment(e,t,r,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,r,i,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,s):this.transmuxUnencrypted(e,r,i,s)},t.transmuxUnencrypted=function(e,t,r,i){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,r,!1,this.id),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,s){var n=this;return this.demuxer.demuxSampleAes(e,t,r).then((function(e){return{remuxResult:n.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,n.id),chunkMeta:s}}))},t.configureTransmuxer=function(e){for(var t,r=this.config,i=this.observer,s=this.typeSupported,n=0,a=wi.length;n<a;n++){var o;if(null!=(o=wi[n].demux)&&o.probe(e,this.logger)){t=wi[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(i,r,s,this.logger)),l&&l instanceof d||(this.demuxer=new d(i,r,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 Qr(this.config)),e},e}(),Di=function(e){return{remuxResult:{},chunkMeta:e}};function Ci(e){return"then"in e&&e.then instanceof Function}var ki=function(e,t,r,i,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=r,this.duration=i,this.defaultInitPts=s||null},Mi=function(e,t,r,i,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=r,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=n},xi=/(\d+)-(\d+)\/(\d+)/,Oi=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||Ni,this.controller=new self.AbortController,this.stats=new Q}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,r){var i=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 r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(n({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}(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=r,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&_(u)?u:d,this.requestTimeout=self.setTimeout((function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(s,e,i.response))}),t.timeout),(Ci(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(r){var n;i.response=i.loader=r;var a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(i.requestTimeout),t.timeout=d,i.requestTimeout=self.setTimeout((function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(s,e,i.response))}),d-(a-s.loading.start)),!r.ok){var l=r.status,h=r.statusText;throw new Fi(h||"fetch, bad network response",l,r)}s.loading.first=a,s.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=xi.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(_(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(r.headers)||s.total;var u=null==(n=i.callbacks)?void 0:n.onProgress;return u&&_(t.highWaterMark)?i.loadProgressively(r,s,e,t.highWaterMark,u):o?r.arrayBuffer():"json"===e.responseType?r.json():r.text()})).then((function(r){var n,a,o=i.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(i.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);var h=r[l];h&&(s.loaded=s.total=h);var u={url:o.url,data:r,code:o.status},d=null==(n=i.callbacks)?void 0:n.onProgress;d&&!_(t.highWaterMark)&&d(s,e,r,o),null==(a=i.callbacks)||a.onSuccess(u,s,e,o)})).catch((function(t){var r;if(self.clearTimeout(i.requestTimeout),!s.aborted){var n=t&&t.code||0,a=t?t.message:null;null==(r=i.callbacks)||r.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,r,i,s){void 0===i&&(i=0);var n=new hr,a=e.body.getReader(),o=function(){return a.read().then((function(a){if(a.done)return n.dataLength&&s(t,r,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return t.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&s(t,r,n.flush().buffer,e)):s(t,r,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},e}();function Ni(e,t){return new self.Request(e.url,t)}var Fi=function(e){function t(t,r,i){var s;return(s=e.call(this,t)||this).code=void 0,s.details=void 0,s.code=r,s.details=i,s}return o(t,e),t}(f(Error)),Bi=/^age:\s*[\d.]+\s*$/im,Ui=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 Q,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,r){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=r,this.loadInternal()},t.loadInternal=function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=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===i&&!e.stats.aborted)return n(i,r.url)})).catch((function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),n(i,r.url)})).then((function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)})).catch((function(t){var n;null==(n=e.callbacks)||n.onError({code:i.status,text:t.message},r,i,s)})):this.openAndSendXhr(i,r,t)}},t.openAndSendXhr=function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,s=r.loadPolicy,n=s.maxTimeToFirstByteMs,a=s.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[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),r.timeout=n&&_(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()},t.readystatechange=function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,s=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.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-(r.loading.first-r.loading.start)))),4===i)){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;r.loading.end=Math.max(self.performance.now(),r.loading.first);var u="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=u,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var c={url:t.responseURL,data:o,code:n};return void(null==(h=this.callbacks)||h.onSuccess(c,r,e,t))}}var f,g=s.loadPolicy.errorRetry;dt(g,r.retry,!1,{url:e.url,data:void 0,code:n})?this.retry(g):(j.error(n+" while loading "+e.url),null==(f=this.callbacks)||f.onError({code:n,text:t.statusText},e,t,r))}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(dt(e,this.stats.retry,!0))this.retry(e);else{var t;j.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,r=this.stats;this.retryDelay=ht(e,r.retry),r.retry++,j.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?void 0:t.url)+", retrying "+r.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&&Bi.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}(),Gi={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Hi=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:Ui,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:tt,bufferController:Et,capLevelController:_t,errorController:ct,fpsController:lr,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:null,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!1,preserveManualLevelOnError:!1,certLoadPolicy:{default:Gi},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:Gi},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:K,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:nr,interstitialsController:void 0});function $i(e){return e&&"object"==typeof e?Array.isArray(e)?e.map($i):Object.keys(e).reduce((function(t,r){return t[r]=$i(e[r]),t}),{}):e}var Wi="NOT_LOADED",Vi="APPENDING",qi="PARTIAL",ji="OK",zi=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.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this)},t._unregisterListeners=function(){var e=this.hls;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this)},t.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var s=r[i];if(!s)break;var n=s.end;if(s.start<=e&&null!==n&&e<=n)return s}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){return this.getFragAtPos(e,t,!0)},t.getFragAtPos=function(e,t,r){for(var i=this.fragments,s=Object.keys(i),n=s.length;n--;){var a=i[s[n]];if((null==a?void 0:a.body.type)===t&&(!r||a.buffered)){var o=a.body;if(o.start<=e&&e<=o.end)return o}}return null},t.detectEvictedFragments=function(e,t,r,i,s){var n=this;this.timeRanges&&(this.timeRanges[e]=t);var a=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(i){var o=n.fragments[i];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 r=!n.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&n.removeFragment(o.body),r})):n.removeFragment(o.body))}else o.body.type===r&&n.removeFragment(o.body)}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges;if(r&&"initSegment"!==e.frag.sn){var i=e.frag,s=Yi(i),n=this.fragments[s];if(!(!n||n.buffered&&i.gap)){var a=!i.relurl;Object.keys(r).forEach((function(s){var o=i.elementaryStreams[s];if(o){var l=r[s],h=a||!0===o.partial;n.range[s]=t.getBufferedTimes(i,e.part,h,l)}})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ki(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}}},t.removeParts=function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Xi(r,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var r=Yi(e),i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)},t.getBufferedTimes=function(e,t,r,i){for(var s={time:[],partial:r},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n,h=0;h<i.length;h++){var u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(l>=u&&o<=d){s.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(a,i.end(h))});break}if(n<d&&a>u){var c=Math.max(n,i.start(h)),f=Math.min(a,i.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,r,i,s=null,n=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&Ki(h)&&(r=h.body.start-a,i=h.body.end+a,e>=r&&e<=i&&(t=Math.min(e-r,i-e),n<=t&&(s=h.body,n=t)))})),s},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Ki(t))},t.getState=function(e){var t=Yi(e),r=this.fragments[t];return r?r.buffered?Ki(r)?qi:ji:Vi:Wi},t.isTimeBuffered=function(e,t,r){for(var i,s,n=0;n<r.length;n++){if(i=r.start(n)-this.bufferPadding,s=r.end(n)+this.bufferPadding,e>=i&&t<=s)return!0;if(t<=i)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,s=Yi(r);this.fragments[s]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=t.frag,i=t.part,s=t.timeRanges,n=t.type;if("initSegment"!==r.sn){var a=r.type;if(i){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=s;var l=s[n];this.detectEvictedFragments(n,l,a,i)}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Yi(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var s=t[r[i]];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,r,i,s){var n=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=n.fragments[a];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||s)&&n.removeFragment(l)}}))},t.removeFragment=function(e){var t=Yi(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Xi(r,(function(e){return e.fragment.sn!==i}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var r=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;r&&r.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function Ki(e){var t,r,i;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(r=e.range.audio)?void 0:r.partial)||(null==(i=e.range.audiovideo)?void 0:i.partial))}function Yi(e){return e.type+"_"+e.level+"_"+e.sn}function Xi(e,t){return e.filter((function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r}))}var Qi=Math.pow(2,17),Ji=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 r=this,i=e.url;if(!i)return Promise.reject(new ts({type:R.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));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){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void l(es(e));e.gap=!1}var h=r.loader=n?new n(s):new a(s),d=Zi(e);e.loader=h;var c=ut(s.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Qi};e.stats=h.stats;var g={onSuccess:function(t,i,s,n){r.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){r.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:u({url:i,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:n,stats:a}))},onAbort:function(t,i,s){r.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:function(t,i,s){r.resetLoader(e,h),l(new ts({type:R.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(r,i,s,n){return t({frag:e,part:null,payload:s,networkDetails:n})}),h.load(d,f,g)}))},t.loadPart=function(e,t,r){var i=this;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||t.gap)l(es(e,t));else{var h=i.loader=n?new n(s):new a(s),d=Zi(e,t);e.loader=h;var c=ut(s.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Qi};t.stats=h.stats,h.load(d,f,{onSuccess:function(s,n,a,l){i.resetLoader(e,h),i.updateStatsFromPart(e,t);var u={frag:e,part:t,payload:s.data,networkDetails:l};r(u),o(u)},onError:function(r,s,n,a){i.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:u({url:d.url,data:void 0},r),error:new Error("HTTP Error "+r.code+" "+r.text),networkDetails:n,stats:a}))},onAbort:function(r,s,n){e.stats.aborted=t.stats.aborted,i.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:n,stats:r}))},onTimeout:function(r,s,n){i.resetLoader(e,h),l(new ts({type:R.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:r}))}})}}))},t.updateStatsFromPart=function(e,t){var r=e.stats,i=t.stats,s=i.total;if(r.loaded+=i.loaded,s){var n=Math.round(e.duration/t.duration),a=Math.min(Math.round(r.loaded/s),n),o=(n-a)*Math.round(r.loaded/a);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,h=i.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 Zi(e,t){void 0===t&&(t=null);var r,i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if(_(n)&&_(a)){var o,l=n,h=a;if("initSegment"===e.sn&&("AES-128"===(r=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===r)){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 es(e,t){var r=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),i={type:R.MEDIA_ERROR,details:A.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new ts(i)}var ts=function(e){function t(t){var r;return(r=e.call(this,t.error.message)||this).data=void 0,r.data=t,r}return o(t,e),t}(f(Error)),rs=function(e){function t(t,r){var i;return(i=e.call(this,t,r)||this)._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}o(t,e);var r=t.prototype;return r.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},r.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},r.onHandlerDestroyed=function(){},r.hasInterval=function(){return!!this._tickInterval},r.hasNextTick=function(){return!!this._tickTimer},r.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},r.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},r.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},r.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},r.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},r.doTick=function(){},t}(F),is=function(e,t,r,i,s,n){void 0===i&&(i=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=r,this.size=i,this.part=s,this.partial=n};function ss(e,t){for(var r=0,i=e.length;r<i;r++){var s;if((null==(s=e[r])?void 0:s.cc)===t)return e[r]}return null}function ns(e,t){if(e){var r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}function as(e,t){for(var r=t.fragments,i=0,s=r.length;i<s;i++)ns(r[i],e);t.fragmentHint&&ns(t.fragmentHint,e),t.alignedSliding=!0}var os={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_LEVEL:"WAITING_LEVEL"},ls=function(e){function t(t,r,i,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=os.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,r=e.fragCurrent,i=e.media,s=e.mediaBuffer,n=e.state,o=i?i.currentTime:0,l=pt.bufferInfo(s||i,o,t.maxBufferHole);if(a.log("media seeking to "+(_(o)?o.toFixed(3):o)+", state: "+n),a.state===os.ENDED)a.resetLoadingState();else if(r){var h=t.maxFragLookUpTolerance,u=r.start-h,d=r.start+r.duration+h;if(!l.len||d<l.start||u>l.end){var c=o>d;(o<u||c)&&(c&&r.loader&&(a.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),r.abortRequests(),a.resetLoadingState()),a.fragPrevious=null)}}if(i&&(a.fragmentTracker.removeFragmentsInRange(o,1/0,a.playlistType,!0),o>a.lastCurrentTime&&(a.lastCurrentTime=o),!a.loadingParts)){var f=Math.max(l.end,o),g=a.shouldLoadParts(a.getLevelDetails(),f);g&&(a.log("LL-Part loading ON after seeking to "+o.toFixed(2)+" with buffer @"+f.toFixed(2)),a.loadingParts=g)}a.hls.hasEnoughToStart||l.len||(a.log("setting startPosition to "+o+" because of seek before start"),a.nextLoadPosition=a.startPosition=o),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 Ji(t.config),a.keyLoader=i,a.fragmentTracker=r,a.config=t.config,a.decrypter=new Qr(t.config),a}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.ERROR,this.onError,this)},r.doTick=function(){this.onTickEnd()},r.onTickEnd=function(){},r.startLoad=function(e){},r.stopLoad=function(){if(this.state!==os.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=os.STOPPED}},r.pauseBuffering=function(){this.buffering=!1},r.resumeBuffering=function(){this.buffering=!0},r._streamEnded=function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=pt.bufferedInfo(s,e.start,0));var n=e.nextStart;if(n&&n>i&&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 pt.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)},r.getLevelDetails=function(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details},r.onMediaAttached=function(e,t){var r=this.media=this.mediaBuffer=t.media;r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),r.addEventListener("seeking",this.onMediaSeeking),r.addEventListener("ended",this.onMediaEnded);var i=this.config;this.levels&&i.autoStartLoad&&this.state===os.STOPPED&&this.startLoad(i.startPosition)},r.onMediaDetaching=function(e,t){var r=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},r.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},r.onError=function(e,t){},r.onManifestLoaded=function(e,t){this.startTimeOffset=t.startTimeOffset},r.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),e.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},r.onHandlerDestroyed=function(){this.state=os.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)},r.loadFragment=function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)},r._loadFragForPlayback=function(e,t,r){var i=this;this._doFragLoad(e,t,r,(function(e){var t=e.frag;if(i.fragContextChanged(t))return i.warn(t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+i.fragInfo(t,!1,e.part)+") was dropped during download."),void i.fragmentTracker.removeFragment(t);t.stats.chunkCount++,i._handleFragmentLoadProgress(e)})).then((function(e){if(e){var t=i.state,r=e.frag;i.fragContextChanged(r)?(t===os.FRAG_LOADING||!i.fragCurrent&&t===os.PARSING)&&(i.fragmentTracker.removeFragment(r),i.state=os.IDLE):("payload"in e&&(i.log("Loaded "+r.type+" sn: "+r.sn+" of "+i.playlistLabel()+" "+r.level),i.hls.trigger(P.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}})).catch((function(t){i.state!==os.STOPPED&&i.state!==os.ERROR&&(i.warn("Frag error: "+((null==t?void 0:t.message)||t)),i.resetFragmentLoading(e))}))},r.clearTrackerIfNeeded=function(e){var t,r=this.fragmentTracker;if(r.getState(e)===Vi){var i=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,i),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))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===qi&&r.removeFragment(e))},r.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)},r.waitForLive=function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)},r.flushMainBuffer=function(e,t,r){if(void 0===r&&(r=null),e-t){var i={startOffset:e,endOffset:t,type:r};this.hls.trigger(P.BUFFER_FLUSHING,i)}},r._loadInitSegment=function(e,t){var r=this;this._doFragLoad(e,t).then((function(e){var t=null==e?void 0:e.frag;if(!t||r.fragContextChanged(t)||!r.levels)throw new Error("init load aborted");return e})).then((function(e){var t=r.hls,i=e.frag,s=e.payload,n=i.decryptdata;if(s&&s.byteLength>0&&null!=n&&n.key&&n.iv&&It(n.method)){var a=self.performance.now();return r.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,Dt(n.method)).catch((function(e){throw t.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((function(s){var n=self.performance.now();return t.trigger(P.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:a,tdecrypt:n}}),e.payload=s,r.completeInitSegmentLoad(e)}))}return r.completeInitSegmentLoad(e)})).catch((function(t){r.state!==os.STOPPED&&r.state!==os.ERROR&&(r.warn(t),r.resetFragmentLoading(e))}))},r.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==os.STOPPED&&(this.state=os.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()},r.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},r.fragBufferedComplete=function(e,t){var r=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:"+(r?function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="["+e.start(i).toFixed(3)+"-"+e.end(i).toFixed(3)+"]";return t}(pt.getBuffered(r)):"(detached)")+")"),re(e)){var i;if(e.type!==x){var s=e.elementaryStreams;if(!Object.keys(s).some((function(e){return!!s[e]})))return void(this.state=os.IDLE)}var n=null==(i=this.levels)?void 0:i[e.level];null!=n&&n.fragmentError&&(this.log("Resetting level fragment error count of "+n.fragmentError+" on frag buffered"),n.fragmentError=0)}this.state=os.IDLE},r._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,s=e.partsLoaded,n=!s||0===s.length||s.some((function(e){return!e})),a=new is(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}},r._handleFragmentLoadProgress=function(e){},r._doFragLoad=function(e,t,r,i){var s,n=this;void 0===r&&(r=null),this.fragCurrent=e;var a=null==t?void 0:t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var o=null;!e.encrypted||null!=(s=e.decryptdata)&&s.key?e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments))&&this.log("[eme] blocking frag load until media-keys acquired"):(this.log("Loading key for "+e.sn+" of ["+a.startSN+"-"+a.endSN+"], "+this.playlistLabel()+" "+e.level),this.state=os.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(P.KEY_LOADED,e),n.state===os.KEY_LOADING&&(n.state=os.IDLE),e})),this.hls.trigger(P.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));var l=this.fragPrevious;if(re(e)&&(!l||e.sn!==l.sn)){var h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log("LL-Part loading "+(h?"ON":"OFF")+" loading sn "+(null==l?void 0:l.sn)+"->"+e.sn),this.loadingParts=h)}if(r=Math.max(e.start,r||0),this.loadingParts&&re(e)){var u=a.partList;if(u&&i){r>e.end&&a.fragmentHint&&(e=a.fragmentHint);var d=this.getNextPart(u,e,r);if(d>-1){var c,f=u[d];return e=this.fragCurrent=f.fragment,this.log("Loading "+e.type+" sn: "+e.sn+" part: "+f.index+" ("+d+"/"+(u.length-1)+") of "+this.fragInfo(e,!1,f)+") cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=f.start+f.duration,this.state=os.FRAG_LOADING,c=o?o.then((function(r){return!r||n.fragContextChanged(r.frag)?null:n.doFragPartsLoad(e,f,t,i)})).catch((function(e){return n.handleFragLoadError(e)})):this.doFragPartsLoad(e,f,t,i).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(P.FRAG_LOADING,{frag:e,part:f,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(u,r))return Promise.resolve(null)}}if(re(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+r.toFixed(2)),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?"["+a.startSN+"-"+a.endSN+"]":"")+", target: "+parseFloat(r.toFixed(3))),_(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=os.FRAG_LOADING;var g,p=this.config.progressive;return g=p&&o?o.then((function(t){return!t||n.fragContextChanged(null==t?void 0:t.frag)?null:n.fragmentLoader.load(e,i)})).catch((function(e){return n.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,p?i:void 0),o]).then((function(e){var t=e[0];return!p&&t&&i&&i(t),t})).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(P.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g},r.doFragPartsLoad=function(e,t,r,i){var s=this;return new Promise((function(n,a){var o,l=[],h=null==(o=r.details)?void 0:o.partList,u=function(t){s.fragmentLoader.loadPart(e,t,i).then((function(i){l[t.index]=i;var a=i.part;s.hls.trigger(P.FRAG_LOADED,i);var o=rr(r.details,e.sn,t.index+1)||ir(h,e.sn,t.index+1);if(!o)return n({frag:e,part:a,partsLoaded:l});u(o)})).catch(a)};u(t)}))},r.handleFragLoadError=function(e){if("data"in e){var t=e.data;e.data&&t.details===A.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(P.ERROR,t)}else this.hls.trigger(P.ERROR,{type:R.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},r._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===os.PARSING){var r=t.frag,i=t.part,s=t.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n);var a=this.getLevelDetails(),o=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+r.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(r,i,s,e.partial)}else this.fragCurrent||this.state===os.STOPPED||this.state===os.ERROR||(this.state=os.IDLE)},r.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var r,i,s=e.partList[0];if(t>=s.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0)&&(this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}return!1},r.getCurrentContext=function(e){var t=this.levels,r=this.fragCurrent,i=e.level,s=e.sn,n=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment "+s+" of "+this.playlistLabel()+" "+i+". The current chunk will not be buffered."),null;var a=t[i],o=a.details,l=n>-1?rr(o,s,n):null,h=l?l.fragment:tr(o,s,r);return h?(r&&r!==h&&(h.stats=r.stats),{frag:h,part:l,level:a}):null},r.bufferFragmentData=function(e,t,r,i,s){var n;if(e&&this.state===os.PARSING){var a=e.data1,o=e.data2,l=a;if(a&&o&&(l=Le(a,o)),null!=(n=l)&&n.length){var h={type:e.type,frag:t,part:r,chunkMeta:i,parent:t.type,data:l};if(this.hls.trigger(P.BUFFER_APPENDING,h),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}}},r.flushBufferGap=function(e){var t=this.media;if(t)if(pt.isBuffered(t,t.currentTime)){var r=t.currentTime,i=pt.bufferInfo(t,r,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,i.end-n),r+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}else this.flushMainBuffer(0,e.start)},r.getFwdBufferInfo=function(e,t){var r,i=this.getLoadPosition();if(!_(i))return null;var s=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,s)},r.getFwdBufferInfoAtPos=function(e,t,r,i){var s=pt.bufferInfo(e,t,i);if(0===s.len&&void 0!==s.nextStart){var n=this.fragmentTracker.getBufferedFrag(t,r);if(n&&(s.nextStart<=n.end||n.gap)){var a=Math.max(Math.min(s.nextStart,n.end)-t,i);return pt.bufferInfo(e,t,a)}}return s},r.getMaxBufferLength=function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)},r.reduceMaxBufferLength=function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t),s=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return s>=i&&(r.maxMaxBufferLength=s,this.warn("Reduce max buffer length to "+s+"s"),!0)},r.getAppendedFrag=function(e,t){var r;void 0===t&&(t=k);var i=null==(r=this.fragmentTracker)?void 0:r.getAppendedFrag(e,t);return i&&"fragment"in i?i.fragment:i},r.getNextFragment=function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var s=this.config,n=r[0].start,a=s.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=s.initialLiveManifestSize;if(i<l)return this.warn("Not enough fragments to start playback (have: "+i+", 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=r[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(r[p+1]||null,t)}return this.mapToInitFragWhenRequired(g)},r.isLoopLoading=function(e,t){var r=this.fragmentTracker.getState(e);return(r===ji||r===qi&&!!e.gap)&&this.nextLoadPosition>t},r.getNextFragmentLoopLoading=function(e,t,r,i,s){var n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t))&&!n.gap&&r.nextStart){var a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==a&&r.len+a.len>=s){var o=n.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,n},r.filterReplacedPrimary=function(e,t){return e?(this.hls.config,e):e},r.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment},r.getNextPart=function(e,t,r){for(var i=-1,s=!1,n=!0,a=0,o=e.length;a<o;a++){var l=e[a];if(n=n&&!l.independent,i>-1&&r<l.start)break;var h=l.loaded;h?i=-1:(s||l.independent||n)&&l.fragment===t&&(i=a),s=h}return i},r.loadedEndOfParts=function(e,t){var r=e[e.length-1];return r&&t>r.start&&r.loaded},r.getInitialLiveFragment=function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!_(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i<e.length;++i){var s=e[i];if(at(t,r,s))return s}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){var n=t[s-e.startSN];r.cc===n.cc&&(i=n,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,s=e.fragments,n=e.fragmentHint;return n&&(s=s.concat(n)),it(s,(function(e){return e.cc<t?1:e.cc>t?-1:(i=e,e.end<=r?1:e.start>r?-1:0)})),i||null}return null}(e,r.cc,r.end),i&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn))}}else{var a=this.hls.liveSyncPosition;null!==a&&(i=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},r.getFragmentAtPosition=function(e,t,r){var i,s,n=this.config,a=this.fragPrevious,o=r.fragments,l=r.endSN,h=r.fragmentHint,u=n.maxFragLookUpTolerance,d=r.partList,c=!!(this.loadingParts&&null!=d&&d.length&&h);if(c&&h&&!this.bitrateTest&&d[d.length-1].fragment.sn===h.sn&&(o=o.concat(h),l=h.sn),i=e<t?st(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=i.sn-r.startSN,g=this.fragmentTracker.getState(i);if((g===ji||g===qi&&i.gap)&&(a=i),a&&i.sn===a.sn&&(!c||d[0].fragment.sn>i.sn||!r.live&&!c)&&a&&i.level===a.level){var p=o[f+1];i=i.sn<l&&this.fragmentTracker.getState(p)!==ji?p:null}}return i},r.alignPlaylists=function(e,t,r){var i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;var s=e.fragmentStart,n=!t,a=e.alignedSliding&&_(s);if(n||!a&&!s){!function(e,t){e&&(function(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var r=Math.min(t.endCC,e.endCC),i=ss(t.fragments,r),s=ss(e.fragments,r);i&&s&&(j.log("Aligning playlist at start of dicontinuity sequence "+r),as(i.start-s.start,e))}}(t,e),!t.alignedSliding&&e&&function(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var r,i,s=e.fragments,n=t.fragments;if(s.length&&n.length){var a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=ss(n,a),i=ss(s,a)),r&&i||(i=ss(s,(r=n[Math.floor(n.length/2)]).cc)||s[Math.floor(s.length/2)]);var o=r.programDateTime,l=i.programDateTime;o&&l&&as((l-o)/1e3-(i.start-r.start),e)}}}(t,e),t.alignedSliding||!e||t.skippedSegments||Zt(e,t,!1))}(r,e);var o=e.fragmentStart;return this.log("Live playlist sliding: "+o.toFixed(2)+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" fragments: "+i),o}return s},r.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},r.setStartPosition=function(e,t){var r=this.startPosition;r<t&&(r=-1);var i=this.timelineOffset;if(-1===r){var s=null!==this.startTimeOffset,n=s?this.startTimeOffset:e.startTimeOffset;null!==n&&_(n)?(r=t+n,n<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to "+r+" for start time offset "+n+" found in "+(s?"multivariant":"media")+" playlist"),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge "+r),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+i}this.nextLoadPosition=r+i},r.getLoadPosition=function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r},r.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&re(e)&&e.stats.aborted&&(this.warn("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},r.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===os.FRAG_LOADING_WAITING_RETRY)||(this.state=os.IDLE)},r.onFragmentOrKeyLoadError=function(e,t){if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var i=t.frag;if(i&&i.type===e&&this.levels)if(this.fragContextChanged(i)){var s;this.warn("Frag load error must match current frag to retry "+i.url+" > "+(null==(s=this.fragCurrent)?void 0:s.url))}else{var n=t.details===A.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);var a=t.errorAction,o=a||{},l=o.action,h=o.flags,u=o.retryCount,d=void 0===u?0:u,c=o.retryConfig,f=!!a&&!!c,g=f&&5===l,p=f&&!a.resolved&&1===h;if(!g&&p&&re(i)&&!i.endList)this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((g||p)&&d<c.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);var m=ht(c,d);this.warn("Fragment "+i.sn+" of "+e+" "+i.level+" errored with "+t.details+", retrying loading "+(d+1)+"/"+c.maxNumRetry+" in "+m+"ms"),a.resolved=!0,this.retryDate=self.performance.now()+m,this.state=os.FRAG_LOADING_WAITING_RETRY}else if(c&&a){if(this.resetFragmentErrors(e),!(d<c.maxNumRetry))return void this.warn(t.details+" reached or exceeded max retry ("+d+")");n||3===l||(a.resolved=!0)}else this.state=2===l?os.WAITING_LEVEL:os.ERROR;this.tickImmediate()}},r.reduceLengthAndFlushBuffer=function(e){if(this.state===os.PARSING||this.state===os.PARSED){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var n=!s;return n&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+r+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1},r.resetFragmentErrors=function(e){e===M&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==os.STOPPED&&(this.state=os.IDLE)},r.afterBufferFlushed=function(e,t,r){if(e){var i=pt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===os.ENDED&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==os.STOPPED&&(this.state=os.IDLE)},r.resetStartWhenNotLoaded=function(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var 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}},r.resetWhenMissingContext=function(e){this.warn("The loading context changed while buffering fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},r.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(e,t,r,i){var s=this,n=r.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=i?0:Xt(n,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return s.hls.trigger(P.LEVEL_PTS_UPDATED,{details:n,level:r,drift:h,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===r.fragmentError&&this.treatAsGap(e,r),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(P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=os.PARSED,this.log("Parsed "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+")"),this.hls.trigger(P.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")},r.playlistLabel=function(){return this.playlistType===k?"level":"track"},r.fragInfo=function(e,t,r){var i,s;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(r?"part":"frag")+":["+(null!=(i=t&&!r?e.startPTS:(r||e).start)?i:NaN).toFixed(3)+"-"+(null!=(s=t&&!r?e.endPTS:(r||e).end)?s:NaN).toFixed(3)+"]"+(r&&"main"===e.type?"INDEPENDENT="+(r.independent?"YES":"NO"):"")},r.treatAsGap=function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)},r.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},r.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},i(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(){return this.hls.config,!1}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}(rs);function hs(e,t,r){us(e,t,r),e.addEventListener(t,r)}function us(e,t,r){e.removeEventListener(t,r)}var ds=function(e){function t(t,r){var i;return(i=e.call(this,"gap-controller",t.logger)||this).hls=null,i.fragmentTracker=null,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(P.MEDIA_ENDED,{stalled:!1}))},i.hls=t,i.fragmentTracker=r,i.registerListeners(),i}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this))},r.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},r.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;hs(r,"playing",this.onMediaPlaying),hs(r,"waiting",this.onMediaWaiting),hs(r,"ended",this.onMediaEnded)},r.onMediaDetaching=function(e,t){this.clearInterval();var r=this.media;r&&(us(r,"playing",this.onMediaPlaying),us(r,"waiting",this.onMediaWaiting),us(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},r.onBufferAppended=function(e,t){this.buffered=t.timeRanges},r.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}},r.poll=function(e,t){var r,i,s=null==(r=this.hls)?void 0:r.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(P.MEDIA_ENDED,{stalled:!1})));if(pt.getBuffered(n).length){var u=pt.bufferInfo(n,e,0),d=u.nextStart||0,c=this.fragmentTracker;if(a&&c&&this.hls){var f=cs(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 m=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(u.len>0||d))return;var v=Math.max(d,u.start||0)-e,y=null!=m&&m.live?2*m.targetduration:2,E=c.getPartialFragment(e);if(v>0&&(v<=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 R;if("ended"===(null==(R=this.mediaSource)?void 0:R.readyState)&&(null==m||!m.live)&&Math.abs(e-((null==m?void 0:m.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(P.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}var A=pt.bufferInfo(n,e,s.maxBufferHole);this._tryFixBufferStall(A,b,e)}else this.nudgeRetry=0}}}},r.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(r)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(P.STALL_RESOLVED,{})}},r.nudgeOnVideoHole=function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var s=pt.bufferedInfo(pt.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){var n=pt.timeRangesToArray(i),a=pt.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&a<n.length-1){var o=pt.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=this.fragmentTracker.getPartialFragment(e)||void 0,c=pt.bufferInfo(this.media,e,0);this.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:c.len,bufferInfo:c})}}}}},r._tryFixBufferStall=function(e,t,r){var i,s,n=this.fragmentTracker,a=this.media,o=null==(i=this.hls)?void 0:i.config;if(a&&n&&o){var l=null==(s=this.hls)?void 0:s.latestLevelDetails,h=n.getPartialFragment(r);if((h||null!=l&&l.live&&r<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;var u=e.buffered,d=this.adjacentTraversal(e,r);(u&&u.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}},r.adjacentTraversal=function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var s=r.getFragAtPos(t,k),n=r.getFragAtPos(i,k);if(s&&n)return n.sn-s.sn<2}return!1},r._reportStall=function(e){var t=this.hls,r=this.media,i=this.stallReported,s=this.stalled;if(!i&&null!==s&&r&&t){this.stallReported=!0;var n=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+Qe(e)+")");this.warn(n.message),t.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:s}})}},r._trySkipBufferHole=function(e){var t,r=this.fragmentTracker,i=this.media,s=null==(t=this.hls)?void 0:t.config;if(!i||!r||!s)return 0;var n=i.currentTime,a=pt.bufferInfo(i,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&&i.readyState<3,u=o-n;if(u>0&&(l||h)){if(u>s.maxBufferHole){var d=!1;if(0===n){var c=r.getAppendedFrag(0,k);c&&o<c.end&&(d=!0)}if(!d){var f=e||r.getAppendedFrag(n,k);if(f){var g;if(null==(g=this.hls.loadLevelObj)||!g.details)return 0;if(cs(this.hls.inFlightFragments,o))return 0;for(var p=!1,m=f.end;m<o;){var v=r.getPartialFragment(m);if(!v){p=!0;break}m+=v.duration}if(p)return 0}}}var y=Math.max(o+.05,n+.1);if(this.warn("skipping hole, adjusting currentTime from "+n+" to "+y),this.moved=!0,i.currentTime=y,null==e||!e.gap){var E=new Error("fragment loaded with buffer holes, seeking from "+n+" to "+y);this.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:E,reason:E.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return y}}return 0},r._tryNudgeBuffer=function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,s=null==t?void 0:t.config;if(!r||!s)return 0;var n=r.currentTime;if(this.nudgeRetry++,i<s.nudgeMaxRetry){var a=n+(i+1)*s.nudgeOffset,o=new Error("Nudging 'currentTime' from "+n+" to "+a);this.warn(o.message),r.currentTime=a,t.trigger(P.ERROR,{type:R.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(P.ERROR,{type:R.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}},i(t,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}(rs);function cs(e,t){var r=fs(e.main);if(r&&r.start<=t)return r;var i=fs(e.audio);return i&&i.start<=t?i:null}function fs(e){if(!e)return null;switch(e.state){case os.IDLE:case os.STOPPED:case os.ENDED:case os.ERROR:return null}return e.frag}function gs(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function ps(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ms(e,t,r,i,s){var n=new e(t,r,"");try{n.value=i,s&&(n.type=s)}catch(a){n=new e(t,r,Qe(s?u({type:s},i):i))}return n}var vs=function(){var e=ps();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),ys=function(){function e(e){var t=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=function(){t.hls&&t.hls.trigger(P.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.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)},t._unregisterListeners=function(){var e=this.hls;e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)},t.onMediaAttaching=function(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)},t.onMediaAttached=function(){var e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)},t.onMediaDetaching=function(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&function(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(var i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===r&&(e.mode=r)}(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 r=e[t];if("metadata"===r.kind&&"id3"===r.label)return gs(r,this.media),r}return this.media.addTextTrack("metadata","id3")}},t.onFragParsingMetadata=function(e,t){if(this.media){var r=this.hls.config,i=r.enableEmsgMetadataCues,s=r.enableID3MetadataCues;if(i||s){var n=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=ps();if(a)for(var o=0;o<n.length;o++){var l=n[o].type;if((l!==kr.emsg||i)&&s){var h=wr(n[o].data);if(h){var u=n[o].pts,d=u+n[o].duration;d>vs&&(d=vs),d-u<=0&&(d=u+.25);for(var c=0;c<h.length;c++){var f=h[c];if(!Ir(f)){this.updateId3CueEnds(u,l);var g=ms(a,u,d,f,l);g&&this.id3Track.addCue(g)}}}}}}}},t.updateId3CueEnds=function(e,t){var r,i=null==(r=this.id3Track)?void 0:r.cues;if(i)for(var s=i.length;s--;){var n=i[s];n.type===t&&n.startTime<e&&n.endTime===vs&&(n.endTime=e)}},t.onBufferFlushing=function(e,t){var r=t.startOffset,i=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)&&function(e,t,r,i){var s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var n=function(e,t,r){var i=[],s=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;for(var i,s=0,n=r;s<=n;)if(t<e[i=Math.floor((n+s)/2)].startTime)n=i-1;else{if(!(t>e[i].startTime&&s<r))return i;s=i+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<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),a=0;a<n.length;a++)i&&!i(n[a])||e.removeCue(n[a]);"disabled"===s&&(e.mode=s)}(n,r,i,"audio"===s?function(e){return e.type===kr.audioId3&&h}:"video"===s?function(e){return e.type===kr.emsg&&l}:function(e){return e.type===kr.audioId3&&h||e.type===kr.emsg&&l})}},t.onLevelUpdated=function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)},t.onLevelPtsUpdated=function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var r=this;if(this.media&&e.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var i,s=this.id3Track,n=e.dateRanges,a=Object.keys(n),o=this.dateRangeCuesAppended;if(s&&t)if(null!=(i=s.cues)&&i.length)for(var l=Object.keys(o).filter((function(e){return!a.includes(e)})),h=function(){var e=l[u],t=o[e].cues;delete o[e],Object.keys(t).forEach((function(e){try{var i=t[e];i.removeEventListener("enter",r.onEventCueEnter),s.removeCue(i)}catch(e){}}))},u=l.length;u--;)h();else o=this.dateRangeCuesAppended={};var d=e.fragments[e.fragments.length-1];if(0!==a.length&&_(null==d?void 0:d.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var c=ps(),f=function(){var e=a[g],t=n[e],i=t.startTime,s=o[e],l=(null==s?void 0:s.cues)||{},h=(null==s?void 0:s.durationKnown)||!1,u=vs,d=t.duration;if(t.endDate&&null!==d)u=i+d,h=!0;else if(t.endOnNext&&!h){var f=a.reduce((function(e,r){if(r!==t.id){var i=n[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e}),null);f&&(u=f.startTime,h=!0)}for(var p,m,v=Object.keys(t.attr),y=0;y<v.length;y++){var E=v[y];if("ID"!==(m=E)&&"CLASS"!==m&&"CUE"!==m&&"START-DATE"!==m&&"DURATION"!==m&&"END-DATE"!==m&&"END-ON-NEXT"!==m){var S=l[E];if(S)h&&!s.durationKnown?S.endTime=u:Math.abs(S.startTime-i)>.01&&(S.startTime=i,S.endTime=u);else if(c){var T=t.attr[E];At(E)&&(p=T,T=Uint8Array.from(p.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);var _=ms(c,i,u,{key:E,data:T},kr.dateRange);_&&(_.id=e,r.id3Track.addCue(_),l[E]=_)}}}o[e]={cues:l,dateRange:t,durationKnown:h}},g=0;g<a.length;g++)f()}}},e}(),Es=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,r=t.levelDetails;if(e&&r){t.currentTime=e.currentTime;var i=t.computeLatency();if(null!==i){t._latency=i;var s=t.config,n=s.lowLatencyMode,a=s.maxLiveSyncPlaybackRate;if(n&&1!==a&&r.live){var o=t.targetLatency;if(null!==o){var l=i-o;if(l<Math.min(t.maxLatency,o+r.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(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.ERROR,this.onError,this))},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.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 r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onError=function(e,t){var r;t.details===A.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(i=this.targetLatency)?void 0:i.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},i(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,r=e.partHoldBack,i=e.targetduration,s=this.config,n=s.liveSyncDuration,a=s.liveSyncDurationCount,o=s.lowLatencyMode,l=this.hls.userConfig,h=o&&r||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*i);var u=i;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 r=this.levelDetails;if(null===r)return null;var i=r.edge,s=e-t-this.edgeStalled,n=i-r.totalduration,a=i-(this.config.lowLatencyMode&&r.partTarget||r.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 r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}])}(),Ss=function(e){function t(t,r){var i;return(i=e.call(this,r,t.logger)||this).hls=void 0,i.canLoad=!1,i.timer=-1,i.hls=t,i}o(t,e);var r=t.prototype;return r.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},r.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},r.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},r.stopLoad=function(){this.canLoad=!1,this.clearTimer()},r.switchParams=function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var s=-1,n=0;n<i.length;n++){var a=i[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=i[s],h=parseInt(l["LAST-MSN"])||(null==t?void 0:t.lastPartSn),u=parseInt(l["LAST-PART"])||(null==t?void 0: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=r&&ze(r);return new Ke(h,u>=0?u:void 0,c)}}},r.loadPlaylist=function(e){this.clearTimer()},r.loadingPlaylist=function(e,t){this.clearTimer()},r.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},r.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},r.playlistLoaded=function(e,t,r){var i=t.details,s=t.stats,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;i.advancedDateTime=Date.now()-a;var o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){var l=Math.max(o||0,0);i.appliedTimelineOffset=l,i.fragments.forEach((function(e){e.start=e.playlistOffset+l}))}if(i.live||null!=r&&r.live){var h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(r),r&&i.fragments.length>0){Qt(r,i);var u=i.playlistParsingError;if(u){this.warn(u);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var c,f=t.networkDetails;return void d.trigger(P.ERROR,{type:R.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:u,reason:u.message,level:t.level||void 0,parent:null==(c=i.fragments[0])?void 0:c.type,networkDetails:f,stats:s})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=s.loading.start);var g,p=this.hls.mainForwardBufferInfo,m=p?p.end-p.len:0,v=er(i,1e3*(i.edge-m));if(i.requestScheduled+v<n?i.requestScheduled=n:i.requestScheduled+=v,this.log("live playlist "+e+" "+(i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED")),!this.canLoad||!i.live)return;var y=void 0,E=void 0;if(i.canBlockReload&&i.endSN&&i.advanced){var S=this.hls.config.lowLatencyMode,T=i.lastPartSn,_=i.endSN,L=i.lastPartIndex,b=T===_;-1!==L?b?(y=_+1,E=S?0:L):(y=T,E=S?L+1:i.maxPartIndex):y=_+1;var w=i.age,I=w+i.ageHeader,D=Math.min(I-i.partTarget,1.5*i.targetduration);if(D>0){if(I>3*i.targetduration)this.log("Playlist last advanced "+w.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=r&&r.tuneInGoal&&I-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+D+" with playlist age: "+i.age),D=0;else{var C=Math.floor(D/i.targetduration);y+=C,void 0!==E&&(E+=Math.round(D%i.targetduration/i.partTarget)),this.log("CDN Tune-in age: "+i.ageHeader+"s last advanced "+w.toFixed(2)+"s goal: "+D+" skip sn "+C+" to part "+E)}i.tuneInGoal=D}if(g=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),S||!b)return i.requestScheduled=n,void this.loadingPlaylist(h,g)}else(i.canBlockReload||i.canSkipUntil)&&(g=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));g&&void 0!==y&&i.canBlockReload&&(i.requestScheduled=s.loading.first+Math.max(v-2*a,v/2)),this.scheduleLoading(h,g,i)}else this.clearTimer()},r.scheduleLoading=function(e,t,r){var i=this,s=r||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 i.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},r.getDeliveryDirectives=function(e,t,r,i){var s=ze(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,s=""),new Ke(r,i,s)},r.checkRetry=function(e){var t=this,r=e.details,i=ot(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(i&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var c=ht(h,l);this.clearTimer(),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+r+'" in '+c+"ms")}e.levelRetry=!0,s.resolved=!0}return u},t}(F),Ts=function(e){function t(t,r){var i;return(i=e.call(this,t,"level-controller")||this)._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}o(t,e);var r=t.prototype;return r._registerListeners=function(){var e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.ERROR,this.onError,this)},r._unregisterListeners=function(){var e=this.hls;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},r.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},r.onManifestLoading=function(e,t){this.resetLevels()},r.onManifestLoaded=function(e,t){var r=this,i=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=Ge(u,i)||void 0),d&&(d=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var i=t[r].split(".");i.length>2&&"avc1"===i[0]&&(t[r]="avc1."+parseInt(i[1]).toString(16)+("000"+parseInt(i[2]).toString(16)).slice(-4))}return t.join(",")}(d));var c=e.width,f=e.height,g=e.unknownCodecs,p=g?g.length:0;if(g)for(var m=p;m--;){var v=g[m];r.isAudioSupported(v)?(e.audioCodec=u=u?u+","+v:v,p--,Ce.audio[u.substring(0,4)]=2):r.isVideoSupported(v)&&(e.videoCodec=d=d?d+","+v:v,p--,Ce.video[d.substring(0,4)]=2)}if(o||(o=!(!c||!f)),l||(l=!!d),h||(h=!!u),p||u&&!r.isAudioSupported(u)||d&&!r.isVideoSupported(d))r.log('Some or all CODECS not supported "'+t.CODECS+'"');else{var y=t.CODECS,E=t["FRAME-RATE"],S=t["HDCP-LEVEL"],T=t["PATHWAY-ID"],_=t.RESOLUTION,L=t["VIDEO-RANGE"],b=(T||".")+"-"+e.bitrate+"-"+_+"-"+E+"-"+y+"-"+L+"-"+S;if(n[b])if(n[b].uri===e.url||e.attrs["PATHWAY-ID"])n[b].addGroupId("audio",t.AUDIO),n[b].addGroupId("text",t.SUBTITLES);else{var R=a[b]+=1;e.attrs["PATHWAY-ID"]=new Array(R+1).join(".");var A=r.createLevel(e);n[b]=A,s.push(A)}else{var P=r.createLevel(e);n[b]=P,a[b]=1,s.push(P)}}})),this.filterAndSortMediaOptions(s,t,o,l,h)},r.createLevel=function(e){var t=new Ye(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'+r.videoCodec+'"');this.log(i.message),t.supportedResult=z.getUnsupportedResult(i,[])}return t},r.isAudioSupported=function(e){return Me(e,"audio",this.hls.config.preferManagedMediaSource)},r.isVideoSupported=function(e){return Me(e,"video",this.hls.config.preferManagedMediaSource)},r.filterAndSortMediaOptions=function(e,t,r,i,s){var n=this,a=[],o=[],l=e;if((r||i)&&s&&(l=l.filter((function(e){var t,r=e.videoCodec,i=e.videoRange,s=e.width,n=e.height;return(!!r||!(!s||!n))&&!!(t=i)&&je.indexOf(t)>-1}))),0!==l.length){t.audioTracks&&_s(a=t.audioTracks.filter((function(e){return!e.audioCodec||n.isAudioSupported(e.audioCodec)}))),t.subtitles&&_s(o=t.subtitles);var h=l.slice(0);l.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(r&&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 je.indexOf(e.videoRange)-je.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=Ne(e.videoCodec),s=Ne(t.videoCodec);if(i!==s)return s-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var n=Fe(e.codecSet),a=Fe(t.codecSet);if(n!==a)return a-n}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var u=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==h.length)for(var d=0;d<h.length;d++)if(h[d].pathwayId===l[0].pathwayId){u=h[d];break}this._levels=l;for(var c=0;c<l.length;c++)if(l[c]===u){var f;this._firstLevel=c;var g=u.bitrate,p=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+l.length+" level(s) found, first bitrate: "+g),void 0===(null==(f=this.hls.userConfig)?void 0:f.abrEwmaDefaultEstimate)){var m=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);m>p&&p===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=m)}break}var v=s&&!i,y=this.hls.config,E=!(!y.audioStreamController||!y.audioTrackController),S={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:i,altAudio:E&&!v&&a.some((function(e){return!!e.url}))};this.hls.trigger(P.MANIFEST_PARSED,S)}else Promise.resolve().then((function(){if(n.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: "+Qe(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,r){return r.indexOf(e)===t}))),n.warn(r),e+=" ("+r+")");var i=new Error(e);n.hls.trigger(P.ERROR,{type:R.MEDIA_ERROR,details:A.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}}))},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===I&&t.context.level===this.level&&this.checkRetry(t)},r.onFragBuffered=function(e,t){var r=t.frag;if(void 0!==r&&r.type===k){var i=r.elementaryStreams;if(!Object.keys(i).some((function(e){return!!i[e]})))return;var s=this._levels[r.level];null!=s&&s.loadError&&(this.log("Resetting level error count of "+s.loadError+" on frag buffered"),s.loadError=0)}},r.onLevelLoaded=function(e,t){var r,i,s=t.level,n=t.details,a=t.levelInfo;if(!a)return this.warn("Invalid level index "+s),void(null!=(i=t.deliveryDirectives)&&i.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!=(r=t.deliveryDirectives)&&r.skip&&(n.deltaUpdateFailed=!0)},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=this.getUrlWithDirectives(t.uri,r),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==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(n?" Pathway "+n:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+i),this.hls.trigger(P.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})},r.removeLevel=function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter((function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));sr(i),this._levels=i,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=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(P.LEVELS_UPDATED,{levels:i})}},r.onLevelsUpdated=function(e,t){var r=t.levels;this._levels=r},r.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(P.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))},i(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 r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(P.ERROR,{type:R.OTHER_ERROR,details:A.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)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(P.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(),r=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=r}}},{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)}}])}(Ss);function _s(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var Ls=[];function bs(e,t,r){if(!((i=t.remuxResult).audio||i.video||i.text||i.id3||i.initSegment))return!1;var i,s=[],n=t.remuxResult,a=n.audio,o=n.video;return a&&Rs(s,a),o&&Rs(s,o),e.postMessage({event:"transmuxComplete",data:t,instanceNo:r},s),!0}function Rs(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function As(e,t,r,i){t.reduce((function(t,r){return bs(e,r,i)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0],instanceNo:i}),e.postMessage({event:"flush",data:r,instanceNo:i})}function Ps(e,t,r){self.postMessage({event:e,data:t,instanceNo:r})}void 0!==r&&r&&self.addEventListener("message",(function(e){var t=e.data,r=t.instanceNo;if(void 0!==r){var i=Ls[r];if("reset"===t.cmd&&(delete Ls[t.resetNo],i&&i.destroy(),t.cmd="init"),"init"===t.cmd){var s=JSON.parse(t.config),n=new E;n.on(P.FRAG_DECRYPTED,Ps),n.on(P.ERROR,Ps);var a=W(s.debug,t.id);return function(e,t){var r=function(r){e[r]=function(e){Ps("workerLog",{logType:r,message:e},t)}};for(var i in e)r(i)}(a,r),Ls[r]=new Ii(n,t.typeSupported,s,"",t.id,a),void Ps("init",null,r)}if(i)switch(t.cmd){case"configure":i.configure(t.config);break;case"demux":var o=i.push(t.data,t.decryptdata,t.chunkMeta,t.state);Ci(o)?o.then((function(e){bs(self,e,r)})).catch((function(e){Ps(P.ERROR,{instanceNo:r,type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker push error"},r)})):bs(self,o,r);break;case"flush":var l=t.chunkMeta,h=i.flush(l);Ci(h)?h.then((function(e){As(self,e,l,r)})).catch((function(e){Ps(P.ERROR,{type:R.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker flush error"},r)})):As(self,h,l,r)}}}));var ws="1.6.5",Is={},Ds=0,Cs=function(){function e(e,r,i,s){var n=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ds++,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,r=n.hls;if(r&&null!=t&&t.event&&t.instanceNo===n.instanceNo)switch(t.event){case"init":var i,s=null==(i=n.workerContext)?void 0:i.objectURL;s&&self.URL.revokeObjectURL(s);break;case"transmuxComplete":n.handleTransmuxComplete(t.data);break;case"flush":n.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.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,r.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(P.ERROR,{type:R.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var a=e.config;this.hls=e,this.id=r,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;var o=function(e,t){(t=t||{}).frag=n.frag||void 0,e===P.ERROR&&(t.parent=n.id,t.part=n.part,n.error=t.error),n.hls.trigger(e,t)};this.observer=new E,this.observer.on(P.FRAG_DECRYPTED,o),this.observer.on(P.ERROR,o);var l=We(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 "'+r+'"'),this.workerContext=function(e){var t=Is[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Is[e]=i,i}(a.workerPath)):(h.log('injecting Web Worker for "'+r+'"'),this.workerContext=function(){var e=Is[ws];if(e)return e.clientCount++,e;var r=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+t.toString()+")(true);"],{type:"text/javascript"}),i=self.URL.createObjectURL(r),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return Is[ws]=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:r,config:Qe(a)})}catch(t){h.warn('Error setting up "'+r+'" Web Worker, fallback to inline',t),this.terminateWorker(),this.error=null,this.transmuxer=new Ii(this.observer,l,a,"",r,e.logger)}}else this.transmuxer=new Ii(this.observer,l,a,"",r,e.logger)}var r=e.prototype;return r.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=Ds++;var t=this.hls.config,r=We(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Qe(t)})}},r.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=Is[e||ws];if(t&&1==t.clientCount--){var r=t.worker,i=t.objectURL;delete Is[e||ws],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}},r.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},r.push=function(e,t,r,i,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,m=s.decryptdata,v=this.frag,y=!(v&&s.cc===v.cc),E=!(v&&l.level===v.level),S=v?l.sn-v.sn:-1,T=this.part?l.part-this.part.index:-1,_=0===S&&l.id>1&&l.id===(null==v?void 0:v.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 R=!(v&&(null==(u=s.initSegment)?void 0:u.url)===(null==(d=v.initSegment)?void 0:d.url)),A=new Mi(y,L,o,E,p,R);if(!L||y||R){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+s.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===k?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+p+"\n initSegmentChange: "+R);var P=new ki(r,i,t,a,h);this.configureTransmuxer(P)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:A},e instanceof ArrayBuffer?[e]:[]);else if(g){var w=g.push(e,m,l,A);Ci(w)?w.then((function(e){c.handleTransmuxComplete(e)})).catch((function(e){c.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(w)}},r.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var s=i.flush(e);Ci(s)?s.then((function(r){t.handleFlushResult(r,e)})).catch((function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}},r.transmuxerError=function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(P.ERROR,{type:R.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:r}))},r.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},r.configureTransmuxer=function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)},r.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}();function ks(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ms(){if(!Ie())return!1;var e=ks();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var xs=function(e){function t(t,r,i){var s;return(s=e.call(this,t,r,i,"stream-controller",k)||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)&&(s.log("Media seeked to "+t.toFixed(3)),s.getBufferedFrag(t))){var r=s.getFwdBufferInfoAtPos(e,t,k,0);null!==r&&0!==r.len?s.tick():s.warn("Main forward buffer length at "+t+' on "seeked" event '+(r?r.len:"empty")+")")}},s.registerListeners(),s}o(t,e);var r=t.prototype;return r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(P.MANIFEST_PARSED,this.onManifestParsed,this),t.on(P.LEVEL_LOADING,this.onLevelLoading,this),t.on(P.LEVEL_LOADED,this.onLevelLoaded,this),t.on(P.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(P.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(P.BUFFER_CREATED,this.onBufferCreated,this),t.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(P.FRAG_BUFFERED,this.onFragBuffered,this)},r.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(P.MANIFEST_PARSED,this.onManifestParsed,this),t.off(P.LEVEL_LOADED,this.onLevelLoaded,this),t.off(P.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(P.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(P.BUFFER_CREATED,this.onBufferCreated,this),t.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(P.FRAG_BUFFERED,this.onFragBuffered,this)},r.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},r.startLoad=function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var s=i.startLevel;-1===s&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @"+r.toFixed(3)),e=r),this.state=os.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=os.STOPPED},r.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case os.WAITING_LEVEL:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=os.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=os.IDLE;break}break;case os.FRAG_LOADING_WAITING_RETRY:var s,n=self.performance.now(),a=this.retryDate;if(!a||n>=a||null!=(s=this.media)&&s.seeking){var o=this.levels,l=this.level,h=null==o?void 0:o[l];this.resetStartWhenNotLoaded(h||null),this.state=os.IDLE}}this.state===os.IDLE&&this.doTickIdle(),this.onTickEnd()},r.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()},r.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var s=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[s]){var n=r[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(P.BUFFER_EOS,l),void(this.state=os.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===os.WAITING_LEVEL||this.waitForLive(n))return this.level=s,this.state=os.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&&re(f)&&this.fragmentTracker.getState(f)!==ji){var g,p=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,m=h.fragments[p-1];m&&f.cc===m.cc&&(f=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var v=this.audioOnly&&!this.altAudio?J:Z,y=(v===Z?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,v,k)}f=this.getNextFragmentLoopLoading(f,h,a,k,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,c))}}}}}},r.loadFragment=function(t,r,i){var s=this.fragmentTracker.getState(t);s===Wi||s===qi?re(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,r)):e.prototype.loadFragment.call(this,t,r,i):this._loadInitSegment(t,r):this.clearTrackerIfNeeded(t)},r.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,k)},r.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},r.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},r.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.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;r=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(t.currentTime+r);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)}}}},r.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case os.KEY_LOADING:case os.FRAG_LOADING:case os.FRAG_LOADING_WAITING_RETRY:case os.PARSING:case os.PARSED:this.state=os.IDLE}this.nextLoadPosition=this.getLoadPosition()},r.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,2===this.altAudio?"video":null)},r.onMediaAttached=function(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;hs(i,"playing",this.onMediaPlaying),hs(i,"seeked",this.onMediaSeeked)},r.onMediaDetaching=function(t,r){var i=this.media;i&&(us(i,"playing",this.onMediaPlaying),us(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,e.prototype.onMediaDetaching.call(this,t,r),r.transferMedia||(this._hasEnoughToStart=!1)},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(P.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},r.onManifestParsed=function(e,t){var r,i,s=!1,n=!1;t.levels.forEach((function(e){var t=e.audioCodec;t&&(s=s||-1!==t.indexOf("mp4a.40.2"),n=n||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&n&&!("function"==typeof(null==(i=ks())||null==(r=i.prototype)?void 0:r.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},r.onLevelLoading=function(e,t){if(this.levels&&this.state===os.IDLE){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=os.WAITING_LEVEL)}},r.onLevelLoaded=function(e,t){var r,i=this.levels,s=this.startFragRequested,n=t.level,a=t.details,o=a.totalduration;if(i){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!==os.FRAG_LOADING&&this.state!==os.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();var u=0;if(a.live||null!=(r=l.details)&&r.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(P.LEVEL_UPDATED,{details:a,level:n}),this.state===os.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=os.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}else this.warn("Levels were reset while loading level "+n)},r.synchronizeToLiveEdge=function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==i&&r.duration>i&&(s<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||s<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn("Playback: "+s.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+i.toFixed(3)),"buffered"===this.config.liveSyncMode){var h,u=pt.bufferInfo(r,i,0);if(null==u||null==(h=u.buffered)||!h.length)return void(r.currentTime=i);if(u.start<=s)return void(r.currentTime=i);var d=pt.bufferedInfo(u.buffered,s,0).nextStart;d&&(r.currentTime=d)}else r.currentTime=i}}},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,s=e.payload,n=this.levels;if(n){var a=n[r.level];if(a){var o=a.details;if(!o)return this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset"),void this.fragmentTracker.removeFragment(r);var l=a.videoCodec,h=o.PTSKnown||!o.live,u=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Cs(this.hls,k,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,p=new is(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,g),m=this.initPTS[r.cc];c.push(s,u,d,l,r,i,o.totalduration,h,p,m)}else this.warn("Level "+r.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r.onAudioTrackSwitching=function(e,t){var r=this,i=this.hls,s=2===this.altAudio;if(et(t.url,i))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(),i.once(P.BUFFER_FLUSHED,(function(){var e;null==(e=r.hls)||e.trigger(P.AUDIO_TRACK_SWITCHED,t)})),void i.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(P.AUDIO_TRACK_SWITCHED,t)}},r.onAudioTrackSwitched=function(e,t){var r=et(t.url,this.hls);if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?2:0,this.tick()},r.onBufferCreated=function(e,t){var r,i,s=t.tracks,n=!1;for(var a in s){var o=s[a];if("main"===o.id){if(i=a,r=o,"video"===a){var l=s[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part,s=r.type===k;if(s){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===os.PARSED&&(this.state=os.IDLE));var n=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),re(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}var a=this.media;a&&(!this._hasEnoughToStart&&pt.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())},r.onError=function(e,t){var r;if(t.fatal)this.state=os.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(k,t);break;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==os.WAITING_LEVEL||(null==(r=t.context)?void 0:r.type)!==I||(this.state=os.IDLE);break;case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.resetLoadingState();break;case A.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},r.onFragLoadEmergencyAborted=function(){this.state=os.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==J||!this.altAudio){var i=(r===Z?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r,k),this.tick())}},r.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},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to "+r+", already seeking at "+t);var i=this.timelineOffset;i&&r&&(r+=i);var s=this.getLevelDetails(),n=pt.getBuffered(e),a=n.length?n.start(0):0,o=a-r,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"),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position "+r+" from current time "+t+" buffer start "+a),e.currentTime=r)}}},r._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},r._loadBitrateTestFrag=function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then((function(e){var i=r.hls,s=null==e?void 0:e.frag;if(s&&!r.fragContextChanged(s)){t.fragmentError=0,r.state=os.IDLE,r.startFragRequested=!1,r.bitrateTest=!1;var n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(P.FRAG_LOADED,e),s.bitrateTest=!1}}))},r._handleTransmuxComplete=function(e){var t,r=this.playlistType,i=this.hls,s=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var o=a.frag,l=a.part,h=a.level,u=s.video,d=s.text,c=s.id3,f=s.initSegment,g=h.details,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=os.PARSING,f){if(null!=f&&f.tracks){var m=o.initSegment||o;this._bufferInitSegment(h,f.tracks,m,n),i.trigger(P.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:r,tracks:f.tracks})}var v=f.initPTS,y=f.timescale;_(v)&&(this.initPTS[o.cc]={baseTime:v,timescale:y},i.trigger(P.INIT_PTS_FOUND,{frag:o,id:r,initPTS:v,timescale:y}))}if(u&&g){p&&"audiovideo"===u.type&&this.logMuxedErr(o);var E=g.fragments[o.sn-1-g.startSN],S=o.sn===g.startSN,T=!E||o.cc>E.cc;if(!1!==s.independent){var L=u.startPTS,b=u.endPTS,R=u.startDTS,A=u.endDTS;if(l)l.elementaryStreams[u.type]={startPTS:L,endPTS:b,startDTS:R,endDTS:A};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!T&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),I=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:L;if(!S&&I<D-this.config.maxBufferHole&&!T)return void this.backtrack(o);T&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,b,o.start,A,!0)}else S&&L-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,L,b,R,A),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,S||T)}else{if(!S&&!T)return void this.backtrack(o);o.gap=!0}}if(p){var C=p.startPTS,k=p.endPTS,M=p.startDTS,x=p.endDTS;l&&(l.elementaryStreams[J]={startPTS:C,endPTS:k,startDTS:M,endDTS:x}),o.setElementaryStreamInfo(J,C,k,M,x),this.bufferFragmentData(p,o,l,n)}if(g&&null!=c&&null!=(t=c.samples)&&t.length){var O={id:r,frag:o,details:g,samples:c.samples};i.trigger(P.FRAG_PARSING_METADATA,O)}if(g&&d){var N={id:r,frag:o,details:g,samples:d.samples};i.trigger(P.FRAG_PARSING_USERDATA,N)}}}else this.resetWhenMissingContext(n)},r.logMuxedErr=function(e){this.warn((re(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},r._bufferInitSegment=function(e,t,r,i){var s=this;if(this.state===os.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var n=t.audio,a=t.video,o=t.audiovideo;if(n){var l=He(n.codec,e.audioCodec);"mp4a"===l&&(l="mp4a.40.5");var h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var u=n.metadata;u&&"channelCount"in u&&1!==(u.channelCount||1)&&-1===h.indexOf("firefox")&&(l="mp4a.40.5")}l&&-1!==l.indexOf("mp4a.40.5")&&-1!==h.indexOf("android")&&"audio/mpeg"!==n.container&&(l="mp4a.40.2",this.log("Android: force audio codec to "+l)),e.audioCodec&&e.audioCodec!==l&&this.log('Swapping manifest audio codec "'+e.audioCodec+'" for "'+l+'"'),n.levelCodec=l,n.id=k,this.log("Init audio buffer, container:"+n.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(e.audioCodec||"")+"/"+n.codec+"]"),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=k;var d=a.codec;if(4===(null==d?void 0:d.length))switch(d){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||"")+"/"+d+"]"+(a.codec!==d?" 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 c=Object.keys(t);if(c.length){if(this.hls.trigger(P.BUFFER_CODECS,t),!this.hls)return;c.forEach((function(e){var n=t[e].initSegment;null!=n&&n.byteLength&&s.hls.trigger(P.BUFFER_APPENDING,{type:e,data:n,frag:r,part:null,chunkMeta:i,parent:r.type})}))}this.tickImmediate()}},r.getMainFwdBufferInfo=function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,k)},r.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=os.IDLE},r.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(pt.isBuffered(e,r)?t=this.getAppendedFrag(r):pt.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,s=t.level;i&&t.sn===i.sn&&i.level===s||(this.fragPlaying=t,this.hls.trigger(P.FRAG_CHANGED,{frag:t}),i&&i.level===s||this.hls.trigger(P.LEVEL_SWITCHED,{level:s}))}}},i(t,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.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)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(_(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?st(null,r.fragments,t):null);if(i){var s=i.programDateTime;if(null!==s){var n=s+1e3*(t-i.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}}])}(ls),Os=function(){function e(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}var t=e.prototype;return t.abort=function(e){for(var t in this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}},t.detach=function(){for(var e in this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}},t.destroy=function(){for(var e in this.detach(),this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}},t.createKeyLoadError=function(e,t,r,i,s){return void 0===t&&(t=A.KEY_LOAD_ERROR),new ts({type:R.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:i})},t.loadClear=function(e,t){var r=this;if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length)if(t.length){for(var i,s=e.sn,n=e.cc,a=function(){var e=t[o];if(n<=e.cc&&("initSegment"===s||"initSegment"===e.sn||s<e.sn))return{v:r.emeController.selectKeySystemFormat(e).then((function(t){if(e.setKeyFormat(t),r.emeController&&r.config.requireKeySystemAccessOnStart){var i=z.keySystemFormatToKeySystemDomain(t);if(i)return r.emeController.getKeySystemAccess([i])}}))}},o=0;o<t.length;o++)if(i=a())return i.v}else if(this.config.requireKeySystemAccessOnStart){var l=z.getKeySystemsForConfig(this.config);if(l.length)return this.emeController.getKeySystemAccess(l)}return null},t.load=function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(r){return t.loadInternal(e,r)})):this.loadInternal(e)},t.loadInternal=function(e,t){var r,i;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");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,l=this.keyUriToKeyInfo[a];if(null!=(r=l)&&r.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(null!=(i=l)&&i.keyLoadPromise)switch(null==(o=l.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return l.keyLoadPromise.then((function(t){return s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:l}}))}switch(l=this.keyUriToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":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+'"')))}},t.loadKeyEME=function(e,t){var r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i=this.emeController.loadKey(r);if(i)return(e.keyLoadPromise=i.then((function(t){return e.mediaKeySessionContext=t,r}))).catch((function(t){throw e.keyLoadPromise=null,t}))}return Promise.resolve(r)},t.loadKeyHTTP=function(e,t){var r=this,i=this.config,s=new(0,i.loader)(i);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=i.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,t,i,s){var o=i.frag,l=i.keyInfo,h=i.url;if(!o.decryptdata||l!==r.keyUriToKeyInfo[h])return a(r.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,i,s,n){r.resetLoader(i),a(r.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,i,s){r.resetLoader(i),a(r.createKeyLoadError(t,A.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:function(e,i,s){r.resetLoader(i),a(r.createKeyLoadError(t,A.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(o,h,d)}))},t.resetLoader=function(e){var t=e.frag,r=e.keyInfo,i=e.url,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[i],s&&s.destroy()},e}();function Ns(e){switch(e.type){case D:return M;case C:return x;default:return k}}function Fs(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var Bs=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(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(P.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(P.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,s=new(r||i)(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 r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:w,url:r,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var r=t.id,i=t.level,s=t.pathwayId,n=t.url,a=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:s,responseType:"text",type:I,url:n,deliveryDirectives:a,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var r=t.id,i=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:D,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onSubtitleTrackLoading=function(e,t){var r=t.id,i=t.groupId,s=t.url,n=t.deliveryDirectives,a=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:C,url:s,deliveryDirectives:n,levelOrTrack:a})},t.onLevelsUpdated=function(e,t){var r=this.loaders[I];if(r){var i=r.context;i&&!t.levels.some((function(e){return e===i.levelOrTrack}))&&(r.abort(),delete this.loaders[I])}},t.load=function(e){var t,r,i,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(r=e.type===w?a.manifestLoadPolicy.default:n({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),o=this.createInternalLoader(e),_(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===I&&null!==e.level?i=this.hls.levels[e.level].details:e.type===D&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===C&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var u=i.partTarget,d=i.targetduration;if(u&&d){var c=1e3*Math.max(3*u,.8*d);r=n({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}var f=r.errorRetry||r.timeoutRetry||{},g={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},p={onSuccess:function(e,t,r,i){var n=s.getInternalLoader(r);s.resetInternalLoader(r.type);var a=e.data;0===a.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Ft.isMediaPlaylist(a)||r.type!==w?s.handleTrackOrLevelPlaylist(e,t,r,i||null,n):s.handleMasterPlaylist(e,t,r,i)):s.handleManifestParsingError(e,r,new Error("no EXTM3U delimiter"),i||null,t)},onError:function(e,t,r,i){s.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){s.handleNetworkError(t,r,!0,void 0,e)}};o.load(e,g,p)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,s=e.forceStartLoad;(r||s)&&(this.hls.logger.log((r?"auto":"force")+" startLoad with configured startPosition "+i),this.hls.startLoad(i))}},t.handleMasterPlaylist=function(e,t,r,i){var s=this.hls,n=e.data,a=Fs(e,r),o=Ft.parseMasterPlaylist(n,a);if(o.playlistParsingError)this.handleManifestParsingError(e,r,o.playlistParsingError,i,t);else{var l=o.contentSteering,h=o.levels,u=o.sessionData,d=o.sessionKeys,c=o.startTimeOffset,f=o.variableList;this.variableList=f;var g=Ft.parseMasterPlaylistMedia(n,a,o),p=g.AUDIO,m=void 0===p?[]:p,v=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];m.length&&(m.some((function(e){return!e.url}))||!h[0].audioCodec||h[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 Rt({}),bitrate:0,url:""}))),s.trigger(P.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:v,captions:y,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:c,variableList:f})}},t.handleTrackOrLevelPlaylist=function(e,t,r,i,s){var n=this.hls,a=r.id,o=r.level,l=r.type,h=Fs(e,r),u=_(o)?o:_(a)?a:0,d=Ns(r),c=Ft.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===w){var f={attrs:new Rt({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=t.loading.start+er(c,0),n.trigger(P.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=c,this.handlePlaylistLoaded(c,e,t,r,i,s)},t.handleManifestParsingError=function(e,t,r,i,s){this.hls.trigger(P.ERROR,{type:R.NETWORK_ERROR,details:A.MANIFEST_PARSING_ERROR,fatal:t.type===w,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:s})},t.handleNetworkError=function(e,t,r,i,s){void 0===r&&(r=!1);var n="A network "+(r?"timeout":"error"+(i?" (status "+i.code+")":""))+" occurred while loading "+e.type;e.type===I?n+=": "+e.level+" id: "+e.id:e.type!==D&&e.type!==C||(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 w:o=r?A.MANIFEST_LOAD_TIMEOUT:A.MANIFEST_LOAD_ERROR,l=!0;break;case I:o=r?A.LEVEL_LOAD_TIMEOUT:A.LEVEL_LOAD_ERROR,l=!1;break;case D:o=r?A.AUDIO_TRACK_LOAD_TIMEOUT:A.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case C:o=r?A.SUBTITLE_TRACK_LOAD_TIMEOUT:A.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);var d={type:R.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(i){var c=(null==t?void 0:t.url)||e.url;d.response=u({url:c,data:void 0},i)}this.hls.trigger(P.ERROR,d)},t.handlePlaylistLoaded=function(e,t,r,i,s,n){var a=this.hls,o=i.type,l=i.level,h=i.id,u=i.groupId,d=i.deliveryDirectives,c=Fs(t,i),f=Ns(i),g="number"==typeof i.level&&f===k?l:void 0;if(e.fragments.length){e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));var p=e.playlistParsingError;if(p){if(this.hls.logger.warn(p),!a.config.ignorePlaylistParsingErrors)return void a.trigger(P.ERROR,{type:R.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:p,reason:p.message,response:t,context:i,level:g,parent:f,networkDetails:s,stats:r});e.playlistParsingError=null}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case w:case I:a.trigger(P.LEVEL_LOADED,{details:e,levelInfo:i.levelOrTrack||a.levels[0],level:g||0,id:h||0,stats:r,networkDetails:s,deliveryDirectives:d,withoutMultiVariant:o===w});break;case D:a.trigger(P.AUDIO_TRACK_LOADED,{details:e,track:i.levelOrTrack,id:h||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:d});break;case C:a.trigger(P.SUBTITLE_TRACK_LOADED,{details:e,track:i.levelOrTrack,id:h||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:d})}}else{var m=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(P.ERROR,{type:R.NETWORK_ERROR,details:A.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:t,context:i,level:g,parent:f,networkDetails:s,stats:r})}},e}(),Us={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Gs={};var Hs=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 E,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 r=this.logger=W(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(e,t,r){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 i=$i(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(r){var s=e+"Loading"+r,l=t[s];if(void 0!==l&&a){o.push(s);var h=i[n].default;switch(t[n]={default:h},r){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&&r.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+n+'": '+Qe(t[n]))})),u(u({},i),t)}(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&function(e,t){var r=e.loader;r!==Oi&&r!==Ui?(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=Oi,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,r);var s=i.abrController,n=i.bufferController,a=i.capLevelController,o=i.errorController,l=i.fpsController,h=new o(this),d=this.abrController=new s(this),c=new zi(this),f=i.interstitialsController,g=f?this.interstitialsController=new f(this,e):null,p=this.bufferController=new n(this,c),m=this.capLevelController=new a(this),v=new l(this),y=new Bs(this),S=i.contentSteeringController,T=S?new S(this):null,_=this.levelController=new Ts(this,T),L=new ys(this),b=new Os(this.config),R=this.streamController=new xs(this,c,b),A=this.gapController=new ds(this,c);m.setStreamController(R),v.setStreamController(R);var w=[y,_,R];g&&w.splice(1,0,g),T&&w.splice(1,0,T),this.networkControllers=w;var I=[d,p,A,m,v,L,c];this.audioTrackController=this.createController(i.audioTrackController,w);var D=i.audioStreamController;D&&w.push(this.audioStreamController=new D(this,c,b)),this.subtitleTrackController=this.createController(i.subtitleTrackController,w);var C=i.subtitleStreamController;C&&w.push(this.subtititleStreamController=new C(this,c,b)),this.createController(i.timelineController,I),b.emeController=this.emeController=this.createController(i.emeController,I),this.cmcdController=this.createController(i.cmcdController,I),this.latencyController=this.createController(Es,I),this.coreComponents=I,w.push(h);var k=h.onErrorOut;"function"==typeof k&&this.on(P.ERROR,k,h),this.on(P.MANIFEST_LOADED,y.onManifestLoaded,y)}e.isMSESupported=function(){return Ms()},e.isSupported=function(){return function(){if(!Ms())return!1;var e=Ie();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(Oe(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Oe(t,"audio"))})))}()},e.getMediaSource=function(){return Ie()};var t=e.prototype;return t.createController=function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null},t.on=function(e,t,r){void 0===r&&(r=this),this._emitter.on(e,t,r)},t.once=function(e,t,r){void 0===r&&(r=this),this._emitter.once(e,t,r)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,r,i){void 0===r&&(r=this),this._emitter.off(e,t,r,i)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,r){return this._emitter.emit(e,t,r)},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 r=e===P.ERROR;this.trigger(P.ERROR,{type:R.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:r,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(P.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(P.ERROR,{type:R.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 r="media"in e,i=r?e.media:e,s=r?e:{media:i};this._media=i,this.trigger(P.MEDIA_ATTACHING,s)}},t.detachMedia=function(){this.logger.log("detachMedia"),this.trigger(P.MEDIA_DETACHING,{}),this._media=null},t.transferMedia=function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(P.MEDIA_DETACHING,{transferMedia:e}),e},t.loadSource=function(e){this.stopLoad();var t=this.media,r=this._url,i=this._url=T.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+i),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(P.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 r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);},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),function(e,t,r){var i=e.videoCodec,s=e.audioCodec;if(!i&&!s||!r)return Promise.resolve(Us);var n=[];if(i){var a={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},o=e.videoRange;"SDR"!==o&&(a.transferFunction=o.toLowerCase());var l=i.split(","),h=navigator.userAgent;if(l.some((function(e){return Re(e)}))&&De())return Promise.resolve(function(e,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:e}}(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: ("+h+")"),n));n.push.apply(n,l.map((function(e){return{type:"media-source",video:u(u({},a),{},{contentType:Oe($e(e),"video")})}})))}return s&&e.audioGroups&&e.audioGroups.forEach((function(e){var r;e&&(null==(r=t.groups[e])||r.tracks.forEach((function(t){if(t.groupId===e){var r=t.channels||"",i=parseFloat(r);_(i)&&i>2&&n.push.apply(n,s.split(",").map((function(e){return{type:"media-source",audio:{contentType:Oe(e,"audio"),channels:""+i}}})))}})))})),Promise.all(n.map((function(e){var t=function(e){var t=e.audio,r=e.video,i=r||t;if(i){var s=Ve(i.contentType);if(r)return"r"+r.height+"x"+r.width+"f"+Math.ceil(r.framerate)+(r.transferFunction||"sd")+"_"+s+"_"+Math.ceil(r.bitrate/1e5);if(t)return"c"+t.channels+(t.spatialRendering?"s":"n")+"_"+s}return""}(e);return Gs[t]||(Gs[t]=r.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}}))}(e,Ze(t),navigator.mediaCapabilities)},i(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={})[k]=this.streamController.inFlightFrag,e);return this.audioStreamController&&(t[M]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[x]=this.subtititleStreamController.inFlightFrag),t}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/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 qe.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 r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var s=e;s--;){var n=t[s].attrs["HDCP-LEVEL"];if(n&&n<=i)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 ws}},{key:"Events",get:function(){return P}},{key:"MetadataSchema",get:function(){return kr}},{key:"ErrorTypes",get:function(){return R}},{key:"ErrorDetails",get:function(){return A}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:Hi},set:function(t){e.defaultConfig=t}}])}();return Hs.defaultConfig=void 0,Hs},e.exports=i()}(!1)},424:(e,t)=>{"use strict";t.h=s;var r=2147483647;function i(e){if(e>r)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,r){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,r)}function n(e,t,r){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 r=0|u(e,t),n=i(r),a=n.write(e,t);a!==r&&(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(v(e,ArrayBuffer)||e&&v(e.buffer,ArrayBuffer))return function(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r);return i.__proto__=s.prototype,i}(e,t,r);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,r);var a=function(e){if(s.isBuffer(e)){var t=0|h(e.length),r=i(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?i(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,r);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),i(e<0?0:0|h(e))}function l(e){for(var t=e.length<0?0:0|h(e.length),r=i(t),s=0;s<t;s+=1)r[s]=255&e[s];return r}function h(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function u(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||v(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 r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return m(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;default:if(n)return i?-1:m(e).length;t=(""+t).toLowerCase(),n=!0}}function d(e,t,r,i){r=Number(r)||0;const s=e.length-r;i?(i=Number(i))>s&&(i=s):i=s;const n=t.length;let a;for(i>n/2&&(i=n/2),a=0;a<i;++a){const i=parseInt(t.substr(2*a,2),16);if(y(i))return a;e[r+a]=i}return a}function c(e,t,r,i){return p(m(t,e.length-r),e,r,i)}function f(e,t,r,i){return p(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function g(e,t,r,i){return p(function(e,t){let r,i,s;const n=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)r=e.charCodeAt(a),i=r>>8,s=r%256,n.push(s),n.push(i);return n}(t,e.length-r),e,r,i)}function p(e,t,r,i){let s;for(s=0;s<i&&!(s+r>=t.length||s>=e.length);++s)t[s+r]=e[s];return s}function m(e,t){var r;t=t||1/0;for(var i=e.length,s=null,n=[],a=0;a<i;++a){if((r=e.charCodeAt(a))>55295&&r<57344){if(!s){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(a+1===i){(t-=3)>-1&&n.push(239,191,189);continue}s=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),s=r;continue}r=65536+(s-55296<<10|r-56320)}else s&&(t-=3)>-1&&n.push(239,191,189);if(s=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function v(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,r){return n(e,t,r)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,r){return function(e,t,r){return a(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},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 r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var i=s.allocUnsafe(t),n=0;for(r=0;r<e.length;++r){var a=e[r];if(v(a,Uint8Array)&&(a=s.from(a)),!s.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(i,n),n+=a.length}return i},s.byteLength=u,s.prototype._isBuffer=!0,s.prototype.copy=function(e,t,r,i){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);var n=i-r;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,r,i);else if(this===e&&r<t&&t<i)for(var a=n-1;a>=0;--a)e[a+t]=this[a+r];else Uint8Array.prototype.set.call(e,this.subarray(r,i),t);return n},s.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}const s=this.length-t;if((void 0===r||r>s)&&(r=s),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return d(this,e,t,r);case"utf8":case"utf-8":return c(this,e,t,r);case"ascii":case"latin1":case"binary":return f(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}}},832:function(e,t,r){var i;!function(s){"use strict";function n(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function a(e,t,r,i,s,a){return n((o=n(n(t,e),n(i,a)))<<(l=s)|o>>>32-l,r);var o,l}function o(e,t,r,i,s,n,o){return a(t&r|~t&i,e,t,s,n,o)}function l(e,t,r,i,s,n,o){return a(t&i|r&~i,e,t,s,n,o)}function h(e,t,r,i,s,n,o){return a(t^r^i,e,t,s,n,o)}function u(e,t,r,i,s,n,o){return a(r^(t|~i),e,t,s,n,o)}function d(e,t){var r,i,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(r=0;r<e.length;r+=16)i=c,s=f,a=g,d=p,c=o(c,f,g,p,e[r],7,-680876936),p=o(p,c,f,g,e[r+1],12,-389564586),g=o(g,p,c,f,e[r+2],17,606105819),f=o(f,g,p,c,e[r+3],22,-1044525330),c=o(c,f,g,p,e[r+4],7,-176418897),p=o(p,c,f,g,e[r+5],12,1200080426),g=o(g,p,c,f,e[r+6],17,-1473231341),f=o(f,g,p,c,e[r+7],22,-45705983),c=o(c,f,g,p,e[r+8],7,1770035416),p=o(p,c,f,g,e[r+9],12,-1958414417),g=o(g,p,c,f,e[r+10],17,-42063),f=o(f,g,p,c,e[r+11],22,-1990404162),c=o(c,f,g,p,e[r+12],7,1804603682),p=o(p,c,f,g,e[r+13],12,-40341101),g=o(g,p,c,f,e[r+14],17,-1502002290),c=l(c,f=o(f,g,p,c,e[r+15],22,1236535329),g,p,e[r+1],5,-165796510),p=l(p,c,f,g,e[r+6],9,-1069501632),g=l(g,p,c,f,e[r+11],14,643717713),f=l(f,g,p,c,e[r],20,-373897302),c=l(c,f,g,p,e[r+5],5,-701558691),p=l(p,c,f,g,e[r+10],9,38016083),g=l(g,p,c,f,e[r+15],14,-660478335),f=l(f,g,p,c,e[r+4],20,-405537848),c=l(c,f,g,p,e[r+9],5,568446438),p=l(p,c,f,g,e[r+14],9,-1019803690),g=l(g,p,c,f,e[r+3],14,-187363961),f=l(f,g,p,c,e[r+8],20,1163531501),c=l(c,f,g,p,e[r+13],5,-1444681467),p=l(p,c,f,g,e[r+2],9,-51403784),g=l(g,p,c,f,e[r+7],14,1735328473),c=h(c,f=l(f,g,p,c,e[r+12],20,-1926607734),g,p,e[r+5],4,-378558),p=h(p,c,f,g,e[r+8],11,-2022574463),g=h(g,p,c,f,e[r+11],16,1839030562),f=h(f,g,p,c,e[r+14],23,-35309556),c=h(c,f,g,p,e[r+1],4,-1530992060),p=h(p,c,f,g,e[r+4],11,1272893353),g=h(g,p,c,f,e[r+7],16,-155497632),f=h(f,g,p,c,e[r+10],23,-1094730640),c=h(c,f,g,p,e[r+13],4,681279174),p=h(p,c,f,g,e[r],11,-358537222),g=h(g,p,c,f,e[r+3],16,-722521979),f=h(f,g,p,c,e[r+6],23,76029189),c=h(c,f,g,p,e[r+9],4,-640364487),p=h(p,c,f,g,e[r+12],11,-421815835),g=h(g,p,c,f,e[r+15],16,530742520),c=u(c,f=h(f,g,p,c,e[r+2],23,-995338651),g,p,e[r],6,-198630844),p=u(p,c,f,g,e[r+7],10,1126891415),g=u(g,p,c,f,e[r+14],15,-1416354905),f=u(f,g,p,c,e[r+5],21,-57434055),c=u(c,f,g,p,e[r+12],6,1700485571),p=u(p,c,f,g,e[r+3],10,-1894986606),g=u(g,p,c,f,e[r+10],15,-1051523),f=u(f,g,p,c,e[r+1],21,-2054922799),c=u(c,f,g,p,e[r+8],6,1873313359),p=u(p,c,f,g,e[r+15],10,-30611744),g=u(g,p,c,f,e[r+6],15,-1560198380),f=u(f,g,p,c,e[r+13],21,1309151649),c=u(c,f,g,p,e[r+4],6,-145523070),p=u(p,c,f,g,e[r+11],10,-1120210379),g=u(g,p,c,f,e[r+2],15,718787259),f=u(f,g,p,c,e[r+9],21,-343485551),c=n(c,i),f=n(f,s),g=n(g,a),p=n(p,d);return[c,f,g,p]}function c(e){var t,r="",i=32*e.length;for(t=0;t<i;t+=8)r+=String.fromCharCode(e[t>>5]>>>t%32&255);return r}function f(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var i=8*e.length;for(t=0;t<i;t+=8)r[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return r}function g(e){var t,r,i="0123456789abcdef",s="";for(r=0;r<e.length;r+=1)t=e.charCodeAt(r),s+=i.charAt(t>>>4&15)+i.charAt(15&t);return s}function p(e){return unescape(encodeURIComponent(e))}function m(e){return function(e){return c(d(f(e),8*e.length))}(p(e))}function v(e,t){return function(e,t){var r,i,s=f(e),n=[],a=[];for(n[15]=a[15]=void 0,s.length>16&&(s=d(s,8*e.length)),r=0;r<16;r+=1)n[r]=909522486^s[r],a[r]=1549556828^s[r];return i=d(n.concat(f(t)),512+8*t.length),c(d(a.concat(i),640))}(p(e),p(t))}function y(e,t,r){return t?r?v(t,e):g(v(t,e)):r?m(e):g(m(e))}void 0===(i=function(){return y}.call(t,r,t,e))||(e.exports=i)}()},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var r={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[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 r.isAndroid()||r.isAndroidWebView()?t.ANDROID_WEB:r.isIOS()||r.isIpad()||r.isIOSWebView()?t.IOS_WEB:r.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!n(s("os "))&&!n(s("android[/ ]"))},isIOS:function(){return n(s("os "))},isIpad:function(){return i().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(i())},isMobile:function(){return r.isAndroid()||r.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=i();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=i();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return r.isAndroidWebView()||r.isIOSWebView()},device:t,getBrowser:function(){return r.isX5()?"X5":r.isAndroidWebView()?"Android-WebView":r.isIOSWebView()?"iOS-WebView":r.isChrome()?"Chrome":r.isFirefox()?"Firefox":r.isIpadSafari()?"iPad-Safari":r.isIOSSafari()?"iPhone-Safari":r.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function s(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=r}},t={};function r(i){var s=t[i];if(void 0!==s)return s.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,r),n.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};return(()=>{"use strict";r.d(i,{default:()=>Fr});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=r(415),n=r.n(s),a=r(424),o=r(558),l=r.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,r){const i=new URL(e);return i.searchParams.append(t,r),i.href}function g(){return Date.parse(new Date)/1e3}function p(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function m(e){return new Promise((t=>setTimeout(t,e)))}function v(){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),r=new a.h(e.byteLength);return t.copy(r),r}function E(){return location.protocol.startsWith("https")}function S(e,t,r){if(e.size<=t)return;const i=[...e.keys()];do{const t=i.shift();r&&r(e.get(t)),e.delete(t)}while(e.size>t)}function T(e,t){if(e.size<=t)return;const r=[...e.values()];do{e.delete(r.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 r=Number(t[0]),i=t[1]?Number(t[1]):-1;return{rangeStart:r,rangeEnd:i>=0?i+1:void 0}}function b(e){return e.split("?")[0]}function R(){let e=new Date,t=e.getHours(),r=e.getMinutes(),i=e.getSeconds(),s=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${s}`}function A(e){return e&&"function"==typeof e}function P(e,t,r,i,s,n){e.sendPartialBuffer(r,i,{from:s,incompletes:n})&&(i.length<r.attachments?function(e,t,r){e.addStreamListener(r,t.remotePeerId,((e,r,i,s,n)=>{i?t.sendMsgPieceAbort(s,r,!0):t.uploading&&t.send(s),n&&(t.uploading=!1)}))}(t,e,!!r.reverse):e.uploading=!1)}const w=e=>0===p(0,1)?[null,e]:[e,null];function I(e,t,r){return 1===e.length?t.length>=1&&r.length>=1?t[0].weight>r[0].weight?[t[0],e[0]]:[e[0],r[0]]:t.length>=1?[t[0],e[0]]:r.length>=1?[e[0],r[0]]:w(e[0]):[t.length>=1?t[0]:null,r.length>=1?r[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 C(e){if(crypto.subtle)try{const t=await crypto.subtle.digest("SHA-256",e),r=String.fromCharCode.apply(null,new Uint8Array(t));return btoa(r)}catch(e){}}class k{constructor(e,t){this.target=t,this.type=e}}class M extends k{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class x extends k{constructor(e=1e3,t="",r){super("close",r),this.code=e,this.reason=t,this.wasClean=!0}}const O=()=>{if("undefined"!=typeof WebSocket)return WebSocket},N={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1};class F{constructor(e,t,r={}){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=r,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 F.CONNECTING}get OPEN(){return F.OPEN}get CLOSING(){return F.CLOSING}get CLOSED(){return F.CLOSED}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?F.CLOSED:F.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=N.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 r of t)this._callEventListener(e,r);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=N.reconnectionDelayGrowFactor,minReconnectionDelay:t=N.minReconnectionDelay,maxReconnectionDelay:r=N.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=t*Math.pow(e,this._retryCount-1),i>r&&(i=r)),i}_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=N.maxRetries,connectionTimeout:t=N.connectionTimeout,WebSocket:r=O()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(i=r)||!i||2!==i.CLOSING)throw Error("No valid WebSocket class provided");var i;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new r(e,this._protocols):new r(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 x(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=N.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,r,i){this.wsAddr=`${e}?app=${t}&id=${r}&v=${i}`,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 F(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const r=B[e];this._ws.send(JSON.stringify({records:[{level:r,text:`${R()}: ${t}`}]}))}sendBatch(e){const t=[];for(let r of e)t.push({level:B[r.levelKey],text:r.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,r)=>{((e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)})(e,{value:t,duration:r,startTime:Date.now()})},$={debug:0,info:1,warn:2,error:3,none:4};const W=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 $||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in $)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:`${R()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,r,i,s=5e3){this.reportUrl&&!this.reporter&&(e&&this.logCache.unshift({levelKey:"info",message:e}),this.reporter=new U(this.reportUrl,t,r,i),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 $){const r=this[t];this[t]=i=>{e(t,i),r(i)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in $)$[e]<$[this.logLevel]?this[e]=d:this[e]=console[e]}get isDebugLevel(){return $[this.logLevel]<=2||this.onlineDebug}};let V;const q="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(V||(V=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),j=65536;function z(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class K extends(n()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||K.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},K.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=v(),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 q((()=>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 r;!t.address||t.address.endsWith(".local")?(r="Ignoring unsupported ICE candidate.",console.warn(r)):(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,q((()=>{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,q((()=>{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=j),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>j}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=z(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=z(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((r=>{const i=[];r.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((r=>{if(this.destroyed)return;const i=[];r.result().forEach((e=>{const r={};e.names().forEach((t=>{r[t]=e.stat(t)})),r.id=e.id,r.type=e.type,r.timestamp=e.timestamp,i.push(t(r))})),e(null,i)}),(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,r)=>{if(this.destroyed)return;t&&(r=[]);const i={},s={},n={};let a=!1;r.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[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 r=i[e.remoteCandidateId];r&&(r.ip||r.address)?(this.remoteAddress=r.ip||r.address,this.remotePort=Number(r.port)):r&&r.ipAddress?(this.remoteAddress=r.ipAddress,this.remotePort=Number(r.portNumber)):"string"==typeof e.googRemoteAddress&&(r=e.googRemoteAddress.split(":"),this.remoteAddress=r[0],this.remotePort=Number(r[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(r.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>j||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()}}K.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},K.channelConfig={};const Y=K;class X{constructor(e,t,r,i,s=0,n={}){this.sn=e,this.segId=t,this.data=r,this.fromPeerId=i,this.level=s,this.ext=n}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var Q=r(365),J=r.n(Q);class Z extends(n()){static get defaultPacketSize(){return u}static get VERSION(){return"8"}constructor(e,t,r,i,s,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=s,this.isInitiator=i,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,r),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,r){this.remotePeerId=r,this.channelId=this.isInitiator?`${t}-${r}`:`${r}-${t}`,r&&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:r,signalName:i}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${r} signalName ${i}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:r,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,r,i){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${i} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:r,seg_id:i}))))}addStreamListener(e,t,r){this.streamListeners.push({handler:r,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 Y({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let r=!0;(this.connected||this.notFatalClosed)&&(r=!1);let i=t.message;t.debug&&(i=`${i} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,r,i)})),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:r}=this;if("string"==typeof t){let i=JSON.parse(t);if(!i)return void r.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(i);let s,n=i.event;switch(s=n!==e.DC_PLAYLIST&&n!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${n}`,r.debug(`datachannel receive ${s} from ${this.remotePeerId}`),n){case e.DC_HAVE:if(this.emit(i.event,i),!i.sn)return;this.config.live||(i.sn<this.startSN&&(this.startSN=i.sn),i.sn>this.endSN&&(this.endSN=i.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=g(),this.timeReceivePiece=performance.now(),this.pieceMsg=i,this._prepareForBinary(i.attachments,i.seg_id,i.sn,i.size),this.emit(i.event,i);break;case e.DC_PIECE_CANCEL:r.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(i.event,i),this.sendMsgPieceAbort("transfer canceled",i.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(i.event,i);break;case e.DC_REQUEST:this._handleRequestMsg(i);break;case e.DC_PIECE_ACK:this._handlePieceAck(i.seg_id,i.size,i.miss);break;case e.DC_STATS:this._handleStats(i);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(i);break;case e.DC_METADATA:this._handleMetadata(i);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,i)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:r.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:r.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(i.event,i.fatal||!1);break;default:this.emit(i.event,i)}}else{if(!t)return void r.error("datachannel on data is undefined!");if(!this.downloading){const i=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return r.warn(i),void this.emit(e.DC_ERROR,!1,i)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,r)=>{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 r=JSON.stringify(t);return r.length>u?(this.logger.error("string to send is too large"),!1):this.send(r,!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 r=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,r)}return!1}sendMsgHave(t,r,i={}){const s=i.reverse||void 0;delete i.reverse,this.sendJson({event:s?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:r,...i})}sendPieceNotFound(t,r,i={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:r||void 0,sn:t,...i})}sendPeers(t){this.sendJson({event:e.DC_PEERS,peers:t})}sendPeersRequest(){this.sendJson({event:e.DC_GET_PEERS})}sendMsgStats(t,r={}){const i={event:e.DC_STATS,total_conns:t,...r};this.sendJson(i)}sendMsgPlaylist(t,r,i){const s=this.playlistMap.get(t);if(s&&s.seq>=i)return;const n={event:e.DC_PLAYLIST,url:t,data:r,seq:i};this.playlistMap.set(t,{data:r,seq:i}),this.sendJson(n)}sendMsgSignal(t,r,i){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:r,data:i})}sendMsgSignalReject(t,r,i,s=!1){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:r,reason:i,fatal:s})}sendMetaData(t,r,i,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.15.8",sequential:r,peers:i,region:s})}sendPartialBuffer(e,t,r={}){if(!this.sendMsgPiece(e,r))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 r={...e,ext:t};return this.sendJson(r)}sendBuffer(t,r,i,s={}){const n=s.reverse||void 0;if(delete s.reverse,!i)return void this.logger.error("sendBuffer payload is undefined!");let a=i.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:r,sn:t,level:s.level,size:a,reverse:n};if(delete s.level,!this.sendMsgPiece(h,s))return;const u=function(e,t,r,i){let s=[];if(i){let n;for(let i=0;i<r-1;i++)n=e.slice(i*t,(i+1)*t),s.push(n);n=e.slice(e.byteLength-i,e.byteLength),s.push(n)}else{let i;for(let n=0;n<r;n++)i=e.slice(n*t,(n+1)*t),s.push(i)}return s}(i,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,r,i=!1,s={}){const n={event:e.DC_REQUEST,seg_id:t,sn:r,...s,urgent:i};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${t} in queue`),i?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}requestDataBySN(t,r=!1,i={}){const s={event:e.DC_REQUEST,sn:t,...i,urgent:r};this.downloading?(this.logger.info(`add req ${t} in queue`),r?this.sendReqQueue.unshift(s):this.sendReqQueue.push(s)):this._realRequestData(s)}_sendBufferArray(e,t=!1){const r=t?e.reverse():e;for(let e=0;e<r.length;e++)this.send(r[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:r}=t;r(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 r={event:e.DC_CLOSE,fatal:t};this.sendJson(r),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:r,reverse:i}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let s=i?this.remainAttachments+1:r-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:r}=e;r(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(i)}}_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:r,seq:i}=e;this.playlistMap.set(t,{data:r,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const r=this.playlistMap.get(e);return r.seq<=t||r.seq>t+2?null:r}_handleMetadata(t){const{logger:r}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,r.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const i=t.channel;if(this.channel!==i){const t=`peer channel ${i} not matched!`;return r.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){r.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:i}=this.config;if(i&&t.token!==i)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,r.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,r.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,r,i){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(r/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),i>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${i}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:r})}_prepareForBinary(e,t,r,i){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=r,this.expectedSize=i}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let r=a.h.concat(this.bufArr);const i=r.byteLength;if(i===this.expectedSize){let t=r.buffer;const i=new X(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,i,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${i}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,r=performance.now()-this.timeSendRequest;if((e||!(r<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,r,i=!1){const s=this.datasToSend.length;if(!i&&!this.uploading&&0===s)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(r,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 re={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class ie 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,r=()=>{this.curTsUri&&function(e,t,r,i=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=i,n.onreadystatechange=e=>{if(4===n.readyState){const e=n.status;206===e||200===e&&t?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),r&&r(n,e),n.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((i=>{e.httpRangeSupported=!1,t&&t.warn(i),this.rangeRequestTimer=setTimeout(r,6e4)})).finally((()=>{t&&t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(r,0)}initLogger(){const{config:e}=this;e.showSlogan&&"en"==("zh-CN"===(navigator.language||navigator.userLanguage)?"cn":"en")&&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 W(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 A(t)?(r,i)=>`${e}-${t(r,i)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,r=`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:i}=t;if(i){let s;"object"==typeof i?(i.main||(i.main=r),s=i.main):"string"==typeof i&&(s=i,t.wsSignalerAddr={main:s}),s===r&&(s=void 0),s&&!t.wsSignalerAddr.backup&&(e=l().parseURL(s).netLoc.substring(2))}else t.wsSignalerAddr={main:r,byDefault:!0};return e}get commonBrowserInfo(){const e=J().getPlatform(),t=J().getNetType()||"wifi";this.netType=t;const{main:r,backup:i,byDefault:s}=this.config.wsSignalerAddr||{};return{signal:r,custom_signal:!s||void 0,signal2:i,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",r=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,r)};e?self.removeEventListener(t,r):self.addEventListener(t,r)}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 ie.version}static isSupported(){const e=v();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,r){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${r}`);let i=4;return t<=2?i=1.5:t<=3?i=2:t<=4?i=2.5:t<=5?i=3:t<=6&&(i=3.5),i}emitEvent(e,...t){this.emit(e,...t);const r=re[e];r&&A(this.config[r])&&this.config[r](...t)}}ie.version="2.15.8",ie.protocolVersion=ee.VERSION;const se=ie;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 r;if(e&&("string"==typeof e?(r=document.querySelector(e),oe(r)||(r=function(e){const t=document.getElementById(e);if(oe(t))return t;if(!t)return null;const r=t.getElementsByTagName("*");for(let e=0;e<r.length;e++)if(oe(r[e]))return r[e];return null}(e))):e instanceof HTMLMediaElement&&(r=e)),!r){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?r=e[0]:(t&&(r=e.find((e=>e.src===t))),r||(r=e.find((e=>e.currentTime>0))))}return r}function oe(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function le(e,t,r,i=0,s=0){const n=u;let a=i,o=s||r-1;const l=Math.floor(r/n),h=r%n>0?l+1:l;if(e>=0&&(a+=(e+1)*n),t>=0&&t<h){o-=r%n+(h-t-1)*n}return{rangeStart:a,rangeEnd:o+1}}function he(e,t){return`${e}-${t}`}function ue(e,t,r,i){let s=r.split("?")[0];return s.startsWith("http")&&(s=s.split("://")[1]),i?`${s}|${i}`:`${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:!0,trickleICE:!0,announceLocation:"eu",trackerZone:void 0,geoIpPreflight:!0,ICEPreflight:!0,useDiskCache:!0,startFromSegmentOffset:3,getStats:function(e,t,r){},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,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)})),r=(i=ge,s="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(s)}),i))));var i,s;return Promise.race([t,r])}const me={};async function ve(e,t,r=!0){const i=me[e]||{};i.promise||(i.promise=new Promise((e=>i.resolve=e)),me[e]=i,Ee(e,t,i.resolve,r));const s=await i.promise;return delete i.promise,s}const ye={};async function Ee(e,t,r,i){if(!ye[e]){const i=indexedDB.open(e);return i.onupgradeneeded=()=>{const e=i.result;t.forEach((t=>{e.createObjectStore(t)}))},void r(ye[e]=await pe(i))}if(i)try{t.forEach((t=>{ye[e].transaction(t)})),r(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,r,i)}else r(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,r=Te()){return r("readwrite",(r=>(r.put(t,e),pe(r.transaction))))}function be(e,t=Te()){return t("readwrite",(t=>(t.delete(e),pe(t.transaction))))}function Re(e=Te()){return e("readwrite",(e=>(e.clear(),pe(e.transaction))))}function Ae(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},pe(e.transaction)}const Pe="size";class we 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 r=e.browserInfo.device;this.isPC=r===J().device.PC_WEB||r===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 r=this.stores;let i;try{i=function(e,t){let r=ve(e,t);return t.map((i=>(s,n)=>r.then((a=>{try{const e=a.transaction(i,s).objectStore(i);return n(e)}catch(a){r=ve(e,t),r.then((e=>n(e.transaction(i,s).objectStore(i))))}}))))}(this.channel,r)}catch(e){return void t(e)}this._createStores(i),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return Le(Pe,0,this.metaStore)}currBufSize(){return new Promise((async(t,r)=>{try{const i=await _e(Pe,this.metaStore);if(isNaN(i))return this.engine.emit(e.BM_FATAL_ERROR),void r("size is NaN");t(i)}catch(e){r(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:r}=this;if(_(t.data))return new Promise((i=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),this.countErrors=0,i()})).catch((e=>{this._handleFataError(),e&&(r.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}`)}))),i()}))}));r.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(Pe,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(e){this.destroyed||this.currBufSize().then((t=>{Le(Pe,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){Re(this.segmentsStore),e?this._initMetaStore():Re(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 Ie=we;const De=class extends Ie{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((r=>{void 0!==t?_e(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?r(!0):r(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),r(!1)})):r(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let r;try{r=await _e(e,this.id2SnStore)}catch(e){return null}return new Promise((i=>{void 0!==r?_e(r,this.segmentsStore).then((r=>{if(this.countErrors=0,r&&r.length>0){const s=r.find((t=>t.segId===e));if(!s)return void i(null);if(!_(s.data))return t.error(`getSegById ${s.sn} is not buffer`),void i(null);i(Ie.toSegment(s))}else i(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),i(null)})):i(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:r,size:i}=e;return Le(t,r,this.id2SnStore),new Promise(((s,n)=>{_e(r,this.segmentsStore).then((async a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(await this._segmentToCache(e)),Le(r,a,this.segmentsStore).then((()=>{this._increaseBufSize(i),s(e)})).catch((e=>{n(e)}))):s(e):Le(r,[await this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(i),s(e)})).catch((e=>{n(e)}))})).catch((e=>{n(e)}))}))}async _trimDisk(t,r=!1){if(this.isCleared||this.destroyed)return;let i=this.maxBufSize;const{logger:s}=this;r&&(i=t-104857600,i<0&&(i=0)),t<i||(s.warn(`_trimDisk currentSize ${t} upBound ${i}`),function(e=Te()){return e("readonly",(e=>{if(e.getAllKeys)return pe(e.getAllKeys());const t=[];return Ae(e,(e=>t.push(e.key))).then((()=>t))}))}(this.segmentsStore).then((async r=>{const n=r.sort(((e,t)=>e-t));let a=0;do{if(a++>10){s.warn("too much loops in SegmentStore");break}const r=n.shift();if(void 0===r){s.warn("lastSN not found");continue}if(r>=this.loadingSN){s.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const i=n[0],o=await _e(r,this.segmentsStore);if(!o){s.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),be(r,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:r,segId:t.segId,next:i,level:t.level})})),t-=l,s.info(`pop sn ${r} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=i)})))}async _segmentToCache(e){const{ext:t={}}=e;let r=t.hash;r||(r=await C(e.data));const i={data:e.data,level:e.level,segId:e.segId,sn:e.sn,fromPeerId:e.fromPeerId,ext:{}};return r&&(i.ext.hash=r),i}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}Re(this.id2SnStore).catch((e=>{}))}};class Ce extends(n()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const r=e.browserInfo.device;if(this.maxBufSize=r===J().device.PC_WEB||r===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 ke=Ce;const Me=class extends ke{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,r)=>{const i=this.id2Sn.get(e);this._segPool.has(i)?t(this._segPool.get(i).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((r,i)=>{if(!this._segPool.has(t))return void r(null);const s=this._segPool.get(t).find((t=>t.segId===e));r(s||null)}))}getSegIdBySN(e){return new Promise(((t,r)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}async _addSeg(t){const{logger:r}=this,{segId:i,sn:s,size:n,ext:a={}}=t;if(this.id2Sn.set(i,s),a.hash||(a.hash=await C(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){r.error("too much loops in SegmentCache");break}const t=l.shift();if(void 0===t){r.error("lastSN not found");continue}const i=l[0],s=this._segPool.get(t);if(!s){r.error("lastSeg not found");continue}let n=0;s.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(t),s.forEach((r=>{this.id2Sn.delete(r.segId),this.emit(e.BM_LOST,{sn:t,segId:r.segId,next:i,level:r.level})})),r.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 xe=r(832),Oe=r.n(xe);function Ne(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}const Fe=function(e,t,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof t&&(r=t,t=void 0),null!=t&&(r.code=t);try{return Ne(e,r)}catch(t){r.message=e.message,r.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),Ne(new i,r)}};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,$e="TRACKER_EXPT",We="IPAPI_ERROR",Ve="uY2R",qe="LmNv",je="uYnll",ze="bQ==",Ke="Z3o",Ye="aGsuc3d",Xe="hcm1j",Qe="bG91ZC",Je="5uZXQ=",Ze=Symbol("httpDownloaded"),et=Symbol("p2pDownloaded"),tt=Symbol("p2pUploaded");class rt extends(n()){constructor(e,t,r,i,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=Ye+Xe+Qe+Je;break;case"us":n="dXMuaGR0dmNsb3VkLmNvbQ==";break;case"cn":n=Ke+Ve+je+qe+ze;break;default:n="ZXUuaGR0dmNsb3VkLmNvbQ=="}this.engine=e,this.key=t||void 0,Array.isArray(i)&&(i=i[Math.floor(Math.random()*i.length)]),this.baseUrl=i||`https://${self.atob(n)}/v1`,this.channelId=self.btoa(r),this.timestamp=g(),this.health=new Be;const o=l().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,""),function(e,t){function r(e,t,r,i,s){return h(r-219,s)}var i,s,n=e();function a(e,t,r,i,s){return h(s- -994,e)}function o(e,t,r,i,s){return h(i-233,t)}function l(e,t,r,i,s){return h(s-305,r)}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(r(0,0,225,0,216))/5)+-parseInt((i=-180,s=-173,h(s- -181,i)))/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(r(0,0,226,0,216))/12))break;n.push(n.shift())}catch(e){n.push(n.shift())}}(d);function h(e,t){var r=d();return(h=function(e,t){return r[e-=0]})(e,t)}const u=function(e,t,r,i,s,n){let a=location.hostname;a===h(-922- -923,-915)&&n&&(a=n+"."+a);return 13,Oe()(a+"2.15.8"+r+i+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.15.8",v:u,announce:this.announce,k:at(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[et]=0,this[tt]=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,r)=>{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 r=G(Ue);e.info("found local geo data"),t(r)}else fetch(self.atob("aHR0cHM6Ly9wcm8uaXAtYXBpLmNvbS9qc29uP2ZpZWxkcz0yMTgxODI2JmtleT1YT3BpYW5zUmdZeEdUaG8=")).then((e=>e.json())).then((e=>{if("success"!==e.status){const t=new Error(`preflight status ${e.status}`);throw Fe(t,We)}{const r=e.mobile?He:Ge;H(Ue,e,r),t(e)}})).catch((e=>{r(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(Fe(new Error("request timeout"),We))}),600)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(t.code!==$e){const t=G(Ue);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:r,isp:i,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:r,isp:i,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,r)=>{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 Fe(new Error(`server response code is ${e.status}`),$e,{retry:t})}return e.json()})).then((e=>{if(!this.engine)throw Fe(new Error("runtime error"),$e,{retry:!1});const r=e.data;if(r.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:r}=e.data;throw Fe(new Error(r),$e,{retry:t>=5e3})}if(r.info&&console.info(`${r.info}`),r.warn&&console.warn(`${r.warn}`),r.min_conns||(r.min_conns=8),(!r.rejected||r.rejected&&r.share_only)&&r.id&&r.report_interval&&r.peers){if(this.peerId=this.id=r.id,r.report_interval<20&&(r.report_interval=20),this.btStats(r.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&&r.asn){const{country:e,asn:t,mobile:i,isp:s,lat:n,lon:a}=r;this.announceInfo={...this.announceInfo,country:e,asn:t},H(Ue,{countryCode:e,as:`AS${t}`,mobile:i,isp:s,lat:n,lon:a,status:"success"},i?He:Ge)}t(r)}else this.engine&&(this.engine.p2pEnabled=!1)})).catch((t=>{e.error(`btAnnounce error ${t}`);const i=t.code||$e,s=!t.code||t.retry;r(Fe(t,i,{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((r=>{let i;if(i=r?JSON.parse(r):{ret:0,data:{}},-1===i.ret)clearInterval(this.heartbeater),t.error(`${i.data.msg} code ${i.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:r=0,failConns:i=0,rebuffers:s=0,requests:n=0,errsInternalExpt:a=0}=this.lastStats||{};this[Ze]>=e&&(this[Ze]-=e),this[et]>=t&&(this[et]-=t),this[tt]>=r&&(this[tt]-=r),this.failConns>=i&&(this.failConns-=i),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:r}=this.engine,{asn:i,country:s}=this.announceInfo;let n={exclusions:e,asn:i,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((r=>{-1===r.ret?t(r.data.msg):e(r.data)})).catch((e=>{r.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 r=Math.round(e/1024);this[et]+=r,this.totalP2PDownloaded+=r,this.health.recordP2p(r),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",r,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[tt]+=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:r}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:r,p2pDownloadSpeed:this.speed});const{getStats:i}=this.config;A(i)&&i(t,r,e,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let r={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[et])||0,share:Math.round(this[tt])||0,asn:e,country:t},i={};this.engine.getExtraForStats&&(i=this.engine.getExtraForStats()),r=Object.assign({},r,i),this.lastStats=JSON.parse(JSON.stringify(r)),Object.keys(r).forEach((e=>{0===r[e]&&delete r[e]}));const{logger:s}=this.engine;return s.isDebugLevel&&s.info(`report ${JSON.stringify(r)}`),this.exptMsg&&(r.exptMsg="2.15.8 "+this.exptMsg),r}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":at(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const it=rt;function st(e,t){const r=nt();return(st=function(e,t){return r[e-=0]})(e,t)}function nt(){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(nt=function(){return e})()}function at(e){if(!e)return;const t=st(-822- -830,-826);let r="".split("").reverse().join("");const i=t.length;for(let s=0;s<e.length;s++){const n=e.charCodeAt(s)^t.charCodeAt(s%i);r+=String.fromCharCode(n)}return self.btoa(r)}!function(e,t){const r=e();function i(e,t,r,i,s){return st(e-92,s)}function s(e,t,r,i,s){return st(s-930,r)}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,st(n- -999,a)))/5+parseInt(i(94,0,0,0,91))/6+-parseInt(i(93,0,0,0,92))/7+-parseInt(i(102,0,0,0,107))/8)break;r.push(r.shift())}catch(e){r.push(r.shift())}var n,a}(nt);class ot 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 m(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 lt=class{constructor(e,t,r,i="main"){this.logger=e,this.config=t,this.wsAddr=r,this.serverVersion=0,this.pingInterval=95e3,this.name=i,this.normalClosed=!1,this.lastSendTs=performance.now(),this.pollingClient=new ot(e,r);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 F(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 r=JSON.stringify(e);t.push(r)},t.addEventListener("message",(e=>{let t=e.data;const r=JSON.parse(t),i=r.action;if("pong"!==i){if("ver"!==i)return"close"===i?(this.logger.warn(`server close signal ${this.name} reason ${r.reason}`),void this.close()):void(this.onmessage&&this.onmessage(r,this.name));this.serverVersion=r.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 ot(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,r){this._send({action:"debug",details:t,ping:r||void 0,to:e})}sendSignal(e,t){const r={action:"signal",to:e,data:t};this._send(r)}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let r of t)this.sendSignal(e,r)}sendReject(e,t,r){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const i={action:"reject",to:e,reason:t,fatal:r};this._send(i)}_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===F.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)this.onmessage(t,this.name)}}},ht=class{constructor(e,t,r,i){this.logger=e,this.config=t,this.mainAddr=r,this.backupAddr=i,this.mainWS=this._init(r),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(i,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let r=new lt(this.logger,this.config,e,t);return r.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},r.onmessage=e=>{this.onmessage&&this.onmessage(e,r.name)},r.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},r.onerror=e=>{this.onerror&&this.onerror(e)},r}sendSignalBatch(e,t,r){if(r){const i=this._getWSByName(r);i&&i.sendSignalBatch(e,t)}else this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected&&this.backupWS.sendSignalBatch(e,t)}sendSignal(e,t,r){this.sendSignalBatch(e,[t],r)}sendReject(e,t,r,i){if(i){const s=this._getWSByName(i);if(s)return void s.sendReject(e,t,r)}this.mainConnected?this.mainWS.sendReject(e,t,r):this.backupConnected?this.backupWS.sendReject(e,t,r):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,r){this.mainConnected&&this.mainWS.sendDebug(e,t,r)}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 ut=function(e,t,r=40){var i=null,s=!1,n=r;return function(r=!1){if(r)return clearTimeout(i),void(s=!1);s||(s=!0,i=setTimeout((function(){e.call(t,n),s=!1,i=null}),1e3*n),n*=1.1)}};class dt{constructor(e,t,r=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=r,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 ct=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,r=0,i="";for(const s of e){if("="===s)break;const e=this.CHARSET.indexOf(s);for(t=t<<this.BITS_PER_BASE64_CHAR|e,r+=this.BITS_PER_BASE64_CHAR;r>=this.BITS_PER_BYTE;){r-=this.BITS_PER_BYTE;i+=(t>>r&(1<<this.BITS_PER_BYTE)-1).toString(16).padStart(2,"0").toUpperCase()}}let s="";for(let e=0;e<i.length;e++)s+=i[e],e%2==1&&e!==i.length-1&&(s+=":");return s}},ft="typ host",gt="generation 0",pt="network-cost",mt="rport",vt="0.0.0.0",yt={V:"v=",O:"o=",S:"s=",C:"c=",A:"a=",M:"m=",T:"t="},Et={U:"ice-ufrag:",P:"ice-pwd:",F:"fingerprint:",C:"candidate:",S:"sctp-port:",M:"max-message-size:"},St={1:"sha-1",2:"sha-224",3:"sha-256",4:"sha-384",5:"sha-512",6:"md5",7:"md2",8:"token"},Tt={P:`${ft} ${gt} ${pt} 999`,W:`${mt} 0 ${gt} ${pt} 999`,H:ft,S:"typ srflx",R:mt,A:"raddr",V:vt,F:"ufrag",G:`${mt} 0 ${gt}`,N:pt,E:"network-id",C:"tcptype active",Q:`${gt}`,U:"udp",T:"tcp"},_t={P:"application",U:"UDP/DTLS/SCTP",S:"DTLS/SCTP",D:"webrtc-datachannel"},Lt={4:"IP4",6:"IP6"},bt={0:vt},Rt=e=>(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in Tt&&(e=Tt[e]),e))).join(" "));function At(e,t){let r=e.split("~"),i=[];r=r.map((e=>{let t=e.slice(0,1),r=e.slice(1);if(t in yt&&(t=yt[t]),"a="===t){let e=r.slice(0,1);const t=r.slice(1);e in Et&&(e=Et[e],r=e+t)}return t+r})),i.push("v=0"),i.push("s=-"),i.push("t=0 0"),i.push("a=msid-semantic: WMS");let s=0;r.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),r=[];r.push("-");const s=t.shift();if(s&&r.push(s),0===t.length)r.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&r.push(e),0===t.length)r.push("IN IP4 127.0.0.1");else{r.push("IN");const e=t.shift();e&&r.push(e);const i=t.shift();i&&r.push(i)}}i.splice(1,0,`o=${r.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(Pt,(e=>_t[e]))}(e),i.push(e),i.push("a=setup:"+(t?"actpass":"active")),i.push(`a=mid:${s}`),void s++;if(e.startsWith("a=candidate:"))return e=Rt(e),void i.push(e);if(e.startsWith("a=fingerprint:")){let[t,r]=e.slice(14).split(" ");return t in St&&(t=St[t]),r=ct.decode(r),void i.push(`a=fingerprint:${t} ${r}`)}if(e.startsWith("c=")){let[t,r]=e.slice(2).split(" ");return t in Lt&&(t=Lt[t]),r in bt&&(r=bt[r]),void i.push(`c=IN ${t} ${r}`)}"I"!==e?"Z"!==e?"B"!==e?i.push(e):i.push("a=sendrecv"):i.push("a=ice-options:ice2,trickle"):i.push("a=ice-options:trickle")}}));const n=i.length-1;return i.splice(n,0,`a=group:BUNDLE ${Array.from(Array(s).keys()).join(" ")}`),i.join("\r\n")}const Pt=new RegExp(Object.keys(_t).join("|"),"g");class wt extends(n()){constructor(e,t,r,i){super(),this.engine=e,this.logger=e.logger,this.config=i,this.connected=!1,this.scheduler=r,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set;const s=J().isMobile();this.peerPool=new dt(e,i,15),this.signalerWs=null,this.fetcher=t,this.peers=[],this.requestPeersQueue=[],this.minConns=5,this.stuns=[],this.requestMorePeers=ut(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:r,fetcher:i}=this,{btAnnounce:s,btAnnouncePreflight:n}=i,{wsSignalerAddr:a,wifiOnly:o,geoIpPreflight:l}=r;(l?n:s).call(i).then((e=>{const{scheduler:r}=this;if(!r)return;t.peerId=this.peerId=e.id,this.minConns=e.min_conns,r.minConns=this.minConns;const s=e.peers;r.notifyPeersLoaded(s.length),s.length>this.gotSignalFails.limit&&(this.gotSignalFails.limit=s.length),t.netType=i.announceInfo.netType,(e.wifi_only||o)&&t.isMobileNet&&(r.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.15.8"),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((r=>{if(this.scheduler&&("TRACKER_EXPT"===r.code&&t.emitEvent(e.EXCEPTION,r),this.scheduler.notifyPeersLoaded(0),r.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 r=t.intermediator;this.signalerWs.connected||r&&this.DCMap.has(r)?(e.debug(`create DataChannel ${t.id} intermediator ${r}`),this._createDatachannel(t.id,!0,r)):e.info(`skip peer ${t.id} without intermediator`)}else e.info("no peers after filter")}_handleSendSignal(e,t){const r=e.remotePeerId;if(e.intermediator){const i=this.DCMap.get(e.intermediator);if(i){let s=!0;for(let e of t)i.sendMsgSignal(r,this.peerId,e)||(s=!1);if(s)return;this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,this.signalerWs.sendSignalBatch(r,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 r=e.to_peer_id||e.to,i=e.from_peer_id||e.from,s=e.action;if(r&&i&&s)if(r!==this.peerId){this.logger.info(`relay signal for ${i}`);const n=this.DCMap.get(r);if(n){if("signal"!==s)return void n.sendMsgSignalReject(r,i,e.reason,e.fatal);if(n.sendMsgSignal(r,i,e.data))return}t.sendMsgSignal(i,r)}else"signal"===s?this._handleSignalMsg(i,e,t.remotePeerId):this._handSignalRejected(i,e)})).on(e.DC_GET_PEERS,(()=>{const e=g(),r=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?15:22)&&!e.super));if(r&&r.length>0){const i=[];r.forEach((r=>{if(r.remotePeerId===t.remotePeerId||r.remotePeerId===this.peerId)return;if(!this.config.live&&(r.currentPos-t.currentPos>600||r.currentPos<t.currentPos))return;e-r.timeJoin>50&&i.push({id:r.remotePeerId,...r.region})})),this.logger.info(`send ${i.length} peers to ${t.remotePeerId}`),t.sendPeers(i)}})).on(e.DC_PEERS,(e=>{const r=e.peers;this.logger.info(`receive ${r.length} peers from ${t.remotePeerId}`),r&&r.length>0&&(r.forEach((e=>{e.intermediator=t.remotePeerId,e.region||(e.region={})})),this.requestPeersQueue.push(...r)),this.requestPeersWaitCount--,this.requestPeersWaitCount<=0&&this._handleRequestedPeers()})).once(e.DC_ERROR,((e,r)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${r}`),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 ${r}`),this._doSignalFusing(this.scheduler.peersNum),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:r,data:i})=>{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))),r&&e&&h&&(this.failedDCMap.set(o,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!e&&h&&!l&&this._tryBackupSignal(t,o,i))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:r}=this;t.isInitiator||r.handshakePeer(t),r.handleMetaData(t,e);const i=this.DCMap.size>=this.maxConnsActive;this.requestMorePeers(i),t.intermediator&&this.peersIncrement++,this._doSignalFusing(r.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,r,i,s){const n=(e,t)=>{let r=`${e}?id=${this.peerId}&p=web&v=2.15.8`;return this.config.signalCompact&&(r=`${r}&c=1`),t&&(r=`${r}&token=${t}`),r};let a,o=n(t,i);if(r&&r!==t){let e=n(r,s);a=new ht(this.logger,this.config,o,e)}else a=new lt(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this.engine.emitEvent("serverConnected",!0),this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let r=e.action;const i=e.from_peer_id||e.from;if(i)switch(r){case"signal":this._handleSignalMsg(i,e,null,t);break;case"reject":this._handSignalRejected(i,e);break;default:this.logger.warn(`Signal websocket unknown action ${r}`)}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,Fe(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const r=`signaling ${e} rejected`;this.logger.warn(`${r}, reason ${t.reason}`);const i=this.DCMap.get(e);i&&!i.connected&&(i.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,r),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,r,i="main"){return!(!(this.signalerWs.backupConnected&&e&&r.length>0&&"main"===i)||e.useBackupSignal)&&(e.useBackupSignal=!0,e.signalName="backup",e.intermediator=void 0,this.signalerWs.sendSignalBatch(t,r,"backup"),!0)}_handleSignalMsg(e,t,r,i){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"}`,r,i,!0);this._handleSignal(e,t.data,r,i)}else{const t=this.DCMap.get(e);if(!t)return;if(this._tryBackupSignal(t,e,t.signalMsgs,i))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(),r||this.notFoundDCSet.add(e)}}_handleSignal(e,t,r,i){let s=t;"string"==typeof s?s=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:Rt(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),r="O"===e[0];return{type:r?"offer":"answer",sdp:At(t,r)}})(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,r)}}else{if("answer"===n){const t=`${e} type wrong ${n}`;return a.warn(t),this._sendSignalReject(e,t,r,i),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,r,i)}o=this._createDatachannel(e,!1,r)}o&&(i&&(o.signalName=i),o.receiveSignal(s,t))}_createDatachannel(e,t,r){if(!this.fetcher)return;let i;if(t&&this.peerPool.available)i=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${i.signalMsgs.length}`),i.intermediator=r,i.assignPeerId(this.peerId,e);else{let s=this.config.trickleICE;this.overloaded&&(s=!1),i=new ee(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:r,trickle:!r&&s})}return this.DCMap.set(e,i),this._setupDC(i),i}_sendSignalReject(e,t,r,i,s){if(r){const i=this.DCMap.get(r);if(i&&i.sendMsgSignalReject(e,this.peerId,t,s))return}this.signalerWs.sendReject(e,t,s,i)}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this,r=this.scheduler.peersNum;r>=this.maxConnsActive||(t.info(`requestMorePeers after delay ${e}, peersIncrement ${this.peersIncrement}`),r<3||r<this.minConns&&this.peersIncrement<=3&&!this.gotPeersFromTracker?this._requestPeersFromServer(r):this._requestPeersFromPeers(r)||this._requestPeersFromServer(r),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 r=[],i=new Set;for(let t of e)i.has(t.id)||(i.add(t.id),r.push(t));const{asn:s,country:n}=t;if(!s||!n||r.length<2)return r;const a=r.filter((e=>!e.asn&&!e.country)),o=r.filter((e=>e.country===n&&e.asn!==s)),l=r.filter((e=>e.asn===s&&e.country===n)),h=r.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 r=this.DCMap.get(e);return!!r&&(r.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=g();for(let t of this.DCMap.values()){const r=e-t.timeJoin;e-t.timeJoin>30&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${r} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}}const It=wt;class Dt 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,r=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(r=this.makeChannelId(e,t));return{channelIdMaker:r,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:r,config:i}=this;if(self.indexedDB&&i.useDiskCache&&!i.live){const e=new De(this,i);try{await e.setupStore(),this.bufMgr=e}catch(e){r.warn(e),this.bufMgr=new Me(this,i)}}else this.bufMgr=new Me(this,i);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,(()=>{r.warn("SegmentStoreFatalError, switch to SegmentCache"),this.bufMgr.destroy(),this.bufMgr=new Me(this,i),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,r){const{logger:i,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()}})),r.live||this.media&&(r.pos=Math.round(this.media.currentTime)),r.tag=void 0===s.tag?this.generateTag():s.tag;let n=new it(this,s.token,encodeURIComponent(e),s.announce||"",r);this.fetcher=n,this.tracker=new It(this,n,t,s),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?ue:he)}_onHlsError(e,r){if(!r||!this.hlsjs)return;const{logger:i,tracker:s}=this;if(!i)return;const n=`${r.type} details ${r.details} reason ${r.reason}`;if(r.fatal?i.error(n):i.warn(n),"networkError"===r.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:a}=this.browserInfo,o=`${a||""} hlsjs ${this.hlsjsVersion} ${location.href}`,l=this.hlsjs.constructor.ErrorDetails;switch(r.details){case l.BUFFER_STALLED_ERROR:if("HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),s&&s.scheduler){const e=s.scheduler;i.warn(`buffered: ${1e3*e.getBufferedDuration()} fragLoading ${e.fragLoading} isCritical ${e.isCritical()}`)}break;case l.INTERNAL_EXCEPTION:if(r.event&&"demuxerWorker"!==r.event){r.error||(r.error={});const e=`${r.error.message} event ${r.event} ${o}`;this.fetcher&&r.fatal&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=e),i.error(`INTERNAL_EXCEPTION event ${r.event} err ${r.error.message}`),this.emitEvent(t.EXCEPTION,Fe(r.error,"HLSJS_EXPT")),i.report(e,r.event,this.peerId,"2.15.8")}break;default:if(r.fatal||r.details===l.FRAG_PARSING_ERROR){"mediaError"===r.type&&r.details!==l.BUFFER_APPEND_ERROR&&s&&s.scheduler&&s.scheduler.disconnectLoadingPeer().finally((()=>{s.scheduler.clearCache()}));const e=`${r.type} ${r.details} ${r.err||""} ${o}`;i.report(e,r.details,this.peerId,"2.15.8")}}}}class Ct{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 kt{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[kt.ElementaryStreamTypes.AUDIO]:!1,[kt.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 r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new Ct,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}}class Mt{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 xt=/^(\d+)x(\d+)$/,Ot=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class Nt{constructor(e){"string"==typeof e&&(e=Nt.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 r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}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=xt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,r={};for(Ot.lastIndex=0;null!==(t=Ot.exec(e));){let e=t[2],i='"';0===e.indexOf(i)&&e.lastIndexOf(i)===e.length-1&&(e=e.slice(1,-1)),r[t[1]]=e}return r}}const Ft=Nt,Bt={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 Ut=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Gt=/#EXT-X-MEDIA:(.*)/g,Ht=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),$t=/(?:(?:#(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?/,Wt=/\.(mp4|m4s|m4v|m4a)$/i;class Vt{static findGroup(e,t){if(!e)return null;let r=null;for(let i=0;i<e.length;i++){const s=e[i];s.id===t&&(r=s)}return r}static convertAVC1ToAVCOTI(e){let t,r=e.split(".");return r.length>2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let r,i=[];function s(e,t){["video","audio"].forEach((r=>{const i=e.filter((e=>function(e,t){const r=Bt[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)));if(i.length){const s=i.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${r}Codec`]=s.length>0?s[0]:i[0],e=e.filter((e=>-1===i.indexOf(e)))}})),t.unknownCodecs=e}for(Ut.lastIndex=0;null!=(r=Ut.exec(e));){const e={},n=e.attrs=new Ft(r[1]);e.url=Vt.resolve(r[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=Vt.convertAVC1ToAVCOTI(e.videoCodec)),i.push(e)}return i}static parseMasterPlaylistMedia(e,t,r,i=[]){let s,n=[],a=0;for(Gt.lastIndex=0;null!==(s=Gt.exec(e));){const e={},o=new Ft(s[1]);if(o.TYPE===r){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=r,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=Vt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),i.length){const t=Vt.findGroup(i,e.groupId);e.audioCodec=t?t.codec:i[0].codec}e.id=a++,n.push(e)}}return n}static parseLevelPlaylist(e,t){let r,i,s=0,n=0,a=new Mt(t),o=new Ct,l=0,h=null,u=new kt,d=null;for(Ht.lastIndex=0;null!==(r=Ht.exec(e));){const e=r[1];if(e){u.duration=parseFloat(e);const t=(" "+r[2]).slice(1);u.title=t||null,u.tagList.push(t?["INF",e,t]:["INF",e])}else if(r[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=(" "+r[3]).slice(1),qt(u,h),a.fragments.push(u),h=u,n+=u.duration,u=new kt}}else if(r[4]){if(u.rawByteRange=(" "+r[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(u.lastByteRangeEndOffset=e)}}else if(r[5])u.rawProgramDateTime=(" "+r[5]).slice(1),u.tagList.push(["PROGRAM-DATE-TIME",u.rawProgramDateTime]),null===d&&(d=a.fragments.length);else{for(r=r[0].match($t),i=1;i<r.length&&void 0===r[i];i++);const e=(" "+r[i+1]).slice(1),n=(" "+r[i+2]).slice(1);switch(r[i]){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 Ft(e),f=c.enumeratedString("METHOD"),g=c.URI,p=c.hexadecimalInteger("IV");f&&(o=new Ct,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 i=new Ft(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(i)&&(a.startTimeOffset=i);break;case"MAP":let h=new Ft(e);u.relurl=h.URI,u.rawByteRange=h.BYTERANGE,u.baseurl=t,u.sn="initSegment",a.initSegment=u,u=new kt,u.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${r}`)}}}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=>Wt.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),u=new kt,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 r=e[t];for(let i=t-1;i>=0;i--){const t=e[i];t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(a.fragments,d),a}}function qt(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 jt={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},zt=(e,t,r,i,s=!1)=>{const[n,a,o]=Kt(e,t,r,i);return s&&n.length>=1?w(n[0]):n.length>=2?[n[0],n[1]]:I(n,a,o)},Kt=(e,t,r,i)=>{const s=[],{COMPLETE:n,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=jt;return[n,a,o].forEach((n=>{s.push(Yt(e,n,t,r,i))})),s},Yt=(e,t,r,i,s)=>e.filter((e=>e.bitset.hasWithId(r,i,s,t)));class Xt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const r=Number(e);if(r<0)continue;const i=new Map;if(t[e])for(let r of t[e])i.set(r,{state:jt.COMPLETE,segId:void 0,size:void 0});this.levelMap.set(r,i)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,r,i=jt.ANY){if(t<0)return!1;const s=this._createOrGetSet(t).get(e);return!!s&&((!r||!s.segId||s.segId===r)&&(i===jt.ANY||s.state===i))}has(e,t,r=jt.ANY){return this.hasWithId(e,t,void 0,r)}hasCompleteOr(e,t,r=jt.COMPLETE){const i=this._createOrGetSet(t).get(e);return!!i&&(i.state===jt.COMPLETE||i.state===r)}getObj(e,t){let r=this._createOrGetSet(t).get(e);return r||(r={}),r}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,r,i,s){if("number"!=typeof(n=e)||n%1!=0)return;var n;this._createOrGetSet(t).set(e,{state:i,segId:r,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,r)=>{e[r]=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[r,i]of e)i.state===jt.COMPLETE&&t.push(r);return t}}class Qt{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 r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);1===t?r.delete(e):r.set(e,t-1)}}incre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);r.set(e,t+1)}else r.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 Jt=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 er extends(n()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Jt,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 r=g();this.getPeers().forEach((i=>{t>this.minConns+1&&(r-i.dataExchangeTs>120||r-i.gotStatsTs>=83)?(this.logger.warn(`close dead peer ${i.remotePeerId} level ${i.currentLevel}`),i.close(!1),t--):i.connected&&i.sendMsgStats(t,e)}))}),4e4)}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}requestPeers(){const e=g();let t=0;for(let r of this.getPeers())r.mobileNet||r.super||(e-r.gotPeersTS<60?this.logger.warn(`${r.remotePeerId} just got peers, ignored`):(r.sendPeersRequest(),r.gotPeersTS=e,t++));return t}chokePeerRequest(t){const r={event:e.DC_CHOKE};t?t.sendJson(r):this._broadcastToPeers(r)}unchokePeerRequest(t){const r={event:e.DC_UNCHOKE};t?t.sendJson(r):this._broadcastToPeers(r)}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 r=this.peerManager.getPeerIds();this._peersStats(r);const{asn:i,country:s}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${s||""} asn ${i||""}, now has ${r.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(),r=t.filter((e=>e.downloading));e.warn(`downloading: ${r.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of r)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:r,level:i})=>{this._broadcastLost(e,t,i),this.onBufferManagerLost(e,t,r,i)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,r,i,s){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:r||void 0,level:i},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:r}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),r.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{r.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 r of this.getPeers())t&&r===t||r.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;A(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(r=this.loadedPeerNum)?3:.5*r+1.67);var r;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const r=this.requestingMap.get(e);if(r)return void r.removeStreamListener(t);const i=this.segmentBuilderMap.get(e);i&&i.removeStreamListener(t)}setTargetPeersFromGroup(e,t,r,i){if(e.hasReversePeer){if((r=t.concat(r)).length>0)return this.targetPeers.forwardPeer=r[0],!0}else if(e.hasForwardPeer&&(i=t.concat(i)).length>0)return this.targetPeers.reversePeer=i[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=I(t,r,i),this.targetPeers.some((e=>!!e)))}}const tr=er;class rr 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 ir=0,sr=1,nr=2,ar=3;class or 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,r)=>{e+=`${r}: ${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 lr=/(\d+)-(\d+)\/(\d+)/;function hr(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class ur{constructor(e){this.fetchSetup=e.fetchSetup||dr,this.xhrSetup=e.xhrSetup,this.controller=new self.AbortController,this.stats=D(),this.packetSize=u,this.fakeXhr=new or}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,r){const i=this.stats;i.trequest=i.loading.start;let s=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal);const n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l=2e4}=t.loadPolicy||{},h=r.onUpdate,u=r.onBodyStart;this.context=e,this.config=t,this.callbacks=r,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),s=function(e,t){e.withCredentials&&(t.credentials="include");for(let[r,i]of e.headers)t.headers.set(r,i);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"),r.onTimeout&&r.onTimeout(i,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(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout&&r.onTimeout(i,e,this.response)}),l-(a-i.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new cr(t||"fetch, bad network response",e,s)}i.tfirst=i.loading.first=a,i.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=lr.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Number.isFinite(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(s.headers)||i.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"!==i.total?(u&&u(i.total,o),this.loadProgressively(s,i,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),i.tload=i.loading.end=Math.max(performance.now(),i.loading.first);const n=t[a];n&&(i.loaded=i.total=n);const o={url:s.url,data:t,code:s.status};r.onProgress&&r.onProgress(i,e,t,s),r.onSuccess&&r.onSuccess(o,i,e,s)})).catch((t=>{if(clearTimeout(this.requestTimeout),i.aborted)return;const s=t&&t.code||0,n=t?t.message:null;r.onError&&r.onError({code:s,text:n},e,t?t.details:null,i)}))}loadProgressively(e,t,r,i){const s=e.body.getReader();let n=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>s.read().then((({value:r,done:s})=>{const{fakeXhr:c}=this;if(c.readyState!==c.LOADING&&(c.readyState=c.LOADING,c.emit("readystatechange")),r&&(n+=r.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),i(e,!0)}else{const e=function(e,t){const r=e.byteLength-t,i=[];let s=t,n=Math.floor(r/u),o=r%u;for(let t=0;t<n;t++){const t=(0,a.h)(u);e.copy(t,0,s,s+u),i.push(t),s+=u}if(o>0){const t=(0,a.h)(o);e.copy(t,0,s,s+o),i.push(t)}return i}(l,o*this.packetSize);for(let t=0;t<e.length;t++)i(e[t],t===e.length-1)}const t=l.buffer,{fakeXhr:r}=this,{status:s,statusText:h,url:d}=e;return r.readyState=r.DONE,r.responseText=s,r.status=h,r.responseURL=d,r.responseType="arraybuffer",r.response=t,r.emit("readystatechange"),r._emitEvent("load"),r._emitEvent("loadend"),Promise.resolve(t)}if(t.loaded+=r.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,r]),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++,i(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function dr(e,t){return new self.Request(e.url,t)}class cr extends Error{constructor(e,t,r){super(e),this.code=t,this.details=r}}class fr extends(n()){constructor(e,t,r=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=r,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,r=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let i of r){const{handler:r}=i;r(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,r){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:r,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:r}=this.pieceMsg,i=i=>i.filter((i=>i.peerId!==e||(i.handler(t,r,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=i(this.forwardStreamListeners),this.reverseStreamListeners=i(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let r=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-r)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=r+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,r){return t?this.setReversePeer(e,r):this.setForwardPeer(e,r)}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:r,level:i}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(r,i,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(r,i,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 r=t===this.reversePeer?this.reverseEvents:this.forwardEvents;r&&r&&t.off(e.DC_PIECE_DATA,r.onPieceData).off(e.DC_PIECE,r.onPiece).off(e.DC_PIECE_NOT_FOUND,r.onPieceNotFound).off(e.DC_PIECE_ABORT,r.onPieceAbort)}_receivePacket(t,r,i,s=!0){const{seg_id:n,sn:o,level:l,size:h,ext:u}=this.pieceMsg,d=r-1;if(this.bufArr[d]?(this.logger.warn(`syn bufArr ${n} already has ${d} size ${i.byteLength}`),this.bufArr[d]=i):(s?this.p2pLoaded+=i.byteLength:this.httpLoaded+=i.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]=i,t?this.reverseOffset=d:this.forwardOffset=d,this._notifyStreamListeners(t,i,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 r=new X(o,n,t,this.getFromPeerId(),l,u);this.emit(e.SYN_OUTPUT,r,{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,ir),this._disconnectPeers()}}_disconnectPeers(){[this.forwardPeer,this.reversePeer].forEach((t=>{t&&t.emit(e.DC_ERROR,!0)}))}_checkPieceSize(e){const{size:t,seg_id:r,sn:i}=this.pieceMsg;return!e||!t||e===t||(this.logger.warn(`checkPieceSize ${r||i} size not match ${t} ${e}`),!1)}_setupPeer(t,r,i){const{logger:s}=this;0===this.timeStart&&(this.timeStart=performance.now()),i&&!this.pieceMsg.size&&(this.pieceMsg.size=i);const n=(r,i,n,a,o,l)=>{if(this.destroyed)return;if(!this._validateMsg(r,l.level,i))return void s.error(`onPieceData ${i||r} size ${n.byteLength} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(a<this.pieceMsg.attachments&&n.byteLength!==u)return s.error(`${i} dataSn ${a} size is ${n.byteLength}`),this.emit(e.SYN_ERROR,this.pieceMsg,ir),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:r,size:i,sn:n,level:a,seg_id:o,ext:l={}}=e;let h=!0;(i<=999||!this._validateMsg(n,a,o))&&(s.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),h=!1),this._checkPieceSize(i)||(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:i,attachments:r,ext:l},this.reverseOffset=r,this.bufArr=new Array(r),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};r?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,r=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:i,size:s,attachments:n}=this.pieceMsg;if(!s||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${i} url ${this.url}`),void this.emit(e.SYN_ERROR,this.pieceMsg,ir);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(r){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const r=e.currentLoadSpeed(),i=t.currentLoadSpeed();return r===i?e.timeSendRequest-t.timeSendRequest:r-i})).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,ar)}shouldWaitForRemain(e){return!this.isEmpty&&this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed,r=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${r}`),t>=r}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 r,i;return t.length<this.pieceMsg.attachments?(r=this.isFull?"WaitPartialDouble":"WaitPartialSingle",i=1):(r=this.isFull?"SynFullDouble":"SynFullSingle",i=0),{from:r,incompletes:i,bufferList:t}}_loadRemainBufferByHttp(){if(this.rangeRequesting||this.alreadyOutput)return;const{size:t,seg_id:r}=this.pieceMsg,{logger:i}=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;i.info(`listeners ${this.streamListeners} continue download ${r} from ${this.url} range: ${o.rangeStart}-${o.rangeEnd}`),this.hasPartialBuffer||(o={});const u=new ur({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,r,s)=>{if(!this.destroyed){if(s)return i.warn("httpLoader aborted"),void(this.alreadyOutput||this.emit(e.SYN_ERROR,this.pieceMsg,sr));if(r){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&&i.warn(`range request fileSize ${s}`),this.destroyed)return;const{size:n}=this.pieceMsg;if(c=t,t!==n||0!==s&&s!==n){let r=!1;s>0&&s!==n?(i.error(`onBodyStart fileSize ${s} != ${n}`),r=!0):t!==l&&(i.error(`onBodyStart size ${t} != expectedSize ${l}`),r=!0),r&&this.emit(e.SYN_ERROR,this.pieceMsg,sr)}else i.warn(`syn range request ${r} resp whole ts`),g=0},onError:t=>{this.destroyed||(i.error(`httpLoader error ${t.text}`),this.emit(e.SYN_ERROR,this.pieceMsg,sr))},onTimeout:()=>{this.destroyed||(i.warn("httpLoader timeout"),this.emit(e.SYN_ERROR,this.pieceMsg,nr))}};u.load(d,{timeout:15e3},p)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class gr extends fr{constructor(e,r,i,s,n,a=!1,o){super(e,r,a,o),this.pieceMsg={event:t.DC_PIECE,sn:i,level:s,seg_id:n},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,r){const{sn:i,seg_id:s,attachments:n}=this.pieceMsg,a=e&&0===r||!e&&r===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:r}=e;r(i,s,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,r){return(!this.pieceMsg.seg_id||r===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}}class pr{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,r,i,s){if(this.meanHttpSpeed<=0)return!1;if(r>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*s>=e)return!1;return((s+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-r)*r<i}_cal(e,t){return.4*e+.6*t}}class mr extends tr{constructor(e,t){super(e,t),this.prefetchOnly=t.prefetchOnly,this.bitset=new Xt(t.live||!1),this.bitCounts=new Qt,this.requestingMap=new rr,this.segmentBuilderMap=new rr,this.allowP2pLimit=t.httpLoadTime+1.5,this.playlistInfo=new Map,this.gotPlaylist=!1,this.targetPeers={},this.sequential=!0,this.coordinator=new pr,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:r}=this.engine.fetcher.announceInfo;e.sendMetaData(this.bitset.allArray(),!0,this.peersNum,{asn:t,country:r},this.isMobileNet)}_receiveDCHave(e,t,r,i){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:r,level:i,complete:s,seg_id:n,size:a}=t,o=s?jt.COMPLETE:jt.PARTIAL_FORWARD;e.bitset.add(r,i,n,o,a),this._receiveDCHave(r,i,n,e),e.isAvailableUrgently&&this._handleDCHave(e,r,i,n,a,o)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:r,level:i,seg_id:s,size:n}=t;e.bitset.hasCompleteOr(r,i,jt.PARTIAL_REVERSE)||e.bitset.add(r,i,s,jt.PARTIAL_REVERSE,n),this._receiveDCHave(r,i,s,e),e.isAvailableUrgently&&this._handleDCHave(e,r,i,s,n,jt.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:r,level:i}=t;e.bitset.has(r,i)&&(e.bitset.delete(r,i),this.bitCounts.decre(r,i))})).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?jt.PARTIAL_REVERSE:jt.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:r,level:i}=t,s=de(r,i);this.removeStreamListener(s,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:r,level:i}=t;e.bitset.delete(r,i),this.bitCounts.decre(r,i),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:r}=this,{sn:i,level:s,reverse:n}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(i));const o=()=>{this.bitset.delete(i,s),e.sendPieceNotFound(i,a,{level:s}),this._broadcastLost(i,a,s,e)},l=await this.bufMgr.getSegById(a),h=de(i,s),u=this.requestingMap.get(h);let d=!1;u&&u.isDownloading&&(d=!0);const c=this.segmentBuilderMap.get(h);if(l)if(r.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)r.info(`peer request ${i} wait from builder, sent ${c.bufferList.length}`),P(e,c,c.pieceMsg,c.bufferList,c.source,1);else if(d){r.info(`syn had ${u.loadedPackets} packets, wait remain from upstream ${u.getFromPeerId()}`);const t={...u.pieceMsg,reverse:n},{from:i,incompletes:s,bufferList:a}=u.getStreamInfo(n);P(e,u,t,a,i,s)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new Xt(this.config.live,t.field);for(let e in t.field){const r=Number(e);if(r<0)continue;t.field[r].forEach((e=>{this.bitset.has(e,r)||this.bitCounts.incre(e,r)}))}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 r=Number(e),i=t[r];i&&i.forEach((e=>{this.bitCounts.decre(e,r)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,r,i){const{logger:s,config:n}=this;let a=1e3*(i-n.httpLoadTime);this.allowP2pLimit=n.httpLoadTime+1.5,s.info(`bufferedDuration ${1e3*i} 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!==r)return s.warn(`syn segId ${n} not match ${r}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,r,i);if(!l.shouldWaitForRemain(a)){if(s.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const i=this.peerManager.getPeersOrderByWeight();let[n,o,h]=Kt(i,e,t,r);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,r,i)}_searchAvailablePeers(e,t,r,i){if(i<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const s=this.peerManager.getPeersOrderByWeight(),[n,a]=zt(s,e,t,r);return this.targetPeers={forwardPeer:n,reversePeer:a},[n,a].some((e=>!!e))}reportTraffic(e,t,r){const{fetcher:i}=this.engine;i&&(e>0&&i.reportFlow(e),t>0&&i.reportDCTraffic(t,r))}notifyAllPeers(e,t,r,i,s=jt.COMPLETE){if(!r)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,r)=>`${e}-${t}-${r}`)(e,t,s);let o;s!==jt.PARTIAL_REVERSE&&(o=s===jt.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,r,{level:t,reverse:s===jt.PARTIAL_REVERSE,complete:o,size:i}),h.notifySet.add(a),n&&T(h.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:r}=this;if(!this.hasPeers)return;const i=t.live;if(this.fragLoading)return void e.info("loading urgently, skip prefetch");const{currentLevel:s}=r;if(0===this.bitCounts.size(s))return;if(!i&&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(!i){const t=this.requestingMap.size,r=this.requestingMap.activePeers;if(r>=o)return void e.warn(`requestingMap size ${t} activePeers ${r}`);o-=r}if(this.getBufferedDuration()<this.allowP2pLimit){if(!i)return;o=1}let u=0,d=this.loadingSN+1;if(this.prefetchOnly&&(d+=2),!i)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&&(i||!(d>l))&&!(i&&d>this.loadingSN+2);){if(this.bitset.has(d,s)){d++;continue}const t=de(d,s),r=this.requestingMap.get(t);if(this.bitCounts.has(d,s)){if(r){for(let e of n)if(e.bitset.has(d,s)){const{state:t,segId:i,size:n}=e.bitset.getObj(d,s);if(this._trySetPeerForSyn(r,e,i,d,s,n,t))break}}else{let r=[null,null];if(i)r=zt(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 i;i=t===jt.COMPLETE?0===p(0,1):t===jt.PARTIAL_REVERSE,r[i?1:0]=e;break}if(r.some((e=>!!e))){const i=new gr(this.coordinator,this.logger,d,s,void 0,this.httpRangeSupported);this._setupSynthesizer(i),this.requestingMap.set(t,i),r.forEach(((t,r)=>{if(t&&a<o){const n=1===r,o=t.bitset.getSize(d,s);i.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,r,i){this.currLostSN=e,r&&(this.nextLostSN=r),this.bitset.delete(e,i),this.bitCounts.delete(e,i)}onBufferManagerSegAdded(e){const{sn:t,segId:r,level:i,size:s}=e;this.notifyAllPeers(t,i,r,s),this.updateLoaded(t,i,r)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[r,i]of this.requestingMap.internalMap){const s=r.split("-"),n=Number(s[1]),a=Number(s[0]);i.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),i.deletePeer(t),this.bitCounts.decre(n,a),t.bitset.delete(n,a))}}updateLoaded(e,t,r){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,r,jt.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 r=function(e){const t=e.split("\n");let r=0,i=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){r=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&i++;return r+i-1}(t);if(!this.isMobileNet)for(let i of this.getPeers())i.sendMsgPlaylist(e,t,r);this.playlistInfo.set(e,{seq:r,data:t})}async getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t,data:r}=this.playlistInfo.get(e),i=()=>{for(let r of this.getPeers()){const i=r.getLatestPlaylist(e,t);if(i)return this.playlistInfo.set(e,i),this.gotPlaylist=!0,i}return null};let s=i();return!s&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await m(240),this.gotPlaylist=!1,s=i()),s}getBufferedDuration(){const{config:e}=this;let{media:t,currentSrc:r}=this.engine;if(!t||t.src!==r&&0===t.currentTime){if(this.logger.info("try get video element"),t=ae(this.config.mediaElem,r),!t)return 4;this.engine.media=t}let i=function(e){let t=0,r=e.currentTime,i=e.buffered;for(let e=i.length-1;e>=0;e--)if(r>=i.start(e)&&r<=i.end(e)){t=i.end(e)-r;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return i}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,r,i,s,n){if(this.logger.info(`syn output ${e} http ${t} p2p ${r} time ${i}`),!this.config.validateSegment(e,new Uint8Array(s)))return!1;if(n){const t=await C(s);if(t&&t!==n)return this.logger.warn(`${e} computedHash ${t} != hash ${n}`),!1}return!0}_handleSynError(e,t,r,i){const{logger:s,config:n}=this;s.warn(`SYN_ERROR ${t}-${r} code ${i}`),i!==ir&&e.hasPartialBuffer&&r>this.loadingSN?s.warn(`syn abort ${r} with partial buffer`):this.requestingMap.delete(de(r,t)),n.live&&this.checkPeers()}_notifySynthesizer(e,t,r,i,s,n,a=!0){const o=this.requestingMap.get(de(r,i));o&&this._trySetPeerForSyn(o,e,t,r,i,s,n,a)}_trySetPeerForSyn(e,t,r,i,s,n,a,o=!1){const{logger:l}=this,h=e.segId;if(r&&h&&r!==h)return l.warn(`notifySynthesizer segId ${r} 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(r,i,!0,{level:s,reverse:e}):t.requestDataBySN(i,!1,{level:s,reverse:e})}function d(){return a===jt.PARTIAL_FORWARD||a===jt.COMPLETE}function c(){return a===jt.PARTIAL_REVERSE||a===jt.COMPLETE}return!1}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:r}=this.config;t||r||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,r={level:e};if(t&&!this.config.live){const{currentTime:e}=t;r.pos=Math.round(e)}return r}checkSynthesizer(e,t){const r=de(e,t),i=this.requestingMap.get(r);i&&(0===i.streamListeners?(this.logger.info(`destroy syn ${r} without listeners`),this.requestingMap.delete(r)):this.logger.info(`keep syn ${r} with listeners`))}setupSynForLoad(e,t,r,i,s){const{forwardPeer:n,reversePeer:a}=this.targetPeers,o=de(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(i):(l=new gr(this.coordinator,this.logger,e,t,r,this.httpRangeSupported,i),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(r,e,!0,{level:t}),a&&l.setReversePeer(a)&&a.requestDataById(r,e,!0,{level:t,reverse:!0})),l.setTimeout(l.isEmpty?0:s,!0)}async disconnectLoadingPeer(e){let t=e;if(!t){const e=await this.bufMgr.getSegById(this.loadingSegId);e&&e.fromPeerId&&(t=e.fromPeerId)}t&&(this.logger.warn(`disconnect loading peer ${t}`),t.split(":").forEach((e=>{const t=this.peerManager.getPeer(e);t&&t.close(!0)})))}}class vr{constructor(t,r,i,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:i,sn:t,level:r,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,r){this.streamListeners.push({handler:r,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:r}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((i=>i.peerId!==e||(i.handler(t,r,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let r of this.streamListeners){const{handler:i}=r;i(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:r}=this.pieceMsg;for(let i of this.streamListeners){const{handler:s}=i;s(t,r,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const yr=/^age:\s*[\d.]+\s*$/im;function Er(e,t,r,i){if(!e)return!1;const s=i&&i.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(s)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,n):n}const Sr=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,r){this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===r&&!this.stats.aborted)return s(r,t.url)})).catch((e=>{if(this.loader===r&&!this.stats.aborted)return r.open("GET",t.url,!0),s(r,t.url)})).then((()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)})).catch((e=>{this.callbacks.onError({code:r.status,text:e.message},t,r,i)})):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=r.loadPolicy;if(i)for(const t in i)e.setRequestHeader(t,i[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),r.timeout=s&&Number.isFinite(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const i=t.readyState,s=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.tfirst=r.loading.first=Math.max(self.performance.now(),r.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-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const i=t.status,n="text"===t.responseType?t.responseText:null;if(i>=200&&i<300){const s=n||t.response;if(null!=s){r.tload=r.loading.end=Math.max(self.performance.now(),r.loading.first);const n="arraybuffer"===t.responseType?s.byteLength:s.length;if(r.loaded=r.total=n,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(r,e,s,t),!this.callbacks)return;const o={url:t.responseURL,data:s,code:i};return void this.callbacks.onSuccess(o,r,e,t)}}const a=s.loadPolicy.errorRetry;Er(a,r.retry,!1,{url:e.url,data:void 0,code:i})?this.retry(a):this.callbacks.onError({code:i,text:t.statusText},e,t,r)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Er(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:r}=this;this.retryDelay=function(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}(e,r.retry),r.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&&yr.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 Tr=class extends mr{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=A(t.segmentBypass)?t.segmentBypass:()=>!1,!0===t.httpStreamEnabled?this.streamEnabled=hr():this.streamEnabled=!1}async handleGetMediaData(e,r){const{logger:i,engine:s,config:n}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return i.warn(`cannot get frag ${a}`),r.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 i.info(`bypass frag ${a}`),r.postMessage({action:t.SW_GET_MEDIA});if(s.segmentLoadCount<n.startFromSegmentOffset)return this._loadFragByHttp(l,r,d,a,o,1e3*this.fragloadTimeout,!1);const c=d===this.loadingSegId;if(c&&(i.warn(`duplicate request ${d}`),this.prefetchOnly))return r.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,i.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(),r.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:f.data}});if(this.fragLoading=!0,this.prefetchOnly)return i.info(`prefetchOnly, skip p2p load ${d}`),this._loadFragByHttp(l,r,d,a,o,1e3*this.fragloadTimeout);let g=this.getBufferedDuration();g>this.fragloadTimeout&&(g=this.fragloadTimeout),i.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const m=de(h,u);if(this.resolveMap.has(h)||c){let e=this.requestingMap.get(m);if(e||c){e&&this.httpRangeSupported&&(i.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let s=setTimeout((()=>{i.info(`notify seg ${h} timeout`),s=-1,r.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{s<0||e&&e.level===u&&(clearTimeout(s),i.info(`notify seg ${e.sn}`),r.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else i.warn(`${h} is requesting, fallback`),r.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,u,d,g)){await this._loadFragByP2p(l,r,h,d,a,u,o,p)||(i.warn(`p2p timeout switch to http load ${d}`),this._loadFragByHttp(l,r,d,a,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,r,d,a,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,r,i,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 ur(g):new Sr(g);let m={url:c,responseType:"arraybuffer",...L(n)};const v={timeout:a,loadPolicy:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4}},E={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,r.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,r.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 ${i} time ${h} speed ${o.byteLength/h}`),!await this.bufMgr.hasSegOfId(i)){const e=y(o).buffer,t=new X(l,i,e,"",u);await this.bufMgr.putSeg(t),this.reportTraffic(o.byteLength,0,0)}this.segmentBuilderMap.delete(d),e.segId=i,e.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:s,sn:l,level:u,segId:i,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(),r.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,i,t,jt.PARTIAL_FORWARD),e=new vr(l,u,i,t),this.segmentBuilderMap.has(d)||this.segmentBuilderMap.set(d,e))},E.onUpdate=(t,r,s)=>{if(s)return this.logger.warn(`loadFragByHttp ${i} aborted`),void this.segmentBuilderMap.delete(d);e&&e.receiveBytes(t,r)}}p.load(m,v,E)}async _loadFragByP2p(e,r,i,s,n,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${i} segId ${s} level ${a}`);const u=await this.load(i,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(i,s,o,l,a,u.ext);h.info(`bufMgr putSeg ${i} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:n,sn:i,level:a,segId:s,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(),r.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 ${i} segId ${s}`),r.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:d.data}}),!0)}notifySWMessage(e,r,i){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(r,i);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,r,i,s,n){const{logger:a,config:o}=this;let l={...L(s),proxied:!0,url:i,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,r,t,l,n);const h=new Promise((i=>{const s={resolve:i,sn:e,level:r,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,r)=>{const{config:i,logger:s}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:u,time:d,http:c,p2p:f}=r,g=this.resolveMap.has(a);g&&(this.fragLoading=!1);const p=await this._handleSynOutput(n,c,f,d,o,h.hash),m=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?m: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(m)}})).on(t.SYN_ERROR,((t,r)=>{const{sn:i,level:s}=t;if(this.resolveMap.has(i)){const e=this.resolveMap.get(i);this.resolveMap.delete(i),e.resolve()}this._handleSynError(e,s,i,r)}))}_handleDCHave(e,t,r,i,s,n){this._notifySynthesizer(e,i,t,r,s,n,this.resolveMap.has(t)),this.config.live&&q((()=>{this.checkPeers()}))}},_r="2.13.0";class Lr extends Dt{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},r=null){super(e,r),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=Lr.name,Lr.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),r&&(r.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),r.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:i,signalId:s,browserInfo:n}=this.setup();if(this.onLevelLoaded=e=>{const{config:r}=this,a=e.live;r.live=a,this.segmentLoadCount=0,this.targetDuration=e.averagetargetduration,this.browserInfo={...n,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${i(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||(r.startSN=e.startSN,r.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:r,startSN:i}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,r,i)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,r)=>{this.multiBitrate=e.length>1,this.currentSrc=r,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:r,data:i}=e.data;if(!r)return;if(r===t.SW_DEBUG){const{level:e,text:t}=i;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 ${r}`),s.postMessage({action:r,pong:!0}),!this.p2pEnabled||!i)return s.postMessage({action:r});if(r===t.SW_GET_PLAYLIST)this.handleGetPlaylist(i,s);else{if(!this.scheduler)return s.postMessage({action:r});this.scheduler.notifySWMessage(r,i,s)}}else this.logger&&this.logger.error(`sender not found in action ${r}`)}}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 r=null;const i=()=>{r||(r=setTimeout((()=>{t()}),2500))},s=()=>{null!=r&&(clearTimeout(r),r=null)};return e.addEventListener("waiting",i),e.addEventListener("playing",s),()=>{e.removeEventListener("waiting",i),e.removeEventListener("playing",s)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,r,i=!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 r=e.split("."),i=t.split("."),s=0;s<Math.max(r.length,i.length);s++){var n=parseInt(r[s]||0),a=parseInt(i[s]||0);if(n<a)return-1;if(n>a)return 1}return 0}(u,_r)?(console.warn(`hls-proxy.js version should >= ${_r}`),r.postMessage({action:t.SW_GET_PLAYLIST})):this.bypassLevels.indexOf(b(a))>=0?(console.warn("bypass audio track"),n&&n.warn("bypass audio track"),r.postMessage({action:t.SW_GET_PLAYLIST})):(r.postMessage({action:t.SW_GET_PLAYLIST,data:{active:!0,debug:n&&n.isDebugLevel,text:l,redirectedUrl:o}}),this._parsePlaylist(l,b(a),o,i),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!s.live&&t()){const r=new URL(e.scope);this.pathname=r.pathname+h;const i=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;n&&(n.error(t),n.report(t,"SWKeepAlive",this.peerId,"2.15.8"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,r)=>{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=>{r(e)}))}))).catch((e=>{i(e)})):i("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,r,i,s=!1){const n=r;i&&(r=i);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let i=0;const o=Vt.parseLevelPlaylist(e,r);this.levels.length>0?(i=this.levels.indexOf(b(o.url)),-1===i?(this.restartP2p(),this.currentSrc=n,i=0):this.currentLevelIndex=i):(""!==this.currentSrc&&n!==this.currentSrc&&this.restartP2p(),this.currentSrc=n,this.levels=[b(r)]),this.emit(t.LEVEL_LOADED,o),a.live&&S(this.fragMap,200),o.fragments.forEach((e=>{e.level=i;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const r=e.byteRange;2===r.length&&(t=`${t}|bytes=${r[0]}-${r[1]-1}`),this.fragMap.set(t,e)})),!s&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(b(r),e)}else{const i=Vt.parseMasterPlaylist(e,r);""!==this.currentSrc&&this.restartP2p(),i.length>0&&(i.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=i.map((e=>b(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{Vt.parseMasterPlaylistMedia(e,r,t).forEach((e=>{e.url&&this.bypassLevels.push(b(e.url))}))}))),this.emit(t.MANIFEST_PARSED,i,n)}this._setupSegmentId()}async handleGetPlaylist(e,r){const{config:i,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:i,seq:n}=t;return s&&s.info(`got playlist from peer seq ${n}`),void this.handlePlaylist({text:i,...e},r,!0)}}try{const{text:i,redirectedUrl:n}=await this._loadPlaylistByHttp(a);if(!function(e){return 0===e.indexOf("#EXTM3U")}(i))return s&&s.warn(`not m3u8: ${i}`),r.postMessage({action:t.SW_GET_PLAYLIST});this.handlePlaylist({text:i,redirectedUrl:n,...e},r)}catch(e){r.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"),Cr.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,r)=>{const{serviceWorker:i}=navigator;i||r(e),i.getRegistration().then((i=>{i?i.unregister().then(t).catch(r):r(e)}))}))}async _init(e,t){const{logger:r,config:i}=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(i.mediaElem)}),3e3);let s=new Tr(this,i);s.fragMap=this.fragMap;try{await super._init(e,s,t)}catch(e){return void(r&&r.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 It&&(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),r=await fetch(t);return{text:await r.text(),redirectedUrl:r.redirected?r.url:void 0}}}const br=Lr;function Rr(e,t,r="main"){return"main"!==r}function Ar(e,t,r){let i,s,n;const a=performance.now();n=a,s=r?n-r.getMeanTimeToLoaded(t):a-200,i=s-100,e.trequest=i,e.tfirst=s,e.tload=n,e.loading={first:i,start:s,end:n},e.loaded=t,e.total=t}const Pr=class extends mr{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,r){const{logger:i,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=r,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,r)=>{const{config:i,logger:s}=this,{segId:n,sn:a,data:o,level:l,ext:h}=t,{speed:u,time:d,http:c,p2p:f}=r,g=this.criticalSeg&&this.criticalSeg.segId===n,p=await this._handleSynOutput(n,c,f,d,o,h.hash),m=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=m,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(m)})).on(t.SYN_ERROR,((t,r)=>{const{sn:i,level:s}=t;this.criticalSeg&&this.criticalSeg.sn===i&&(this.criticalSeg=null,this.callbacks.onTimeout({},this.context,null)),this._handleSynError(e,s,i,r)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:r,segId:i})=>{this.criticalSeg&&this.criticalSeg.segId===i&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:r},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:r,level:i})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,r&&this.checkSynthesizer(e,i)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:r,level:i})=>{this.fragLoading=!1,r||this.checkSynthesizer(e,i)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,r,i,s,n){this._notifySynthesizer(e,i,t,r,s,n,this.criticalSeg&&this.criticalSeg.segId===i),this.config.live&&q((()=>{this.checkPeers()}))}};class wr extends Dt{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=wr.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:r,signalId:i,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,r,i,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:r}=this,{fragments:i,averagetargetduration:s,startSN:n}=t.details;r.httpLoadTime=this.determineHttpLoadTime(i,s,n)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,r)=>{this._setupSegmentId();const i=r.levels.length;this.multiBitrate=i>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,r,i,s,n={}){const{config:a}=this;a.live=t,this.browserInfo={...r,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${i(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:r,config:i}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const s=new Pr(this,i);try{await super._init(e,s,t)}catch(e){return void r.error(e)}this.hlsjs.config.fLoader=function(e,t,r,i){const s=i.httpStreamEnabled&&hr();return class extends(n()){constructor(n){super(),this.logger=r,this.isHlsV0=i.isHlsV0,this.bufMgr=e.bufMgr,this.httpLoader=s||this.isHlsV0?new ur(n):new Sr(n),this.originalLoader=n.loader,this.p2pEnabled=i.p2pEnabled,this.isLive=i.live,this.scheduler=e,this.fetcher=t,this.segmentId=i.segmentId,this.blockTypes=i.p2pBlackList,this.stats=this.httpLoader.stats||D(),this.enableWorker=n.enableWorker,this.segmentBypass=A(i.segmentBypass)?i.segmentBypass:()=>!1,this.prefetchOnly=i.prefetchOnly,this.startFromSegmentOffset=i.startFromSegmentOffset}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,r){const{logger:i,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,r));if(!n||!Number.isInteger(l)||Rr(0,this.blockTypes,h)||this.segmentBypass(n,u))return i.info(`HTTP load blockType ${n}`),c();if(this.fetcher.increMediaRequests(),this.isLive&&s.requestedSet.has(d))return i.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){i.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 Ar(this.stats,g.size,s.coordinator),a.loaded=g.size,a.loadByP2P=!0,a.fromPeerId=g.fromPeerId,void q((()=>{!this.isHlsV0&&r.onProgress&&r.onProgress(this.stats,e,n.data),r.onSuccess(n,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&s.hasAndSetTargetPeer(l,o,d,f)?this.loadFragByP2p(e,t,r,d,f):(i.info(`fragLoader load ${d} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,r,d))}loadFragByHttp(e,t,r,i){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;r.onUpdate=(t,r,s)=>{if(s)return n.warn(`loadFragByHttp ${i} aborted`),void o.delete(d);e&&e.receiveBytes(t,r)},r.onBodyStart=t=>{!e&&t>0&&(e=new vr(h,u,i,t),o.has(d)||o.set(d,e),a.notifyAllPeers(h,u,i,t,jt.PARTIAL_FORWARD))}}const c=r.onSuccess;r.onSuccess=async(e,t,r)=>{a.coordinator.addLoaderHttpSpeed(t.tload-t.tfirst,t.loaded);const{data:s}=e;let l=t.tload-t.trequest;if(n.info(`HTTP loaded ${i} time ${l} speed ${t.total/l}`),!await this.bufMgr.hasSegOfId(i)){const e=y(s).buffer,t=new X(h,i,e,this.fetcher.peerId,u);await this.bufMgr.putSeg(t)}o.delete(d),this.fetcher.reportFlow(t.total),c(e,t,r)};const f=r.onProgress;f&&(r.onProgress=(e,t,r)=>{l.loaded=e.total,f(e,t,r&&this.enableWorker?y(r).buffer:r)}),e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,r)}loadFragByP2p(t,r,i,s,n){const{logger:a}=this,o=t.frag;let l;l=r.loadPolicy?r.loadPolicy.maxTimeToFirstByteMs:r.timeout,(!l||l>1e3*n)&&(l=1e3*n),t.defaultTimeout=l,this.scheduler.load(t,r,i);const h=i.onSuccess,u=i.onTimeout;i.onTimeout=(e,t)=>{a.warn(`P2P timeout switched to HTTP load ${o.relurl} at ${o.sn}`),i.onSuccess=h,this.loadFragByHttp(t,r,i,s),i.onTimeout=u},i.onSuccess=async(t,r,n)=>{const{data:l}=t;if(Ar(r=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(r.total),o.loaded=r.loaded,a.info(`${o.loadByP2P?"P2P":"HTTP"} loaded segment id ${s}`),!this.isHlsV0&&i.onProgress&&i.onProgress(r,n,l),h(t,r,n)}}}}(s,this.fetcher,r,i),i.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,r){return class extends(n()){constructor(i){super(),this.logger=t,this.xhrLoader=new i.loader(i),this.p2pEnabled=r.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||D()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,r){const{logger:i}=this,{url:s}=e,n=b(s),a=r.onSuccess;if(r.onSuccess=(e,t,r)=>{this.scheduler&&!r.loadedByPeer&&this.scheduler.broadcastPlaylist(n,e.data),a(e,t,r)},this.scheduler&&this.scheduler.playlistInfo.has(n)){const t=await this.scheduler.getPlaylistFromPeer(n);if(t&&t.data){const{data:n,seq:a}=t;i.info(`got playlist from peer seq ${a}`),Ar(this.stats,n.length);let o={url:s,data:n};return e.loadedByPeer=!0,void q((()=>{r.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,r)}}}(s,r,i))}_onFragLoading(e,r){const i=r.frag;let{sn:s,level:n,segId:a}=i;if(!Rr(i.url,this.config.p2pBlackList,i.type)&&Number.isInteger(s)){if(this.logger&&this.logger.info("loading frag "+s),this.bufMgr&&(this.bufMgr.loadingSN=s),!a){let e;i._byteRange&&(e="bytes="+i._byteRange[0]+"-"+i._byteRange[1]);let t=i.url;this._setupSegmentId(),a=i.segId=this.config.segmentId(String(n),i.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:s,segId:a,byHttp:i.loadByHTTP,level:n})}}_onLevelUpdated(e,t){const{details:r}=t,{hlsjs:i,config:s}=this,{targetduration:n,live:a,fragments:o}=r,l=o.length;if(a&&i&&"main"===o[0].type&&!(l<=4)&&(s.isHlsV0||!i.userConfig.liveSyncDuration&&!i.userConfig.liveSyncDurationCount)){const e=l<=9?l-1:l-2;i.config.liveSyncDurationCount!==e&&(i.config.liveSyncDurationCount=e)}}_onFragLoaded(e,r){if(this.segmentLoadCount++,!this.p2pEnabled)return;const{frag:i}=r;this.curTsUri=i.url;const{sn:s,segId:n,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:u,url:d}=i,{config:c,logger:f}=this;this.tracker&&this.tracker.scheduler&&(T(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(n)),Rr(i.url,c.p2pBlackList,i.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,r){const{frag:i}=r;if(!Rr(i.url,this.config.p2pBlackList,i.type)){this.logger&&this.logger.info("frag changed: "+i.sn);const{sn:e,duration:r}=i;this.emit(t.FRAG_CHANGED,{sn:e,duration:r})}}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 r=e?"off":"on";t[r](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[r](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[r](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[r](this.HLSEvents.ERROR,this._onHlsError),t[r](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,r=e.ports[0];if(r)return r.postMessage({action:t,pong:!0}),r.postMessage({action:t,data:{bypass:!0}})}}}const Ir=wr;class Dr{static get Events(){return t}static get TrackerZone(){return se.TrackerZone}static isSupported(){return se.isSupported()&&(ne()||br.isServiceWorkerSupported())}static isServiceWorkerSupported(){return br.isServiceWorkerSupported()}static isMSESupported(){return ne()}static getBrowser(){return J().getBrowser()}static get ServiceWorkerEngine(){return br}static get HlsjsEngine(){return Ir}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return Dr.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:r}={}){const{serviceWorker:i}=navigator;return!i||r?Promise.resolve():i.getRegistration().then((r=>r||Promise.race([i.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,r)=>{const i=e.installing||e.waiting||e.active,s=()=>"activated"===i.state&&(i.removeEventListener("statechange",s),t(e),!0);s()||i.addEventListener("statechange",s)}))}(e))).catch((()=>{Promise.resolve()})),m(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const r=()=>{this._realEngine=new Ir(t,e)},i=()=>{this._realEngine=new br(e,t)};"1"!==c("_sw")?e.proxyFirst&&t?br.isServiceWorkerSupported()?i():r():!e.proxyOnly&&ne()&&t?r():i():i()}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 A(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return A(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return se.version}}Dr.version=se.version,Dr.protocolVersion=ee.VERSION,"object"==typeof self&&(self.P2PEngineHls=Dr);const Cr=Dr;var kr=r(917),Mr=r.n(kr);const xr={maxBufferLength:12},Or={maxBufferLength:40};class Nr extends(Mr()){static get P2PEvents(){return Cr.Events}static get P2pEngine(){return Cr}constructor(e={}){let t=e.p2pConfig||{};const r=!1===t.live?Or:xr;let i=JSON.parse(JSON.stringify(r));i.maxBufferSize=0,i.enableWorker=!1;for(let t in e)"p2pConfig"!==t&&(i[t]=e[t]);super(i),this._restartEvent=()=>{this.restartP2P()},Cr.isSupported()&&(this._p2pEngine=new Cr({...t,hlsjsInstance:this}),this._p2pEngine.on(Cr.Events.RESTART_P2P,this._restartEvent)),this.on(Mr().Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(Cr.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(Cr.Events.RESTART_P2P,this._restartEvent))}}Nr.engineVersion=Cr.version,Nr.protocolVersion=Cr.protocolVersion,Nr.WEBRTC_SUPPORT=Cr.isSupported();const Fr=Nr})(),i=i.default})()));