@swarmcloud/hls 2.14.3 → 2.14.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/hls.min.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(this,(()=>(()=>{var e={415:e=>{"use strict";var t,i="object"==typeof Reflect?Reflect:null,r=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(i,r){function n(i){e.removeListener(t,s),r(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),i([].slice.call(arguments))}p(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&p(e,"error",t,i)}(e,n,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.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?s.defaultMaxListeners:e._maxListeners}function h(e,t,i,r){var n,s,a,h;if(o(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]),void 0===a)a=s[t]=i,++e._eventsCount;else if("function"==typeof a?a=s[t]=r?[i,a]:[a,i]:r?a.unshift(i):a.push(i),(n=l(e))>0&&a.length>n&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,h=u,console&&console.warn&&console.warn(h)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=u.bind(r);return n.listener=i,r.wrapFn=n,n}function c(e,t,i){var r=e._events;if(void 0===r)return[];var n=r[t];return void 0===n?[]:"function"==typeof n?i?[n.listener||n]:[n]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(n):g(n,n.length)}function f(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function g(e,t){for(var i=new Array(t),r=0;r<t;++r)i[r]=e[r];return i}function p(e,t,i,r){if("function"==typeof e.on)r.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function n(s){r.once&&e.removeEventListener(t,n),i(s)}))}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),s.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},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(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},s.prototype.getMaxListeners=function(){return l(this)},s.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){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=s[e];if(void 0===l)return!1;if("function"==typeof l)r(l,this,t);else{var h=l.length,u=g(l,h);for(i=0;i<h;++i)r(u[i],this,t)}return!0},s.prototype.addListener=function(e,t){return h(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return h(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,d(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,d(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,r,n,s,a;if(o(t),void 0===(r=this._events))return this;if(void 0===(i=r[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,n=s;break}if(n<0)return this;0===n?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,n),1===i.length&&(r[e]=i[0]),void 0!==r.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,r;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var n,s=Object.keys(i);for(r=0;r<s.length;++r)"removeListener"!==(n=s[r])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},s.prototype.listeners=function(e){return c(this,e,!0)},s.prototype.rawListeners=function(e){return c(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(h.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+s.path;h.path=a.normalizePath(d)}else h.path=o.path,s.params||(h.params=o.params,s.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(h)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(s,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()},251:e=>{!function t(i){var r;r=function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function r(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,g(r.key),r)}}function n(e,t,i){return t&&r(e.prototype,t),i&&r(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(t,i){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,i){if(t){if("string"==typeof t)return e(t,i);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,i):void 0}}(t))||i){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function a(e,t,i){return(t=g(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},o.apply(null,arguments)}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function h(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,f(e,t)}function u(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(u=function(){return!!e})()}function d(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function c(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?d(Object(i),!0).forEach((function(t){a(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):d(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function f(e,t){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},f(e,t)}function g(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function p(e){var t="function"==typeof Map?new Map:void 0;return p=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return function(e,t,i){if(u())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var n=new(e.bind.apply(e,r));return i&&f(n,i.prototype),n}(e,arguments,l(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),f(i,e)},p(e)}var v,m,y={exports:{}},E=(v||(v=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,r,s,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new n(r,s||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,n=[];if(0===this._eventsCount)return n;for(r in e=this._events)t.call(e,r)&&n.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,s=r.length,a=new Array(s);n<s;n++)a[n]=r[n].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,n,s,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,h,u=this._events[o],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,n),!0;case 5:return u.fn.call(u.context,t,r,n,s),!0;case 6:return u.fn.call(u.context,t,r,n,s,a),!0}for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var c,f=u.length;for(h=0;h<f;h++)switch(u[h].once&&this.removeListener(e,u[h].fn,void 0,!0),d){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,t);break;case 3:u[h].fn.call(u[h].context,t,r);break;case 4:u[h].fn.call(u[h].context,t,r,n);break;default:if(!l)for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u[h].fn.apply(u[h].context,l)}}return!0},o.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,r,n){var s=i?i+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn!==t||n&&!o.once||r&&o.context!==r||a(this,s);else{for(var l=0,h=[],u=o.length;l<u;l++)(o[l].fn!==t||n&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[s]=1===h.length?h[0]:h:a(this,s)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(y)),y.exports),S=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(E),T={exports:{}},L=(m||(m=1,function(e,t){var i,r,n,s,a;i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(h.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+s.path;h.path=a.normalizePath(d)}else h.path=o.path,s.params||(h.params=o.params,s.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(h)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(s,"")).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}(T)),T.exports),_=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},b=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=A},A=Number.MAX_SAFE_INTEGER||9007199254740991,I=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}({}),R=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}({}),k="manifest",D="level",w="audioTrack",C="subtitleTrack",M="main",O="audio",x="subtitle",F=function(){function e(e,t,i){void 0===t&&(t=0),void 0===i&&(i=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}var t=e.prototype;return t.sample=function(e,t){var i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),N=function(){function e(e,t,i,r){void 0===r&&(r=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new F(e),this.fast_=new F(t),this.defaultTTFB_=r,this.ttfb_=new F(e)}var t=e.prototype;return t.update=function(e,t){var i=this.slow_,r=this.fast_,n=this.ttfb_;i.halfLife!==e&&(this.slow_=new F(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new F(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new F(e,n.getEstimate(),n.getTotalWeight()))},t.sample=function(e,t){var i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)},t.sampleTTFB=function(e){var t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},n(e,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),B=function(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="["+e+"]:";this.trace=U,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)},U=function(){},G={trace:U,debug:U,log:U,warn:U,info:U,error:U};function H(){return o({},G)}function V(e,t,i){return t[e]?t[e].bind(t):function(e,t){var i=self.console[e];return i?i.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):U}(e,i)}var K=H();function W(e,t,i){var r=H();if("object"==typeof console&&!0===e||"object"==typeof e){var n=["debug","log","info","warn","error"];n.forEach((function(t){r[t]=V(t,e,i)}));try{r.log('Debug logs enabled for "'+t+'" in hls.js version 1.6.2')}catch(e){return H()}n.forEach((function(t){K[t]=V(t,e)}))}else o(K,r);return r}var $=K;function q(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function j(e,t){var i=Object.keys(e),r=Object.keys(t),n=i.length,s=r.length;return!n||!s||n===s&&!i.some((function(e){return-1===r.indexOf(e)}))}function Y(e,t){if(void 0===t&&(t=!1),"undefined"!=typeof TextDecoder){var i=new TextDecoder("utf-8").decode(e);if(t){var r=i.indexOf("\0");return-1!==r?i.substring(0,r):i}return i.replace(/\0/g,"")}for(var n,s,a,o=e.length,l="",h=0;h<o;){if(0===(n=e[h++])&&t)return l;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:s=e[h++],l+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=e[h++],a=e[h++],l+=String.fromCharCode((15&n)<<12|(63&s)<<6|63&a)}}return l}var z=function(e){for(var t="",i=0;i<e.length;i++){var r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t},X=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}},Q="audio",J="video",Z="audiovideo",ee=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 i,r=e.split("@",2);i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]},t.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[Q]=null,e[J]=null,e[Z]=null},n(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={})[Q]=null,e[J]=null,e[Z]=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 X),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=L.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}])}();function te(e){return"initSegment"!==e.sn}var ie=function(e){function t(t,i){var r;return(r=e.call(this,i)||this)._decryptdata=null,r._programDateTime=null,r._ref=null,r._bitrate=void 0,r.rawProgramDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.playlistOffset=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=t,r}h(t,e);var i=t.prototype;return i.addStart=function(e){this.setStart(this.start+e)},i.setStart=function(e){this.start=e,this._ref&&(this._ref.start=e)},i.setDuration=function(e){this.duration=e,this._ref&&(this._ref.duration=e)},i.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},i.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},i.setElementaryStreamInfo=function(e,t,i,r,n,s){void 0===s&&(s=!1);var a=this.elementaryStreams,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,n)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:s}},n(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],i=this.byteRange[1];if(_(t)&&_(i))return i-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{var t=Object.keys(this.levelkeys);if(1===t.length)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),i=t.length;if(i>1||1===i&&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 te(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(ee),re=function(e){function t(t,i,r,n,s){var a;(a=e.call(this,r)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.duration=t.decimalFloatingPoint("DURATION"),a.gap=t.bool("GAP"),a.independent=t.bool("INDEPENDENT"),a.relurl=t.enumeratedString("URI"),a.fragment=i,a.index=n;var o=t.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,s),s&&(a.fragOffset=s.fragOffset+s.duration),a}return h(t,e),n(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)}}])}(ee);function ne(e,t){var i=Object.getPrototypeOf(e);if(i)return Object.getOwnPropertyDescriptor(i,t)||ne(i,t)}var se=Math.pow(2,32)-1,ae=[].push,oe={video:1,audio:2,id3:3,text:4};function le(e){return String.fromCharCode.apply(null,e)}function he(e,t){var i=e[t]<<8|e[t+1];return i<0?65536+i:i}function ue(e,t){var i=ce(e,t);return i<0?4294967296+i:i}function de(e,t){var i=ue(e,t);return(i*=Math.pow(2,32))+ue(e,t+4)}function ce(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function fe(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function ge(e,t){var i=[];if(!t.length)return i;for(var r=e.byteLength,n=0;n<r;){var s=ue(e,n),a=s>1?n+s:r;if(le(e.subarray(n+4,n+8))===t[0])if(1===t.length)i.push(e.subarray(n+8,a));else{var o=ge(e.subarray(n+8,a),t.slice(1));o.length&&ae.apply(i,o)}n=a}return i}function pe(e){var t=[],i=e[0],r=8,n=ue(e,r);r+=4;var s=0,a=0;0===i?(s=ue(e,r),a=ue(e,r+4),r+=8):(s=de(e,r),a=de(e,r+8),r+=16),r+=2;var o=e.length+a,l=he(e,r);r+=2;for(var h=0;h<l;h++){var u=r,d=ue(e,u);u+=4;var c=2147483647&d;if(1==(2147483648&d)>>>31)return $.warn("SIDX has hierarchical references (not supported)"),null;var f=ue(e,u);u+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+c-1}}),o+=c,r=u+=4}return{earliestPresentationTime:s,timescale:n,version:i,referencesCount:l,references:t}}function ve(e){for(var t=[],i=ge(e,["moov","trak"]),r=0;r<i.length;r++){var n=i[r],s=ge(n,["tkhd"])[0];if(s){var a=s[0],o=ue(s,0===a?12:20),l=ge(n,["mdia","mdhd"])[0];if(l){var h=ue(l,0===(a=l[0])?12:20),u=ge(n,["mdia","hdlr"])[0];if(u){var d=le(u.subarray(8,12)),f={soun:Q,vide:J}[d],g=me(ge(n,["mdia","minf","stbl","stsd"])[0]);f?(t[o]={timescale:h,type:f,stsd:g},t[f]=c({timescale:h,id:o},g)):t[o]={timescale:h,type:d,stsd:g}}}}}return ge(e,["moov","mvex","trex"]).forEach((function(e){var i=ue(e,4),r=t[i];r&&(r.default={duration:ue(e,12),flags:ue(e,20)})})),t}function me(e){var t,i=e.subarray(8),r=i.subarray(86),n=le(i.subarray(4,8)),s=n,a="enca"===n||"encv"===n;if(a){var o=ge(i,[n])[0];ge(o.subarray("enca"===n?28:78),["sinf"]).forEach((function(e){var t=ge(e,["schm"])[0];if(t){var i=le(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=ge(e,["frma"])[0];r&&(s=le(r))}}}))}var l=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":var h=ge(r,["avcC"])[0];h&&h.length>3&&(s+="."+Se(h[1])+Se(h[2])+Se(h[3]),t=ye("avc1"===l?"dva1":"dvav",r));break;case"mp4a":var u=ge(i,[n])[0],d=ge(u.subarray(28),["esds"])[0];if(d&&d.length>7){var c=4;if(3!==d[c++])break;c=Ee(d,c),c+=2;var f=d[c++];if(128&f&&(c+=2),64&f&&(c+=d[c++]),4!==d[c++])break;c=Ee(d,c);var g=d[c++];if(64!==g)break;if(s+="."+Se(g),c+=12,5!==d[c++])break;c=Ee(d,c);var p=d[c++],v=(248&p)>>3;31===v&&(v+=1+((7&p)<<3)+((224&d[c])>>5)),s+="."+v}break;case"hvc1":case"hev1":var m=ge(r,["hvcC"])[0];if(m&&m.length>12){var y=m[1],E=["","A","B","C"][y>>6],S=31&y,T=ue(m,2),L=(32&y)>>5?"H":"L",_=m[12],b=m.subarray(6,12);s+="."+E+S,s+="."+T.toString(16).toUpperCase(),s+="."+L+_;for(var A="",I=b.length;I--;){var R=b[I];(R||A)&&(A="."+R.toString(16).toUpperCase()+A)}s+=A}t=ye("hev1"==l?"dvhe":"dvh1",r);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=ye(s,r)||s;break;case"vp09":var P=ge(r,["vpcC"])[0];if(P&&P.length>6){var k=P[4],D=P[5],w=P[6]>>4&15;s+="."+Te(k)+"."+Te(D)+"."+Te(w)}break;case"av01":var C=ge(r,["av1C"])[0];if(C&&C.length>2){var M=C[1]>>>5,O=31&C[1],x=C[2]>>>7?"H":"M",F=(64&C[2])>>6,N=(32&C[2])>>5,B=2===M&&F?N?12:10:F?10:8,U=(16&C[2])>>4,G=(8&C[2])>>3,H=(4&C[2])>>2,V=3&C[2];s+="."+M+"."+Te(O)+x+"."+Te(B)+"."+U+"."+G+H+V+"."+Te(1)+"."+Te(1)+"."+Te(1)+".0",t=ye("dav1",r)}}return{codec:s,encrypted:a,supplemental:t}}function ye(e,t){var i=ge(t,["dvvC"]),r=i.length?i[0]:ge(t,["dvcC"])[0];if(r){var n=r[2]>>1&127,s=r[2]<<5&32|r[3]>>3&31;return e+"."+Te(n)+"."+Te(s)}}function Ee(e,t){for(var i=t+5;128&e[t++]&&t<i;);return t}function Se(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Te(e){return(e<10?"0":"")+e}function Le(e){var t=ge(e,["schm"])[0];if(t){var i=le(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return ge(e,["schi","tenc"])[0]}return null}function _e(e){var t=ue(e,0),i=8;1&t&&(i+=4),4&t&&(i+=4);for(var r=0,n=ue(e,4),s=0;s<n;s++)256&t&&(r+=ue(e,i),i+=4),512&t&&(i+=4),1024&t&&(i+=4),2048&t&&(i+=4);return r}function be(e,t){var i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function Ae(e,t){var i=[],r=t.samples,n=t.timescale,s=t.id,a=!1;return ge(r,["moof"]).map((function(o){var l=o.byteOffset-8;ge(o,["traf"]).map((function(o){var h=ge(o,["tfdt"]).map((function(e){var t=e[0],i=ue(e,4);return 1===t&&(i*=Math.pow(2,32),i+=ue(e,8)),i/n}))[0];return void 0!==h&&(e=h),ge(o,["tfhd"]).map((function(h){var u=ue(h,4),d=16777215&ue(h,0),c=0,f=!!(16&d),g=0,p=!!(32&d),v=8;u===s&&(!!(1&d)&&(v+=8),!!(2&d)&&(v+=4),!!(8&d)&&(c=ue(h,v),v+=4),f&&(g=ue(h,v),v+=4),p&&(v+=4),"video"===t.type&&(a=Ie(t.codec)),ge(o,["trun"]).map((function(s){var o=s[0],h=16777215&ue(s,0),u=!!(1&h),d=0,f=!!(4&h),p=!!(256&h),v=0,m=!!(512&h),y=0,E=!!(1024&h),S=!!(2048&h),T=0,L=ue(s,4),_=8;u&&(d=ue(s,_),_+=4),f&&(_+=4);for(var b=d+l,A=0;A<L;A++){if(p?(v=ue(s,_),_+=4):v=c,m?(y=ue(s,_),_+=4):y=g,E&&(_+=4),S&&(T=0===o?ue(s,_):ce(s,_),_+=4),t.type===J)for(var I=0;I<y;){var R=ue(r,b);Re(a,r[b+=4])&&Pe(r.subarray(b,b+R),a?2:1,e+T/n,i),b+=R,I+=R+4}e+=v/n}})))}))}))})),i}function Ie(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Re(e,t){if(e){var i=t>>1&63;return 39===i||40===i}return 6==(31&t)}function Pe(e,t,i,r){var n=ke(e),s=0;s+=t;for(var a=0,o=0,l=0;s<n.length;){a=0;do{if(s>=n.length)break;a+=l=n[s++]}while(255===l);o=0;do{if(s>=n.length)break;o+=l=n[s++]}while(255===l);var h=n.length-s,u=s;if(o<h)s+=o;else if(o>h){$.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===n[u++]){var d=he(n,u);if(u+=2,49===d){var c=ue(n,u);if(u+=4,1195456820===c){var f=n[u++];if(3===f){var g=n[u++],p=64&g,v=p?2+3*(31&g):0,m=new Uint8Array(v);if(p){m[0]=g;for(var y=1;y<v;y++)m[y]=n[u++]}r.push({type:f,payloadType:a,pts:i,bytes:m})}}}}}else if(5===a&&o>16){for(var E=[],S=0;S<16;S++){var T=n[u++].toString(16);E.push(1==T.length?"0"+T:T),3!==S&&5!==S&&7!==S&&9!==S||E.push("-")}for(var L=o-16,_=new Uint8Array(L),b=0;b<L;b++)_[b]=n[u++];r.push({payloadType:a,pts:i,uuid:E.join(""),userData:Y(_),userDataBytes:_})}}}function ke(e){for(var t=e.byteLength,i=[],r=1;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;var n=t-i.length,s=new Uint8Array(n),a=0;for(r=0;r<n;a++,r++)a===i[0]&&(a++,i.shift()),s[r]=e[a];return s}function De(e){var t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:i,size:t};var s=e.buffer,a=z(new Uint8Array(s,i+12,16)),o=e.getUint32(28),l=null,h=null;if(0===n){if(t-32<o||o<22)return{offset:i,size:t};h=new Uint8Array(s,i+32,o)}else if(1===n){if(!o||r<i+32+16*o+16)return{offset:i,size:t};l=[];for(var u=0;u<o;u++)l.push(new Uint8Array(s,i+32+16*u,16))}return{version:n,systemId:a,kids:l,data:h,offset:i,size:t}}var we=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 Me(e,t){var i=Ce[t];return!!i&&!!i[e.slice(0,4)]}function Oe(e,t,i){return void 0===i&&(i=!0),!e.split(",").some((function(e){return!xe(e,t,i)}))}function xe(e,t,i){var r;void 0===i&&(i=!0);var n=q(i);return null!=(r=null==n?void 0:n.isTypeSupported(Fe(e,t)))&&r}function Fe(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 Be(e){var t=we();return e.split(",").reduce((function(e,i){var r=t&&Ie(i)?9:Ce.video[i];return r?(2*r+e)/(e?3:2):(Ce.audio[i]+e)/(e?2:1)}),0)}var Ue={},Ge=/flac|opus|mp4a\.40\.34/i;function He(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 i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],r=0;r<i.length;r++){var n;if(xe(i[r],"audio",t))return Ue[e]=i[r],i[r];if("mp3"===i[r]&&null!=(n=q(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)}))}function Ve(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){var i=t.split(",");if(i.length>1){if(e)for(var r=i.length;r--;)if(i[r].substring(0,4)===e.substring(0,4))return i[r];return i[0]}}return t||e}function Ke(e){if(e.startsWith("av01.")){for(var t=e.split("."),i=["0","111","01","01","01","0"],r=t.length;r>4&&r<10;r++)t[r]=i[r-4];return t.join(".")}return e}function We(e){var t=q(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function $e(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var qe={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function je(e,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:e}}var Ye={};function ze(e,t,i){var r=e.videoCodec,n=e.audioCodec;if(!r&&!n||!i)return Promise.resolve(qe);var s=[];if(r){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=r.split(","),h=navigator.userAgent;if(l.some((function(e){return Ie(e)}))&&we())return Promise.resolve(je(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: ("+h+")"),s));s.push.apply(s,l.map((function(e){return{type:"media-source",video:c(c({},a),{},{contentType:Fe(Ke(e),"video")})}})))}return n&&e.audioGroups&&e.audioGroups.forEach((function(e){var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((function(t){if(t.groupId===e){var i=t.channels||"",r=parseFloat(i);_(r)&&r>2&&s.push.apply(s,n.split(",").map((function(e){return{type:"media-source",audio:{contentType:Fe(e,"audio"),channels:""+r}}})))}})))})),Promise.all(s.map((function(e){var t=function(e){var t=e.audio,i=e.video,r=i||t;if(r){var n=$e(r.contentType);if(i)return"r"+i.height+"x"+i.width+"f"+Math.ceil(i.framerate)+(i.transferFunction||"sd")+"_"+n+"_"+Math.ceil(i.bitrate/1e5);if(t)return"c"+t.channels+(t.spatialRendering?"s":"n")+"_"+n}return""}(e);return Ye[t]||(Ye[t]=i.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:s,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:s,decodingInfoResults:[],error:e}}))}var Xe=["NONE","TYPE-0","TYPE-1",null],Qe=["SDR","PQ","HLG"];function Je(e){var t=e.canSkipUntil,i=e.canSkipDateRanges,r=e.age;return t&&r<t/2?i?"v2":"YES":""}var Ze=function(){function e(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}return e.prototype.addDirectives=function(e){var t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href},e}(),et=function(){function e(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((function(e){return!!e})).map((function(e){return e.substring(0,4)})).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;var i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=","+i.substring(0,4))}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}var t=e.prototype;return t.hasAudioGroup=function(e){return tt(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return tt(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(t)&&i.push(t)}else if("text"===e){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(t)&&r.push(t)}},t.addFallback=function(){},n(e,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}}])}();function tt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}var it=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(i,r){if(e&&(r=e(i,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}}(t))};function rt(e,t){$.log('[abr] start candidates with "'+e+'" ignored because '+t)}function nt(e){return e.reduce((function(e,t){var i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);var r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function st(e){if(!e)return e;var t=e;return{lang:t.lang,assocLang:t.assocLang,characteristics:t.characteristics,channels:t.channels,audioCodec:t.audioCodec}}function at(e,t,i){if("attrs"in e){var r=t.indexOf(e);if(-1!==r)return r}for(var n=0;n<t.length;n++)if(ot(e,t[n],i))return n;return-1}function ot(e,t,i){var r,n,s=e.groupId,a=e.name,o=e.lang,l=e.assocLang,h=e.default,u=e.forced;return(void 0===s||t.groupId===s)&&(void 0===a||t.name===a)&&(void 0===o||(r=o,void 0===(n=t.lang)&&(n="--"),r.length===n.length?r===n:r.startsWith(n)||n.startsWith(r)))&&(void 0===o||t.assocLang===l)&&(void 0===h||t.default===h)&&(void 0===u||t.forced===u)&&(!("characteristics"in e)||function(e,t){void 0===t&&(t="");var i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some((function(e){return-1===r.indexOf(e)}))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function lt(e,t){var i=e.audioCodec,r=e.channels;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function ht(e,t,i){for(var r=t;r>-1;r--)if(i(e[r]))return r;for(var n=t+1;n<e.length;n++)if(i(e[n]))return n;return-1}function ut(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}var dt=function(e){function t(t){var i;return(i=e.call(this,"abr",t.logger)||this).hls=void 0,i.lastLevelLoadSec=0,i.lastLoadedFragLevel=-1,i.firstSelection=-1,i._nextAutoLevel=-1,i.nextAutoLevelKey="",i.audioTracksByGroup=null,i.codecTiers=null,i.timer=-1,i.fragCurrent=null,i.partCurrent=null,i.bitrateTestDelay=0,i.rebufferNotice=-1,i.bwEstimator=void 0,i._abandonRulesCheck=function(e){var t,r=i,n=r.fragCurrent,s=r.partCurrent,a=r.hls,o=a.autoLevelEnabled,l=a.media;if(n&&l){var h=performance.now(),u=s?s.stats:n.stats,d=s?s.duration:n.duration,c=h-u.loading.start,f=a.minAutoLevel,g=n.level,p=i._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f)return i.clearTimer(),void(i._nextAutoLevel=-1);if(o){var v=p>-1&&p!==g,m=!!e||v;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=a.mainForwardBufferInfo;if(m||null!==y){var E=i.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(!(c<=Math.max(E,d/(2*S)*1e3))){var T=y?y.len/S:0,L=u.loading.first?u.loading.first-u.loading.start:-1,b=u.loaded&&L>-1,A=i.getBwEstimate(),I=a.levels,R=I[g],k=Math.max(u.loaded,Math.round(d*(n.bitrate||R.averageBitrate)/8)),D=b?c-L:c;D<1&&b&&(D=Math.min(c,8*u.loaded/A));var w=b?1e3*u.loaded/D:0,C=E/1e3,M=w?(k-u.loaded)/w:8*k/A+C;if(!(M<=T)){var O,x=w?8*w:A,F=!0===(null==(t=(null==e?void 0:e.details)||i.hls.latestLevelDetails)?void 0:t.live),N=i.hls.config.abrBandWidthUpFactor,B=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){var U=I[O].maxBitrate,G=!I[O].details||F;if((B=i.getTimeToLoadFrag(C,x,d*U,G))<Math.min(T,d+C))break}if(!(B>=M||B>10*d)){b?i.bwEstimator.sample(c-Math.min(E,L),u.loaded):i.bwEstimator.sampleTTFB(c);var H=I[O].maxBitrate;i.getBwEstimate()*N>H&&i.resetEstimator(H);var V=i.findBestLevel(H,f,O,0,T,1,1);V>-1&&(O=V),i.warn("Fragment "+n.sn+(s?" part "+s.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+n.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: "+(_(A)?0|A:"Unknown")+" bps\n New BW estimate: "+(0|i.getBwEstimate())+" bps\n Switching to level "+O+" @ "+(0|H)+" bps"),a.nextLoadLevel=a.nextAutoLevel=O,i.clearTimer();var K=function(){if(i.clearTimer(),i.fragCurrent===n&&i.hls.loadLevel===O&&O>0){var e=i.getStarvationDelay();if(i.warn("Aborting inflight request "+(O>0?"and switching down":"")+"\n Fragment duration: "+n.duration.toFixed(3)+" s\n Time to underbuffer: "+e.toFixed(3)+" s"),n.abortRequests(),i.fragCurrent=i.partCurrent=null,O>f){var t=i.findBestLevel(i.hls.levels[f].bitrate,f,O,0,e,1,1);-1===t&&(t=f),i.hls.nextLoadLevel=i.hls.nextAutoLevel=t,i.resetEstimator(i.hls.levels[t].bitrate)}}};v||M>2*B?K():i.timer=self.setInterval(K,1e3*B),a.trigger(P.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:s,stats:u})}}}}}}}},i.hls=t,i.bwEstimator=i.initEstimator(),i.registerListeners(),i}h(t,e);var i=t.prototype;return i.resetEstimator=function(e){e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},i.initEstimator=function(){var e=this.hls.config;return new N(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},i.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)},i.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))},i.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},i.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},i.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},i.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},i.onFragLoading=function(e,t){var i,r=t.frag;this.ignoreFragment(r)||(r.bitrateTest||(this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},i.onLevelSwitching=function(e,t){this.clearTimer()},i.onError=function(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:var i=t.frag,r=this.fragCurrent,n=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var s=performance.now(),a=n?n.stats:i.stats,o=s-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){var h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}}},i.getTimeToLoadFrag=function(e,t,i,r){return e+i/t+(r?e+this.lastLevelLoadSec:0)},i.onLevelLoaded=function(e,t){var i=this.hls.config,r=t.stats.loading,n=r.end-r.first;_(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},i.onFragLoaded=function(e,t){var i=t.frag,r=t.part,n=r?r.stats:i.stats;if(i.type===M&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var s=r?r.duration:i.duration,a=this.hls.levels[i.level],o=(a.loaded?a.loaded.bytes:0)+n.loaded,l=(a.loaded?a.loaded.duration:0)+s;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(i.bitrateTest){var h={stats:n,frag:i,part:r,id:i.type};this.onFragBuffered(P.FRAG_BUFFERED,h),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,n=null!=r&&r.stats.loaded?r.stats:i.stats;if(!n.aborted&&!this.ignoreFragment(i)){var s=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}},i.ignoreFragment=function(e){return e.type!==M||"initSegment"===e.sn},i.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},i.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},i.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,i=this.hls;if(i.levels.length<=1)return i.loadLevel;var r=i.maxAutoLevel,n=i.config,s=i.minAutoLevel,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,s,r,l,0,h,u);if(d>=0)return this.rebufferNotice=-1,d}var c=a?Math.min(a,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(a?Math.min(a,n.maxLoadingDelay):n.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,s,r,l,c,h,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var p=i.levels[s],v=i.loadLevelObj;return v&&(null==p?void 0:p.bitrate)<v.bitrate?s:i.loadLevel},i.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i},i.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},i.findBestLevel=function(e,t,i,r,n,s,a){var o,l=this,h=r+n,u=this.lastLoadedFragLevel,d=-1===u?this.hls.firstLevel:u,c=this.fragCurrent,f=this.partCurrent,g=this.hls,p=g.levels,v=g.allAudioTracks,m=g.loadLevel,y=g.config;if(1===p.length)return 0;var E,S=p[d],T=!(null==(o=this.hls.latestLevelDetails)||!o.live),L=-1===m||-1===u,b="SDR",A=(null==S?void 0:S.frameRate)||0,I=y.audioPreference,R=y.videoPreference,P=this.audioTracksByGroup||(this.audioTracksByGroup=nt(v)),k=-1;if(L){if(-1!==this.firstSelection)return this.firstSelection;var D=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce((function(e,i,r){if(!i.codecSet)return e;var n=i.audioGroups,s=e[i.codecSet];s||(e[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);var a=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.minIndex=Math.min(s.minIndex,r),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,n&&n.forEach((function(e){if(e){var i=t.groups[e];i&&(s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((function(e){s.channels[e]=(s.channels[e]||0)+i.channels[e]})))}})),e}),{})}(p,P,t,i)),w=function(e,t,i,r,n){for(var s=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=null==n?void 0:n.videoCodec,h=a&&2===parseInt(a),u=!1,d=!1,c=1/0,f=1/0,g=1/0,p=1/0,v=0,m=[],y=function(e,t){var i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){var n="SDR"!==(r=t.allowedVideoRanges||Qe.slice(0)).join("")&&!t.videoCodec;(i=void 0!==t.preferHDR?t.preferHDR:n&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}(t,n),E=y.preferHDR,S=y.allowedVideoRanges,T=function(){var t=e[s[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=s.length;L--;)T();c=_(c)?c:0,f=_(f)?f:0;var b=Math.max(1080,c),A=Math.max(30,f);g=_(g)?g:i,i=Math.max(g,i),d||(t=void 0);var I=s.length>1;return{codecSet:s.reduce((function(t,r){var n=e[r];if(r===t)return t;if(m=d?S.filter((function(e){return n.videoRanges[e]>0})):[],I){if(n.minBitrate>i)return rt(r,"min bitrate of "+n.minBitrate+" > current estimate of "+i),t;if(!n.hasDefaultAudio)return rt(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return rt(r,'audio codec preference "'+o+'" not found'),t;if(a&&!h){if(!n.channels[a])return rt(r,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(n.channels)+")"),t}else if((!o||h)&&u&&0===n.channels[2])return rt(r,"no renditions with stereo sound found"),t;if(n.minHeight>b)return rt(r,"min resolution of "+n.minHeight+" > maximum of "+b),t;if(n.minFramerate>A)return rt(r,"min framerate of "+n.minFramerate+" > maximum of "+A),t;if(!m.some((function(e){return n.videoRanges[e]>0})))return rt(r,"no variants with VIDEO-RANGE of "+it(m)+" found"),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return rt(r,'video codec preference "'+l+'" not found'),t;if(n.maxScore<v)return rt(r,"max score of "+n.maxScore+" < selected max of "+v),t}return t&&(Be(r)>=Be(t)||n.fragmentError>e[t].fragmentError)?t:(p=n.minIndex,v=n.maxScore,r)}),void 0),videoRanges:m,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}(D,b,e,I,R),C=w.codecSet,M=w.videoRanges,O=w.minFramerate,x=w.minBitrate,F=w.minIndex,N=w.preferHDR;k=F,E=C,b=N?M[M.length-1]:M[0],A=O,e=Math.max(e,x),this.log("picked start tier "+it(w))}else E=null==S?void 0:S.codecSet,b=null==S?void 0:S.videoRange;for(var B,U=f?f.duration:c?c.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,H=[],V=function(){var t,o=p[K],c=K>d;if(!o)return 0;if(y.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&(function(e,t,i,r,n,s){var a=e.audioCodec?e.audioGroups:null,o=null==s?void 0:s.audioCodec,l=null==s?void 0:s.channels,h=l?parseInt(l):o?1/0:2,u=null;if(null!=a&&a.length)try{u=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce((function(e,i){if(i){var r=t.groups[i];if(!r)throw new Error("Audio track group "+i+" not found");Object.keys(r.channels).forEach((function(t){e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(n,8e6))||!!u&&_(h)&&Object.keys(u).some((function(e){return parseInt(e)>h}))}(o,P,b,A,e,I)||Ie(o.videoCodec))?(o.supportedPromise=ze(o,P,g),o.supportedPromise.then((function(e){if(l.hls){o.supportedResult=e;var t=l.hls.levels,i=t.indexOf(o);e.error?l.warn('MediaCapabilities decodingInfo error: "'+e.error+'" for level '+i+" "+it(e)):e.supported||(l.warn("Unsupported MediaCapabilities decodingInfo result for level "+i+" "+it(e)),i>-1&&t.length>1&&(l.log("Removing unsupported level "+i),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}}))):o.supportedResult=qe}if((E&&o.codecSet!==E||b&&o.videoRange!==b||c&&A>o.frameRate||!c&&A>0&&A<o.frameRate||o.supportedResult&&(null==(t=o.supportedResult.decodingInfoResults)||!t[0].smooth))&&(!L||K!==k))return H.push(K),0;var v,S=o.details,R=(f?null==S?void 0:S.partTarget:null==S?void 0:S.averagetargetduration)||U;v=c?a*e:s*e;var D=U&&r>=2*U&&0===n?o.averageBitrate:o.maxBitrate,w=l.getTimeToLoadFrag(G,v,D*R,void 0===S);if(v>=D&&(K===u||0===o.loadError&&0===o.fragmentError)&&(w<=G||!_(w)||T&&!l.bitrateTestDelay||w<h)){var C=l.forcedAutoLevel;return K===m||-1!==C&&C===m||(H.length&&l.trace("Skipped level(s) "+H.join(",")+" of "+i+' max with CODECS and VIDEO-RANGE:"'+p[H[0]].codecs+'" '+p[H[0]].videoRange+'; not compatible with "'+E+'" '+b),l.info("switch candidate:"+d+"->"+K+" adjustedbw("+Math.round(v)+")-bitrate="+Math.round(v-D)+" ttfb:"+G.toFixed(1)+" avgDuration:"+R.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+w.toFixed(1)+" firstSelection:"+L+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+m)),L&&(l.firstSelection=K),{v:K}}},K=i;K>=t;K--)if(0!==(B=V())&&B)return B.v;return-1},i.deriveNextAutoLevel=function(e){var t=this.hls,i=t.maxAutoLevel,r=t.minAutoLevel;return Math.min(Math.max(e,r),i)},n(t,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,i=e.minAutoLevel,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,i,t,0,n,1,1);if(s>-1)return s;var a=this.hls.firstLevel,o=Math.min(Math.max(a,i),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+a+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(B),ct=function(e,t){for(var i=0,r=e.length-1,n=null,s=null;i<=r;){var a=t(s=e[n=(i+r)/2|0]);if(a>0)i=n+1;else{if(!(a<0))return s;r=n-1}}return null};function ft(e,t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=.005);var s=null;if(e){s=t[1+e.sn-t[0].sn]||null;var a=e.endDTS-i;a>0&&a<15e-7&&(i+=15e-7),s&&e.level!==s.level&&s.end<=e.end&&(s=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(s=t[0]);if(s&&((!e||e.level===s.level)&&0===gt(i,r,s)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var r=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),i);return e.start<=r}return!1}(s,e,Math.min(n,r))))return s;var o=ct(t,gt.bind(null,i,r));return!o||o===e&&s?s:o}function gt(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=0),i.start<=e&&i.start+i.duration>e)return 0;var r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function pt(e,t,i){var r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}function vt(e,t){return ct(e,(function(e){return e.cc<t?1:e.cc>t?-1:0}))}function mt(e){switch(e.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function yt(e,t){var i=mt(t);return e.default[(i?"timeout":"error")+"Retry"]}function Et(e,t){var i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function St(e){return c(c({},e),{errorRetry:null,timeoutRetry:null})}function Tt(e,t,i,r){if(!e)return!1;var n=null==r?void 0:r.code,s=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(n)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,s):s}var Lt=function(e){function t(t){var i;return(i=e.call(this,"error-controller",t.logger)||this).hls=void 0,i.playlistError=0,i.penalizedRenditions={},i.hls=t,i.registerListeners(),i}h(t,e);var i=t.prototype;return i.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)},i.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))},i.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},i.startLoad=function(e){},i.stopLoad=function(){this.playlistError=0},i.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===M?e.level:this.hls.loadLevel},i.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},i.onLevelUpdated=function(){this.playlistError=0},i.onError=function(e,t){var i;if(!t.fatal){var r=this.hls,n=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case R.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=_t());case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=2);case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:var s,a,o=t.parent===M?t.level:r.loadLevel;return void(t.details===R.LEVEL_EMPTY_ERROR&&null!=(s=t.context)&&null!=(a=s.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o)));case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var l=r.loadLevelObj;if(l&&(n.type===w&&l.hasAudioGroup(n.groupId)||n.type===C&&l.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var h=r.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 R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:var d;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(d=t.level)?d:r.loadLevel)));case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=_t())}t.type===I.KEY_SYSTEM_ERROR&&this.keySystemError(t)}},i.keySystemError=function(e){var t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)},i.getPlaylistRetryOrSwitchAction=function(e,t){var i=yt(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Tt(i,r,mt(e),e.response))return{action:5,flags:0,retryConfig:i,retryCount:r};var n=this.getLevelSwitchAction(e,t);return i&&(n.retryConfig=i,n.retryCount=r),n},i.getFragRetryOrSwitchAction=function(e){var t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=t.config,s=n.fragLoadPolicy,a=n.keyLoadPolicy,o=yt(e.details.startsWith("key")?a:s,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(r&&(e.details!==R.FRAG_GAP&&r.fragmentError++,Tt(o,l,mt(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(e,i);return o&&(h.retryConfig=o,h.retryCount=l),h},i.getLevelSwitchAction=function(e,t){var i=this.hls;null==t&&(t=i.loadLevel);var r=this.hls.levels[t];if(r){var n,s,a=e.details;r.loadError++,a===R.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,h=i.loadLevel,u=i.minAutoLevel,d=i.maxAutoLevel;i.autoLevelEnabled||(i.loadLevel=-1);for(var c,f=null==(n=e.frag)?void 0:n.type,g=(f===O&&a===R.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(a===R.BUFFER_ADD_CODEC_ERROR||a===R.BUFFER_APPEND_ERROR))&&l.some((function(e){var t=e.audioCodec;return r.audioCodec!==t})),p="video"===e.sourceBufferName&&(a===R.BUFFER_ADD_CODEC_ERROR||a===R.BUFFER_APPEND_ERROR)&&l.some((function(e){var t=e.codecSet,i=e.audioCodec;return r.codecSet!==t&&r.audioCodec===i})),v=null!=(s=e.context)?s:{},m=v.type,y=v.groupId,E=function(){var t=(S+h)%l.length;if(t!==h&&t>=u&&t<=d&&0===l[t].loadError){var i,n,s=l[t];if(a===R.FRAG_GAP&&f===M&&e.frag){var c=l[t].details;if(c){var v=ft(e.frag,c.fragments,e.frag.start);if(null!=v&&v.gap)return 0}}else{if(m===w&&s.hasAudioGroup(y)||m===C&&s.hasSubtitleGroup(y))return 0;if(f===O&&null!=(i=r.audioGroups)&&i.some((function(e){return s.hasAudioGroup(e)}))||f===x&&null!=(n=r.subtitleGroups)&&n.some((function(e){return s.hasSubtitleGroup(e)}))||g&&r.audioCodec===s.audioCodec||!g&&r.audioCodec!==s.audioCodec||p&&r.codecSet===s.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(c=E())||1!==c););if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}},i.onErrorOut=function(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===R.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'+t.sourceBufferName+'" sourceBuffer append error. Attempting to recover from media error.'),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()},i.sendAlternateToPenaltyBox=function(e){var t=this.hls,i=e.errorAction;if(i){var r=i.flags,n=i.hdcpLevel,s=i.nextAutoLevel;switch(r){case 0:this.switchLevel(e,s);break;case 2:n&&(t.maxHdcpLevel=Xe[Xe.indexOf(n)-1],i.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')}i.resolved||this.switchLevel(e,s)}},i.switchLevel=function(e,t){if(void 0!==t&&e.errorAction&&(this.warn("switching to level "+t+" after "+e.details),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var i=$e(e.mimeType),r=this.hls.levels,n=r.length;n--;)r[n][e.sourceBufferName+"Codec"]===i&&this.hls.removeLevel(n)},t}(B);function _t(e){var t={action:0,flags:0};return e&&(t.resolved=!0),t}var bt="NOT_LOADED",At="APPENDING",It="PARTIAL",Rt="OK",Pt=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 i=this.activePartLists[t];if(i)for(var r=i.length;r--;){var n=i[r];if(!n)break;var s=n.end;if(n.start<=e&&null!==s&&e<=s)return n}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){return this.getFragAtPos(e,t,!0)},t.getFragAtPos=function(e,t,i){for(var r=this.fragments,n=Object.keys(r),s=n.length;s--;){var a=r[n[s]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){var o=a.body;if(o.start<=e&&e<=o.end)return o}}return null},t.detectEvictedFragments=function(e,t,i,r,n){var s=this;this.timeRanges&&(this.timeRanges[e]=t);var a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(r){var o=s.fragments[r];if(o&&!(a>=o.body.sn))if(o.buffered||o.loaded&&!n){var l=o.range[e];l&&(0!==l.time.length?l.time.some((function(e){var i=!s.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&s.removeFragment(o.body),i})):s.removeFragment(o.body))}else o.body.type===i&&s.removeFragment(o.body)}))},t.detectPartialFragments=function(e){var t=this,i=this.timeRanges;if(i&&"initSegment"!==e.frag.sn){var r=e.frag,n=Dt(r),s=this.fragments[n];if(!(!s||s.buffered&&r.gap)){var a=!r.relurl;Object.keys(i).forEach((function(n){var o=r.elementaryStreams[n];if(o){var l=i[n],h=a||!0===o.partial;s.range[n]=t.getBufferedTimes(r,e.part,h,l)}})),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=r.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),kt(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}}},t.removeParts=function(e,t){var i=this.activePartLists[t];i&&(this.activePartLists[t]=wt(i,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var i=Dt(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)},t.getBufferedTimes=function(e,t,i,r){for(var n={time:[],partial:i},s=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||s,h=0;h<r.length;h++){var u=r.start(h)-this.bufferPadding,d=r.end(h)+this.bufferPadding;if(l>=u&&o<=d){n.time.push({startPTS:Math.max(s,r.start(h)),endPTS:Math.min(a,r.end(h))});break}if(s<d&&a>u){var c=Math.max(s,r.start(h)),f=Math.min(a,r.end(h));f>c&&(n.partial=!0,n.time.push({startPTS:c,endPTS:f}))}else if(a<=u)break}return n},t.getPartialFragment=function(e){var t,i,r,n=null,s=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&kt(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),s<=t&&(n=h.body,s=t)))})),n},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||kt(t))},t.getState=function(e){var t=Dt(e),i=this.fragments[t];return i?i.buffered?kt(i)?It:Rt:At:bt},t.isTimeBuffered=function(e,t,i){for(var r,n,s=0;s<i.length;s++){if(r=i.start(s)-this.bufferPadding,n=i.end(s)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var i=t.frag,r=t.part?null:t,n=Dt(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var i=t.frag,r=t.part,n=t.timeRanges,s=t.type;if("initSegment"!==i.sn){var a=i.type;if(r){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=n;var l=n[s];this.detectEvictedFragments(s,l,a,r)}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Dt(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,i=Object.keys(t);if(!e)return i.length>0;for(var r=i.length;r--;){var n=t[i[r]];if((null==n?void 0:n.body.type)===e)return!0}return!1},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.removeFragmentsInRange=function(e,t,i,r,n){var s=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=s.fragments[a];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&s.removeFragment(l)}}))},t.removeFragment=function(e){var t=Dt(e);e.clearElementaryStreamInfo();var i=this.activePartLists[e.type];if(i){var r=e.sn;this.activePartLists[e.type]=wt(i,(function(e){return e.fragment.sn!==r}))}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 i=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;i&&i.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function kt(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function Dt(e){return e.type+"_"+e.level+"_"+e.sn}function wt(e,t){return e.filter((function(e){var i=t(e);return i||e.clearElementaryStreamInfo(),i}))}var Ct=function(){function e(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}return e.prototype.decrypt=function(e,t){switch(this.aesMode){case 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},e}(),Mt=function(){function e(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),i=new Uint32Array(4),r=0;r<4;r++)i[r]=t.getUint32(4*r);return i},t.initTable=function(){var e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],s=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],u=o[2],d=o[3],c=new Uint32Array(256),f=0,g=0,p=0;for(p=0;p<256;p++)c[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^255&v^99,e[f]=v,t[v]=f;var m=c[f],y=c[m],E=c[y],S=257*c[v]^16843008*v;r[f]=S<<24|S>>>8,n[f]=S<<16|S>>>16,s[f]=S<<8|S>>>24,a[f]=S,S=16843009*E^65537*y^257*m^16843008*f,l[v]=S<<24|S>>>8,h[v]=S<<16|S>>>16,u[v]=S<<8|S>>>24,d[v]=S,f?(f=m^c[c[c[E^m]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;r<t.length&&i;)i=t[r]===this.key[r],r++;if(!i){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var s,a,o,l,h=this.ksRows=4*(n+6+1),u=this.keySchedule=new Uint32Array(h),d=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,p=g[0],v=g[1],m=g[2],y=g[3];for(s=0;s<h;s++)s<n?o=u[s]=t[s]:(l=o,s%n==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[s/n|0]<<24):n>6&&s%n==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),u[s]=o=(u[s-n]^l)>>>0);for(a=0;a<h;a++)s=h-a,l=3&a?u[s]:u[s-4],d[a]=a<4||s<=4?l:p[c[l>>>24]]^v[c[l>>>16&255]]^m[c[l>>>8&255]]^y[c[255&l]],d[a]=d[a]>>>0}},t.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},t.decrypt=function(e,t,i){for(var r,n,s,a,o,l,h,u,d,c,f,g,p,v,m=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,S=this.invSubMix,T=S[0],L=S[1],_=S[2],b=S[3],A=this.uint8ArrayToUint32Array_(i),I=A[0],R=A[1],P=A[2],k=A[3],D=new Int32Array(e),w=new Int32Array(D.length),C=this.networkToHostOrderSwap;t<D.length;){for(d=C(D[t]),c=C(D[t+1]),f=C(D[t+2]),g=C(D[t+3]),o=d^y[0],l=g^y[1],h=f^y[2],u=c^y[3],p=4,v=1;v<m;v++)r=T[o>>>24]^L[l>>16&255]^_[h>>8&255]^b[255&u]^y[p],n=T[l>>>24]^L[h>>16&255]^_[u>>8&255]^b[255&o]^y[p+1],s=T[h>>>24]^L[u>>16&255]^_[o>>8&255]^b[255&l]^y[p+2],a=T[u>>>24]^L[o>>16&255]^_[l>>8&255]^b[255&h]^y[p+3],o=r,l=n,h=s,u=a,p+=4;r=E[o>>>24]<<24^E[l>>16&255]<<16^E[h>>8&255]<<8^E[255&u]^y[p],n=E[l>>>24]<<24^E[h>>16&255]<<16^E[u>>8&255]<<8^E[255&o]^y[p+1],s=E[h>>>24]<<24^E[u>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[p+2],a=E[u>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&h]^y[p+3],w[t]=C(r^I),w[t+1]=C(a^R),w[t+2]=C(s^P),w[t+3]=C(n^k),I=d,R=c,P=f,k=g,t+=4}return w.buffer},e}(),Ot=function(){function e(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}return e.prototype.expandKey=function(){var e=function(e){switch(e){case 0:return"AES-CBC";case 1:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode "+e)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])},e}(),xt=function(){function e(e,t){var i=(void 0===t?{}:t).removePKCS7Padding,r=void 0===i||i;if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=r,r)try{var n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}var t=e.prototype;return t.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},t.isSync=function(){return this.useSoftware},t.flush=function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var i,r,n,s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(n=(r=(i=s).byteLength)&&new DataView(i.buffer).getUint8(r-1))?i.slice(0,r-n):i:s},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,i,r){var n=this;return this.useSoftware?new Promise((function(s,a){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);n.softwareDecrypt(o,t,i,r);var l=n.flush();l?s(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)},t.softwareDecrypt=function(e,t,i,r){var n=this.currentIV,s=this.currentResult,a=this.remainderData;if(0!==r||16!==t.byteLength)return $.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;n&&(i=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Mt),l.expandKey(t);var h=s;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null},t.webCryptoDecrypt=function(e,t,i,r){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Ot(this.subtle,t,r)}return this.fastAesKey.expandKey().then((function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new Ct(n.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(s){return $.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+s.name+": "+s.message),n.onWebCryptoError(e,t,i,r)}))},t.onWebCryptoError=function(e,t,i,r){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);var s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")},t.getValidChunk=function(e){var t=e,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t},t.logOnce=function(e){this.logEnabled&&($.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),Ft=Math.pow(2,17),Nt=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t){var i=this,r=e.url;if(!r)return Promise.reject(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();var n=this.config,s=n.fLoader,a=n.loader;return new Promise((function(o,l){if(i.loader&&i.loader.destroy(),e.gap){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void l(Ut(e));e.gap=!1}var h=i.loader=s?new s(n):new a(n),u=Bt(e);e.loader=h;var d=St(n.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Ft};e.stats=h.stats;var g={onSuccess:function(t,r,n,s){i.resetLoader(e,h);var a=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:s})},onError:function(t,n,s,a){i.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:c({url:r,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:s,stats:a}))},onAbort:function(t,r,n){i.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,r,n){i.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:t}))}};t&&(g.onProgress=function(i,r,n,s){return t({frag:e,part:null,payload:n,networkDetails:s})}),h.load(u,f,g)}))},t.loadPart=function(e,t,i){var r=this;this.abort();var n=this.config,s=n.fLoader,a=n.loader;return new Promise((function(o,l){if(r.loader&&r.loader.destroy(),e.gap||t.gap)l(Ut(e,t));else{var h=r.loader=s?new s(n):new a(n),u=Bt(e,t);e.loader=h;var d=St(n.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ft};t.stats=h.stats,h.load(u,f,{onSuccess:function(n,s,a,l){r.resetLoader(e,h),r.updateStatsFromPart(e,t);var u={frag:e,part:t,payload:n.data,networkDetails:l};i(u),o(u)},onError:function(i,n,s,a){r.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:c({url:u.url,data:void 0},i),error:new Error("HTTP Error "+i.code+" "+i.text),networkDetails:s,stats:a}))},onAbort:function(i,n,s){e.stats.aborted=t.stats.aborted,r.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:function(i,n,s){r.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:s,stats:i}))}})}}))},t.updateStatsFromPart=function(e,t){var i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){var s=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/n),s),o=(s-a)*Math.round(i.loaded/a);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,h=r.loading;l.start?l.first+=h.first-h.start:(l.start=h.start,l.first=h.first),l.end=h.end},t.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function Bt(e,t){void 0===t&&(t=null);var i,r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(_(s)&&_(a)){var o,l=s,h=a;if("initSegment"===e.sn&&("AES-128"===(i=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===i)){var u=a-s;u%16&&(h=a+(16-u%16)),0!==s&&(n.resetIV=!0,l=s-16)}n.rangeStart=l,n.rangeEnd=h}return n}function Ut(e,t){var i=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),r={type:I.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Gt(r)}var Gt=function(e){function t(t){var i;return(i=e.call(this,t.error.message)||this).data=void 0,i.data=t,i}return h(t,e),t}(p(Error)),Ht=function(e){function t(t,i){var r;return(r=e.call(this,t,i)||this)._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(r),r}h(t,e);var i=t.prototype;return i.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},i.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},i.onHandlerDestroyed=function(){},i.hasInterval=function(){return!!this._tickInterval},i.hasNextTick=function(){return!!this._tickTimer},i.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},i.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},i.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},i.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},i.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},i.doTick=function(){},t}(B),Vt=function(e,t,i,r,n,s){void 0===r&&(r=0),void 0===n&&(n=-1),void 0===s&&(s=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=s},Kt={length:0,start:function(){return 0},end:function(){return 0}},Wt=function(){function e(){}return e.isBuffered=function(t,i){if(t)for(var r=e.getBuffered(t),n=r.length;n--;)if(i>=r.start(n)&&i<=r.end(n))return!0;return!1},e.bufferedRanges=function(t){if(t){var i=e.getBuffered(t);return e.timeRangesToArray(i)}return[]},e.timeRangesToArray=function(e){for(var t=[],i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t},e.bufferInfo=function(t,i,r){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,i,r)}return{len:0,start:i,end:i,bufferedIndex:-1}},e.bufferedInfo=function(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var r=-1,n=[];if(i)for(var s=0;s<e.length;s++){t>=e[s].start&&t<=e[s].end&&(r=s);var a=n.length;if(a){var o=n[a-1].end;e[s].start-o<i?e[s].end>o&&(n[a-1].end=e[s].end):n.push(e[s])}else n.push(e[s])}else n=e;for(var l,h=0,u=t,d=t,c=0;c<n.length;c++){var f=n[c].start,g=n[c].end;if(-1===r&&t>=f&&t<=g&&(r=c),t+i>=f&&t<g)u=f,h=(d=g)-t;else if(t+i<f){l=f;break}}return{len:h,start:u||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:r}},e.getBuffered=function(e){try{return e.buffered||Kt}catch(e){return $.log("failed to get media.buffered",e),Kt}},e}(),$t=/\{\$([a-zA-Z0-9-_]+)\}/g;function qt(e){return $t.test(e)}function jt(e,t){if(null!==e.variableList||e.hasVariableRefs){var i=e.variableList;return t.replace($t,(function(t){var r=t.substring(2,t.length-1),n=null==i?void 0:i[r];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+r+'"')),t):n}))}return t}function Yt(e,t,i){var r,n,s=e.variableList;if(s||(e.variableList=s={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{var a=new self.URL(i).searchParams;if(!a.has(r))throw new Error('"'+r+'" does not match any query parameter in URI: "'+i+'"');n=a.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+t.message))}}else r=t.NAME,n=t.VALUE;r in s?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+r+'"')):s[r]=n||""}function zt(e,t,i){var r=t.IMPORT;if(i&&r in i){var n=e.variableList;n||(e.variableList=n={}),n[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+r+'"'))}var Xt=/^(\d+)x(\d+)$/,Qt=/(.+?)=(".*?"|.*?)(?:,|$)/g,Jt=function(){function e(t,i){"string"==typeof t&&(t=e.parseAttrList(t,i)),o(this,t)}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var i=new Uint8Array(t.length/2),r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(2*r,2*r+2),16);return i}return null},t.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var i=this[e];return i?parseFloat(i):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((function(e,t){return e[t.toLowerCase()]=!0,e}),t)},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=Xt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var i,r={};for(Qt.lastIndex=0;null!==(i=Qt.exec(e));){var n=i[1].trim(),s=i[2],a=0===s.indexOf('"')&&s.lastIndexOf('"')===s.length-1,o=!1;if(a)s=s.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))s=jt(t,s);else if(!o&&!a)switch(n){case"CLOSED-CAPTIONS":if("NONE"===s)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":$.warn(e+": attribute "+n+" is missing quotes")}r[n]=s}return r},n(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function Zt(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var ei=n((function(e,t,i){var r;if(void 0===i&&(i=0),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:i,t){var n=t.attr;for(var s in n)if(Object.prototype.hasOwnProperty.call(e,s)&&e[s]!==n[s]){$.warn('DATERANGE tag attribute: "'+s+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=s;break}e=o(new Jt({}),n,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 a=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);_(a.getTime())&&(this._endDate=a)}}),[{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?($.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)}}]),ti=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,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1},n(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 i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function ii(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function ri(e){switch(e){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw new Error("invalid full segment method "+e)}}function ni(e){return Uint8Array.from(atob(e),(function(e){return e.charCodeAt(0)}))}function si(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}var ai="undefined"!=typeof self?self:void 0,oi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},li="org.w3.clearkey",hi="com.apple.streamingkeydelivery",ui="com.microsoft.playready",di="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function ci(e){switch(e){case hi:return oi.FAIRPLAY;case ui:return oi.PLAYREADY;case di:return oi.WIDEVINE;case li:return oi.CLEARKEY}}function fi(e){return"edef8ba979d64acea3c827dcd51d21ed"===e?oi.WIDEVINE:"9a04f07998404286ab92e65be0885f95"===e?oi.PLAYREADY:"1077efecc0b24d02ace33c1e52e2fb4b"===e||"e2719d58a985b3c9781ab030af78d30e"===e?oi.CLEARKEY:void 0}function gi(e){switch(e){case oi.FAIRPLAY:return hi;case oi.PLAYREADY:return ui;case oi.WIDEVINE:return di;case oi.CLEARKEY:return li}}function pi(e){var t=e.drmSystems,i=e.widevineLicenseUrl,r=t?[oi.FAIRPLAY,oi.WIDEVINE,oi.PLAYREADY,oi.CLEARKEY].filter((function(e){return!!t[e]})):[];return!r[oi.WIDEVINE]&&i&&r.push(oi.WIDEVINE),r}var vi,mi=null!=ai&&null!=(vi=ai.navigator)&&vi.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function yi(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){var s=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(s){var a=ni(s).subarray(0,16);return function(e){var t=function(e,t,i){var r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(a),a}}return null}var Ei={},Si=function(){function e(e,t,i,r,n){void 0===r&&(r=[1]),void 0===n&&(n=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!ii(e)}e.clearKeyUriToKeyIdMap=function(){Ei={}};var t=e.prototype;return t.isSupported=function(){if(this.method){if(ii(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case hi:case di:case ui:case li:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},t.getDecryptData=function(t){if(!this.encrypted||!this.uri)return null;if(ii(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&($.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0);var i=function(e){for(var t=new Uint8Array(16),i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(t);return new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}var r=function(e){var t,i,r=e.split(":"),n=null;if("data"===r[0]&&2===r.length){var s=r[1].split(";"),a=s[s.length-1].split(",");if(2===a.length){var o="base64"===a[0],l=a[1];o?(s.splice(-1,1),n=ni(l)):(t=si(l).subarray(0,16),(i=new Uint8Array(16)).set(t,16-t.length),n=i)}}return n}(this.uri);if(r)switch(this.keyFormat){case di:this.pssh=r,r.length>=22&&(this.keyId=r.subarray(r.length-22,r.length-6));break;case ui:var n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");var r,n;r=new Uint8Array,n=new Uint8Array;var s=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(s.buffer).setUint32(0,i.byteLength,!1),function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var n=i.length,s=8,a=n;a--;)s+=i[a].byteLength;var o=new Uint8Array(s);for(o[0]=s>>24&255,o[1]=s>>16&255,o[2]=s>>8&255,o[3]=255&s,o.set(e,4),a=0,s=8;a<n;a++)o.set(i[a],s),s+=i[a].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,s,i||new Uint8Array)}(n,0,r),this.keyId=yi(r);break;default:var s=r.subarray(0,16);if(16!==s.length){var a=new Uint8Array(16);a.set(s,16-s.length),s=a}this.keyId=s}if(!this.keyId||16!==this.keyId.byteLength){var o=Ei[this.uri];if(!o){var l=Object.keys(Ei).length%Number.MAX_SAFE_INTEGER;o=new Uint8Array(16),new DataView(o.buffer,12,4).setUint32(0,l),Ei[this.uri]=o}this.keyId=o}return this},e}(),Ti=/#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,Li=/#EXT-X-MEDIA:(.*)/g,_i=/^#EXT(?:INF|-X-TARGETDURATION):/m,bi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ai=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("|")),Ii=function(){function e(){}return e.findGroup=function(e,t){for(var i=0;i<e.length;i++){var r=e[i];if(r.id===t)return r}},e.resolve=function(e,t){return L.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.isMediaPlaylist=function(e){return _i.test(e)},e.parseMasterPlaylist=function(t,i){var r,n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:qt(t)},s=[];for(Ti.lastIndex=0;null!=(r=Ti.exec(t));)if(r[1]){var a,o=new Jt(r[1],n),l=jt(n,r[2]),h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,i)},u=o.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),wi(o.CODECS,h);var d=o["SUPPLEMENTAL-CODECS"];d&&(h.supplemental={},wi(d,h.supplemental)),null!=(a=h.unknownCodecs)&&a.length||s.push(h),n.levels.push(h)}else if(r[3]){var c=r[3],f=r[4];switch(c){case"SESSION-DATA":var g=new Jt(f,n),p=g["DATA-ID"];p&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[p]=g);break;case"SESSION-KEY":var v=ki(f,i,n);v.encrypted&&v.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(v)):$.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+f+'"');break;case"DEFINE":Yt(n,new Jt(f,n),i);break;case"CONTENT-STEERING":var m=new Jt(f,n);n.contentSteering={uri:e.resolve(m["SERVER-URI"],i),pathwayId:m["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Di(f)}}var y=s.length>0&&s.length<n.levels.length;return n.levels=y?s:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n},e.parseMasterPlaylistMedia=function(t,i,r){var n,s={},a=r.levels,o={AUDIO:a.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),SUBTITLES:a.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),"CLOSED-CAPTIONS":[]},l=0;for(Li.lastIndex=0;null!==(n=Li.exec(t));){var h=new Jt(n[1],r),u=h.TYPE;if(u){var d=o[u],c=s[u]||[];s[u]=c;var f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],p=h.CHANNELS,v=h.CHARACTERISTICS,m=h["INSTREAM-ID"],y={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:u,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?e.resolve(h.URI,i):""};if(g&&(y.assocLang=g),p&&(y.channels=p),v&&(y.characteristics=v),m&&(y.instreamId=m),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Ci(y,E,"audioCodec"),Ci(y,E,"textCodec")}c.push(y)}}return s},e.parseLevelPlaylist=function(e,t,i,r,n,s){var a,l,h,u,d,c={url:t},f=new ti(t),g=f.fragments,p=[],v=null,m=0,y=0,E=0,S=0,T=0,L=null,b=new ie(r,c),A=-1,I=!1,R=null;if(bi.lastIndex=0,f.m3u8=e,f.hasVariableRefs=qt(e),"#EXTM3U"!==(null==(a=bi.exec(e))?void 0:a[0]))return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;null!==(l=bi.exec(e));){I&&(I=!1,(b=new ie(r,c)).playlistOffset=E,b.start=E,b.sn=m,b.cc=S,T&&(b.bitrate=T),b.level=i,v&&(b.initSegment=v,v.rawProgramDateTime&&(b.rawProgramDateTime=v.rawProgramDateTime,v.rawProgramDateTime=null),R&&(b.setByteRange(R),R=null)));var P=l[1];if(P){b.duration=parseFloat(P);var k=(" "+l[2]).slice(1);b.title=k||null,b.tagList.push(k?["INF",P,k]:["INF",P])}else if(l[3]){if(_(b.duration)){b.playlistOffset=E,b.start=E,u&&xi(b,u,f),b.sn=m,b.level=i,b.cc=S,g.push(b);var D=(" "+l[3]).slice(1);b.relurl=jt(f,D),Mi(b,L,p),L=b,E+=b.duration,m++,y=0,I=!0}}else{if(!(l=l[0].match(Ai))){$.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);var w=(" "+l[h]).slice(1),C=(" "+l[h+1]).slice(1),M=l[h+2]?(" "+l[h+2]).slice(1):null;switch(w){case"BYTERANGE":L?b.setByteRange(C,L):b.setByteRange(C);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=C,b.tagList.push(["PROGRAM-DATE-TIME",C]),-1===A&&(A=g.length);break;case"PLAYLIST-TYPE":f.type&&Fi(f,w,l),f.type=C.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?Fi(f,w,l):g.length>0&&Ni(f,w,l),m=f.startSN=parseInt(C);break;case"SKIP":f.skippedSegments&&Fi(f,w,l);var O=new Jt(C,f),x=O.decimalInteger("SKIPPED-SEGMENTS");if(_(x)){f.skippedSegments+=x;for(var F=x;F--;)g.push(null);m+=x}var N=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");N&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(N.split("\t")));break;case"TARGETDURATION":0!==f.targetduration&&Fi(f,w,l),f.targetduration=Math.max(parseInt(C),1);break;case"VERSION":null!==f.version&&Fi(f,w,l),f.version=parseInt(C);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":f.live||Fi(f,w,l),f.live=!1;break;case"#":(C||M)&&b.tagList.push(M?[C,M]:[C]);break;case"DISCONTINUITY":S++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([w]);break;case"BITRATE":b.tagList.push([w,C]),T=1e3*parseInt(C),_(T)?b.bitrate=T:T=0;break;case"DATERANGE":var B=new Jt(C,f),U=new ei(B,f.dateRanges[B.ID],f.dateRangeTagCount);f.dateRangeTagCount++,U.isValid||f.skippedSegments?f.dateRanges[U.id]=U:$.warn('Ignoring invalid DATERANGE tag: "'+C+'"'),b.tagList.push(["EXT-X-DATERANGE",C]);break;case"DEFINE":var G=new Jt(C,f);"IMPORT"in G?zt(f,G,s):Yt(f,G,t);break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?Fi(f,w,l):g.length>0&&Ni(f,w,l),f.startCC=S=parseInt(C);break;case"KEY":var H=ki(C,t,f);if(H.isSupported()){if("NONE"===H.method){u=void 0;break}u||(u={}),u[H.keyFormat]&&(u=o({},u)),u[H.keyFormat]=H}else $.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+C+'"');break;case"START":f.startTimeOffset=Di(C);break;case"MAP":var V=new Jt(C,f);if(b.duration){var K=new ie(r,c);Oi(K,V,i,u),v=K,b.initSegment=v,v.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=v.rawProgramDateTime)}else{var W=b.byteRangeEndOffset;if(W){var q=b.byteRangeStartOffset;R=W-q+"@"+q}else R=null;Oi(b,V,i,u),v=b,I=!0}v.cc=S;break;case"SERVER-CONTROL":d&&Fi(f,w,l),d=new Jt(C),f.canBlockReload=d.bool("CAN-BLOCK-RELOAD"),f.canSkipUntil=d.optionalFloat("CAN-SKIP-UNTIL",0),f.canSkipDateRanges=f.canSkipUntil>0&&d.bool("CAN-SKIP-DATERANGES"),f.partHoldBack=d.optionalFloat("PART-HOLD-BACK",0),f.holdBack=d.optionalFloat("HOLD-BACK",0);break;case"PART-INF":f.partTarget&&Fi(f,w,l);var j=new Jt(C);f.partTarget=j.decimalFloatingPoint("PART-TARGET");break;case"PART":var Y=f.partList;Y||(Y=f.partList=[]);var z=y>0?Y[Y.length-1]:void 0,X=y++,Q=new Jt(C,f),J=new re(Q,b,c,X,z);Y.push(J),b.duration+=J.duration;break;case"PRELOAD-HINT":var Z=new Jt(C,f);f.preloadHint=Z;break;case"RENDITION-REPORT":var ee=new Jt(C,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(ee);break;default:$.warn("line parsed but not handled: "+l)}}}L&&!L.relurl?(g.pop(),E-=L.duration,f.partList&&(f.fragmentHint=L)):f.partList&&(Mi(b,L,p),b.cc=S,f.fragmentHint=b,u&&xi(b,u,f)),f.targetduration||(f.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));var te=g.length,ne=g[0],se=g[te-1];if((E+=f.skippedSegments*f.targetduration)>0&&te&&se){f.averagetargetduration=E/te;var ae=se.sn;f.endSN="initSegment"!==ae?ae:0,f.live||(se.endList=!0),ne&&void 0===f.startCC&&(f.startCC=ne.cc),A>0&&(function(e,t){for(var i=e[t],r=t;r--;){var n=e[r];if(!n)return;n.programDateTime=i.programDateTime-1e3*n.duration,i=n}}(g,A),ne&&p.unshift(ne))}else f.endSN=0,f.startCC=0;return f.fragmentHint&&(E+=f.fragmentHint.duration),f.totalduration=E,p.length&&f.dateRangeTagCount&&ne&&Ri(p,f),f.endCC=S,f},e}();function Ri(e,t){for(var i=e.length,r=e[i-1],n=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),a=s.length;a--;){var o=t.dateRanges[s[a]],l=o.startDate.getTime();o.tagAnchor=r.ref;for(var h=i;h--;){var u=Pi(t,l,e,h,n);if(-1!==u){o.tagAnchor=t.fragments[u].ref;break}}}}function Pi(e,t,i,r,n){var s=i[r];if(s){var a,o=s.programDateTime;if((t>=o||0===r)&&t<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||n)-s.start)){var l=i[r].sn-e.startSN,h=e.fragments;if(h.length>i.length)for(var u=(i[r+1]||h[h.length-1]).sn-e.startSN;u>l;u--){var d=h[u].programDateTime;if(t>=d&&t<d+1e3*h[u].duration)return u}return l}}return-1}function ki(e,t,i){var r,n,s=new Jt(e,i),a=null!=(r=s.METHOD)?r:"",o=s.URI,l=s.hexadecimalInteger("IV"),h=s.KEYFORMATVERSIONS,u=null!=(n=s.KEYFORMAT)?n:"identity";o&&s.IV&&!l&&$.error("Invalid IV: "+s.IV);var d=o?Ii.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Si(a,d,u,c,l)}function Di(e){var t=new Jt(e).decimalFloatingPoint("TIME-OFFSET");return _(t)?t:null}function wi(e,t){var i=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var r=i.filter((function(t){return Me(t,e)}));r.length&&(t[e+"Codec"]=r.map((function(e){return e.split("/")[0]})).join(","),i=i.filter((function(e){return-1===r.indexOf(e)})))})),t.unknownCodecs=i}function Ci(e,t,i){var r=t[i];r&&(e[i]=r)}function Mi(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Oi(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function xi(e,t,i){e.levelkeys=t;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||r.push(e)}function Fi(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must not appear more than once ("+i[0]+")")}function Ni(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must appear before the first Media Segment ("+i[0]+")")}function Bi(e,t){var i=t.startPTS;if(_(i)){var r,n=0;t.sn>e.sn?(n=i-e.start,r=e):(n=e.start-i,r=t),r.duration!==n&&r.setDuration(n)}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 Ui(e,t,i,r,n,s){r-i<=0&&($.warn("Fragment should have a positive duration",t),r=i+t.duration,s=n+t.duration);var a=i,o=r,l=t.startPTS,h=t.endPTS;if(_(l)){var u=Math.abs(l-i);_(t.deltaPTS)?t.deltaPTS=Math.max(u,t.deltaPTS):t.deltaPTS=u,a=Math.max(i,l),i=Math.min(i,l),n=Math.min(n,t.startDTS),o=Math.min(r,h),r=Math.max(r,h),s=Math.max(s,t.endDTS)}var d=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=a,t.startDTS=n,t.endPTS=r,t.minEndPTS=o,t.endDTS=s;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--)Bi(p[c],p[c-1]);for(c=g;c<p.length-1;c++)Bi(p[c],p[c+1]);return e.fragmentHint&&Bi(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function Gi(e,t){if(e!==t){for(var i,r=null,n=e.fragments,s=n.length-1;s>=0;s--){var a=n[s].initSegment;if(a){r=a;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){for(var r=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=n;h<=s;h++){var u=l[a+h],d=o[h];if(r&&!d&&u&&(d=t.fragments[h]=u),u&&d){if(i(u,d,h,o),u.url&&u.url!==d.url)return void(t.playlistParsingError=Hi("media sequence mismatch "+d.sn+":",e,t,0,d));if(u.cc!==d.cc)return void(t.playlistParsingError=Hi("discontinuity sequence mismatch ("+u.cc+"!="+d.cc+")",e,t,0,d))}}}(e,t,(function(n,s,a,o){if(!t.startCC&&s.cc!==n.cc){for(var l,h,u=n.cc-s.cc,d=a;d<o.length;d++)o[d].cc+=u;t.startCC=null!=(l=null==(h=$i(e,t.startSN-1))?void 0:h.cc)?l:o[0].cc,t.endCC=o[o.length-1].cc}_(n.startPTS)&&_(n.endPTS)&&(s.setStart(s.startPTS=n.startPTS),s.startDTS=n.startDTS,s.maxStartPTS=n.maxStartPTS,s.endPTS=n.endPTS,s.endDTS=n.endDTS,s.minEndPTS=n.minEndPTS,s.setDuration(n.endPTS-n.startPTS),s.duration&&(i=s),t.PTSKnown=t.alignedSliding=!0),n.hasStreams&&(s.elementaryStreams=n.elementaryStreams),s.loader=n.loader,n.hasStats&&(s.stats=n.stats),n.initSegment&&(s.initSegment=n.initSegment,r=n.initSegment)}));var l=t.fragments,h=t.fragmentHint?l.concat(t.fragmentHint):l;if(r&&h.forEach((function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)})),t.skippedSegments)if(t.deltaUpdateFailed=l.some((function(e){return!e})),t.deltaUpdateFailed){$.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 i=t.dateRanges,r=t.recentlyRemovedDateranges,n=o({},e);r&&r.forEach((function(e){delete n[e]}));var s=Object.keys(n).length;return s&&Object.keys(i).forEach((function(e){var t=n[e],r=new ei(i[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=s)):$.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+it(i[e].attr)+'"')})),n}(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&&Mi(h[c],h[c-1],d);Ri(d,t)}!function(e,t,i){if(e&&t)for(var r=0,n=0,s=e.length;n<=s;n++){var a=e[n],o=t[n+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):r--}}(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),i?Ui(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):Vi(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 Hi(e,t,i,r,n){return new Error(e+" "+n.url+"\nPlaylist starting @"+t.startSN+"\n"+t.m3u8+"\n\nPlaylist starting @"+i.startSN+"\n"+i.m3u8)}function Vi(e,t,i){void 0===i&&(i=!0);var r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,s=r>=0,a=0;if(s&&r<n.length)a=n[r].start;else if(s&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(s&&i)a=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}Ki(t,a)}function Ki(e,t){if(t){for(var i=e.fragments,r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Wi(e,t){void 0===t&&(t=1/0);var i=1e3*e.targetduration;if(e.updated){var r=e.fragments;if(r.length&&4*i>t){var n=1e3*r[r.length-1].duration;n<i&&(i=n)}}else i/=2;return Math.round(i)}function $i(e,t,i){if(!e)return null;var r=e.fragments[t-e.startSN];return r||((r=e.fragmentHint)&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null)}function qi(e,t,i){return e?ji(e.partList,t,i):null}function ji(e,t,i){if(e)for(var r=e.length;r--;){var n=e[r];if(n.index===i&&n.fragment.sn===t)return n}return null}function Yi(e){e.forEach((function(e,t){var i;null==(i=e.details)||i.fragments.forEach((function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function zi(e,t){for(var i=0,r=e.length;i<r;i++){var n;if((null==(n=e[i])?void 0:n.cc)===t)return e[i]}return null}function Xi(e,t){if(e){var i=e.start+t;e.start=e.startPTS=i,e.endPTS=i+e.duration}}function Qi(e,t){for(var i=t.fragments,r=0,n=i.length;r<n;r++)Xi(i[r],e);t.fragmentHint&&Xi(t.fragmentHint,e),t.alignedSliding=!0}function Ji(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var i=Math.min(t.endCC,e.endCC),r=zi(t.fragments,i),n=zi(e.fragments,i);r&&n&&($.log("Aligning playlist at start of dicontinuity sequence "+i),Qi(r.start-n.start,e))}}function Zi(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i=e.fragments,r=t.fragments;if(i.length&&r.length){var n,s,a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(n=zi(r,a),s=zi(i,a)),n&&s||(s=zi(i,(n=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.length/2)]);var o=n.programDateTime,l=s.programDateTime;o&&l&&Qi((l-o)/1e3-(s.start-n.start),e)}}}var er={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},tr=function(e){function t(t,i,r,n,s){var a;return(a=e.call(this,n,t.logger)||this).hls=void 0,a.fragPrevious=null,a.fragCurrent=null,a.fragmentTracker=void 0,a.transmuxer=null,a._state=er.STOPPED,a.playlistType=void 0,a.media=null,a.mediaBuffer=null,a.config=void 0,a.bitrateTest=!1,a.lastCurrentTime=0,a.nextLoadPosition=0,a.startPosition=0,a.startTimeOffset=null,a.retryDate=0,a.levels=null,a.fragmentLoader=void 0,a.keyLoader=void 0,a.levelLastLoaded=null,a.startFragRequested=!1,a.decrypter=void 0,a.initPTS=[],a.buffering=!0,a.loadingParts=!1,a.loopSn=void 0,a.onMediaSeeking=function(){var e=a,t=e.config,i=e.fragCurrent,r=e.media,n=e.mediaBuffer,s=e.state,o=r?r.currentTime:0,l=Wt.bufferInfo(n||r,o,t.maxBufferHole);if(a.log("media seeking to "+(_(o)?o.toFixed(3):o)+", state: "+s),a.state===er.ENDED)a.resetLoadingState();else if(i){var h=t.maxFragLookUpTolerance,u=i.start-h,d=i.start+i.duration+h;if(!l.len||d<l.start||u>l.end){var c=o>d;(o<u||c)&&(c&&i.loader&&(a.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),i.abortRequests(),a.resetLoadingState()),a.fragPrevious=null)}}if(r&&(a.fragmentTracker.removeFragmentsInRange(o,1/0,a.playlistType,!0),o>a.lastCurrentTime&&(a.lastCurrentTime=o),!a.loadingParts)){var 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=s,a.hls=t,a.fragmentLoader=new Nt(t.config),a.keyLoader=r,a.fragmentTracker=i,a.config=t.config,a.decrypter=new xt(t.config),a}h(t,e);var i=t.prototype;return i.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)},i.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)},i.doTick=function(){this.onTickEnd()},i.onTickEnd=function(){},i.startLoad=function(e){},i.stopLoad=function(){if(this.state!==er.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=er.STOPPED}},i.pauseBuffering=function(){this.buffering=!1},i.resumeBuffering=function(){this.buffering=!0},i._streamEnded=function(e,t){if(t.live||!this.media)return!1;var i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;var n=e.nextStart;if(n&&n>r&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var a=s[s.length-1];return Wt.isBuffered(this.media,a.start+a.duration/2)}var o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)},i.getLevelDetails=function(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details},i.onMediaAttached=function(e,t){var i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);var r=this.config;this.levels&&r.autoStartLoad&&this.state===er.STOPPED&&this.startLoad(r.startPosition)},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},i.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},i.onError=function(e,t){},i.onManifestLoaded=function(e,t){this.startTimeOffset=t.startTimeOffset},i.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),e.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},i.onHandlerDestroyed=function(){this.state=er.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,e.prototype.onHandlerDestroyed.call(this)},i.loadFragment=function(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)},i._loadFragForPlayback=function(e,t,i){var r=this;this._doFragLoad(e,t,i,(function(e){var t=e.frag;if(r.fragContextChanged(t))return r.warn(t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+r.fragInfo(t,!1,e.part)+") was dropped during download."),void r.fragmentTracker.removeFragment(t);t.stats.chunkCount++,r._handleFragmentLoadProgress(e)})).then((function(e){if(e){var t=r.state,i=e.frag;r.fragContextChanged(i)?(t===er.FRAG_LOADING||!r.fragCurrent&&t===er.PARSING)&&(r.fragmentTracker.removeFragment(i),r.state=er.IDLE):("payload"in e&&(r.log("Loaded "+i.type+" sn: "+i.sn+" of "+r.playlistLabel()+" "+i.level),r.hls.trigger(P.FRAG_LOADED,e)),r._handleFragmentLoadComplete(e))}})).catch((function(t){r.state!==er.STOPPED&&r.state!==er.ERROR&&(r.warn("Frag error: "+((null==t?void 0:t.message)||t)),r.resetFragmentLoading(e))}))},i.clearTrackerIfNeeded=function(e){var t,i=this.fragmentTracker;if(i.getState(e)===At){var r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),s=Math.max(e.duration,n?n.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?e.sn-a.sn:0)||this.reduceMaxBufferLength(s,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===It&&i.removeFragment(e))},i.checkLiveUpdate=function(e){if(e.updated&&!e.live){var t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)},i.waitForLive=function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)},i.flushMainBuffer=function(e,t,i){if(void 0===i&&(i=null),e-t){var r={startOffset:e,endOffset:t,type:i};this.hls.trigger(P.BUFFER_FLUSHING,r)}},i._loadInitSegment=function(e,t){var i=this;this._doFragLoad(e,t).then((function(e){var t=null==e?void 0:e.frag;if(!t||i.fragContextChanged(t)||!i.levels)throw new Error("init load aborted");return e})).then((function(e){var t=i.hls,r=e.frag,n=e.payload,s=r.decryptdata;if(n&&n.byteLength>0&&null!=s&&s.key&&s.iv&&ii(s.method)){var a=self.performance.now();return i.decrypter.decrypt(new Uint8Array(n),s.key.buffer,s.iv.buffer,ri(s.method)).catch((function(e){throw t.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e})).then((function(n){var s=self.performance.now();return t.trigger(P.FRAG_DECRYPTED,{frag:r,payload:n,stats:{tstart:a,tdecrypt:s}}),e.payload=n,i.completeInitSegmentLoad(e)}))}return i.completeInitSegmentLoad(e)})).catch((function(t){i.state!==er.STOPPED&&i.state!==er.ERROR&&(i.warn(t),i.resetFragmentLoading(e))}))},i.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==er.STOPPED&&(this.state=er.IDLE),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()},i.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},i.fragBufferedComplete=function(e,t){var i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+" > buffer:"+(i?function(e){for(var t="",i=e.length,r=0;r<i;r++)t+="["+e.start(r).toFixed(3)+"-"+e.end(r).toFixed(3)+"]";return t}(Wt.getBuffered(i)):"(detached)")+")"),te(e)){var r;if(e.type!==x){var n=e.elementaryStreams;if(!Object.keys(n).some((function(e){return!!n[e]})))return void(this.state=er.IDLE)}var s=null==(r=this.levels)?void 0:r[e.level];null!=s&&s.fragmentError&&(this.log("Resetting level fragment error count of "+s.fragmentError+" on frag buffered"),s.fragmentError=0)}this.state=er.IDLE},i._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var i=e.frag,r=e.part,n=e.partsLoaded,s=!n||0===n.length||n.some((function(e){return!e})),a=new Vt(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!s);t.flush(a)}},i._handleFragmentLoadProgress=function(e){},i._doFragLoad=function(e,t,i,r){var n,s=this;void 0===i&&(i=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!=(n=e.decryptdata)&&n.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=er.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!s.fragContextChanged(e.frag))return s.hls.trigger(P.KEY_LOADED,e),s.state===er.KEY_LOADING&&(s.state=er.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(te(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(i=Math.max(e.start,i||0),this.loadingParts&&te(e)){var u=a.partList;if(u&&r){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);var d=this.getNextPart(u,e,i);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(i.toFixed(3))),this.nextLoadPosition=f.start+f.duration,this.state=er.FRAG_LOADING,c=o?o.then((function(i){return!i||s.fragContextChanged(i.frag)?null:s.doFragPartsLoad(e,f,t,r)})).catch((function(e){return s.handleFragLoadError(e)})):this.doFragPartsLoad(e,f,t,r).catch((function(e){return s.handleFragLoadError(e)})),this.hls.trigger(P.FRAG_LOADING,{frag:e,part:f,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}if(te(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+i.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(i.toFixed(3))),_(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=er.FRAG_LOADING;var g,p=this.config.progressive;return g=p&&o?o.then((function(t){return!t||s.fragContextChanged(null==t?void 0:t.frag)?null:s.fragmentLoader.load(e,r)})).catch((function(e){return s.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,p?r:void 0),o]).then((function(e){var t=e[0];return!p&&t&&r&&r(t),t})).catch((function(e){return s.handleFragLoadError(e)})),this.hls.trigger(P.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g},i.doFragPartsLoad=function(e,t,i,r){var n=this;return new Promise((function(s,a){var o,l=[],h=null==(o=i.details)?void 0:o.partList,u=function(t){n.fragmentLoader.loadPart(e,t,r).then((function(r){l[t.index]=r;var a=r.part;n.hls.trigger(P.FRAG_LOADED,r);var o=qi(i.details,e.sn,t.index+1)||ji(h,e.sn,t.index+1);if(!o)return s({frag:e,part:a,partsLoaded:l});u(o)})).catch(a)};u(t)}))},i.handleFragLoadError=function(e){if("data"in e){var t=e.data;e.data&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(P.ERROR,t)}else this.hls.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},i._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===er.PARSING){var i=t.frag,r=t.part,n=t.level,s=self.performance.now();i.stats.parsing.end=s,r&&(r.stats.parsing.end=s);var a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+i.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(i,r,n,e.partial)}else this.fragCurrent||this.state===er.STOPPED||this.state===er.ERROR||(this.state=er.IDLE)},i.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var i,r,n=e.partList[0];if(t>=n.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1},i.getCurrentContext=function(e){var t=this.levels,i=this.fragCurrent,r=e.level,n=e.sn,s=e.part;if(null==t||!t[r])return this.warn("Levels object was unset while buffering fragment "+n+" of "+this.playlistLabel()+" "+r+". The current chunk will not be buffered."),null;var a=t[r],o=a.details,l=s>-1?qi(o,n,s):null,h=l?l.fragment:$i(o,n,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null},i.bufferFragmentData=function(e,t,i,r,n){var s;if(e&&this.state===er.PARSING){var a=e.data1,o=e.data2,l=a;if(a&&o&&(l=be(a,o)),null!=(s=l)&&s.length){var h={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:l};if(this.hls.trigger(P.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}}},i.flushBufferGap=function(e){var t=this.media;if(t)if(Wt.isBuffered(t,t.currentTime)){var i=t.currentTime,r=Wt.bufferInfo(t,i,0),n=e.duration,s=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),a=Math.max(Math.min(e.start-s,r.end-s),i+s);e.start-a>s&&this.flushMainBuffer(a,e.start)}else this.flushMainBuffer(0,e.start)},i.getFwdBufferInfo=function(e,t){var i,r=this.getLoadPosition();if(!_(r))return null;var n=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,n)},i.getFwdBufferInfoAtPos=function(e,t,i,r){var n=Wt.bufferInfo(e,t,r);if(0===n.len&&void 0!==n.nextStart){var s=this.fragmentTracker.getBufferedFrag(t,i);if(s&&(n.nextStart<=s.end||s.gap)){var a=Math.max(Math.min(n.nextStart,s.end)-t,r);return Wt.bufferInfo(e,t,a)}}return n},i.getMaxBufferLength=function(e){var t,i=this.config;return t=e?Math.max(8*i.maxBufferSize/e,i.maxBufferLength):i.maxBufferLength,Math.min(t,i.maxMaxBufferLength)},i.reduceMaxBufferLength=function(e,t){var i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return n>=r&&(i.maxMaxBufferLength=n,this.warn("Reduce max buffer length to "+n+"s"),!0)},i.getAppendedFrag=function(e,t){var i;void 0===t&&(t=M);var r=null==(i=this.fragmentTracker)?void 0:i.getAppendedFrag(e,t);return r&&"fragment"in r?r.fragment:r},i.getNextFragment=function(e,t){var i=t.fragments,r=i.length;if(!r)return null;var n=this.config,s=i[0].start,a=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(r<l)return this.warn("Not enough fragments to start playback (have: "+r+", need: "+l+")"),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<s){var h;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t,i);var u=this.hls.startPosition,d=this.hls.liveSyncPosition,c=o?(-1!==u&&u>=s?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<=s&&(o=i[0]);if(!o){var f=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,f,t)}var g=this.filterReplacedPrimary(o,t);if(!g&&o){var p=o.sn-t.startSN;g=this.filterReplacedPrimary(i[p+1]||null,t)}return this.mapToInitFragWhenRequired(g)},i.isLoopLoading=function(e,t){var i=this.fragmentTracker.getState(e);return(i===Rt||i===It&&!!e.gap)&&this.nextLoadPosition>t},i.getNextFragmentLoopLoading=function(e,t,i,r,n){var s=null;if(e.gap&&(s=this.getNextFragment(this.nextLoadPosition,t))&&!s.gap&&i.nextStart){var a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==a&&i.len+a.len>=n){var o=s.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+r+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,s},i.filterReplacedPrimary=function(e,t){if(!e)return e;if(ir(this.hls.config)&&e.type!==x){var i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){var n=r.event;if(n){if(n.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}var s=null==i?void 0:i.playerQueue;if(s)for(var a=s.length;a--;){var o=s[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e},i.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment},i.getNextPart=function(e,t,i){for(var r=-1,n=!1,s=!0,a=0,o=e.length;a<o;a++){var l=e[a];if(s=s&&!l.independent,r>-1&&i<l.start)break;var h=l.loaded;h?r=-1:(n||l.independent||s)&&l.fragment===t&&(r=a),n=h}return r},i.loadedEndOfParts=function(e,t){var i=e[e.length-1];return i&&t>i.start&&i.loaded},i.getInitialLiveFragment=function(e,t){var i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+i.programDateTime),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!_(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(var r=0;r<e.length;++r){var n=e[r];if(pt(t,i,n))return n}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){var s=t[n-e.startSN];i.cc===s.cc&&(r=s,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=vt(t,i.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn)}}else{var a=this.hls.liveSyncPosition;null!==a&&(r=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r},i.getFragmentAtPosition=function(e,t,i){var r,n,s=this.config,a=this.fragPrevious,o=i.fragments,l=i.endSN,h=i.fragmentHint,u=s.maxFragLookUpTolerance,d=i.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),r=e<t?ft(a,o,e,e<this.lastCurrentTime||e>t-u||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:u):o[o.length-1]){var f=r.sn-i.startSN,g=this.fragmentTracker.getState(r);if((g===Rt||g===It&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!c||d[0].fragment.sn>r.sn||!i.live&&!c)&&a&&r.level===a.level){var p=o[f+1];r=r.sn<l&&this.fragmentTracker.getState(p)!==Rt?p:null}}return r},i.alignPlaylists=function(e,t,i){var r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;var n=e.fragmentStart,s=!t,a=e.alignedSliding&&_(n);if(s||!a&&!n){!function(e,t){e&&(Ji(t,e),!t.alignedSliding&&e&&Zi(t,e),t.alignedSliding||!e||t.skippedSegments||Vi(e,t,!1))}(i,e);var o=e.fragmentStart;return this.log("Live playlist sliding: "+o.toFixed(2)+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" fragments: "+r),o}return n},i.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},i.setStartPosition=function(e,t){var i=this.startPosition;i<t&&(i=-1);var r=this.timelineOffset;if(-1===i){var n=null!==this.startTimeOffset,s=n?this.startTimeOffset:e.startTimeOffset;null!==s&&_(s)?(i=t+s,s<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log("Setting startPosition to "+i+" for start time offset "+s+" found in "+(n?"multivariant":"media")+" playlist"),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge "+i),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r},i.getLoadPosition=function(){var e,t=this.media,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i},i.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&te(e)&&e.stats.aborted&&(this.warn("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},i.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===er.FRAG_LOADING_WAITING_RETRY)||(this.state=er.IDLE)},i.onFragmentOrKeyLoadError=function(e,t){if(t.chunkMeta&&!t.frag){var i=this.getCurrentContext(t.chunkMeta);i&&(t.frag=i.frag)}var r=t.frag;if(r&&r.type===e&&this.levels)if(this.fragContextChanged(r)){var n;this.warn("Frag load error must match current frag to retry "+r.url+" > "+(null==(n=this.fragCurrent)?void 0:n.url))}else{var s=t.details===R.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!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&&te(r)&&!r.endList)this.resetFragmentErrors(e),this.treatAsGap(r),a.resolved=!0;else if((g||p)&&d<c.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);var v=Et(c,d);this.warn("Fragment "+r.sn+" of "+e+" "+r.level+" errored with "+t.details+", retrying loading "+(d+1)+"/"+c.maxNumRetry+" in "+v+"ms"),a.resolved=!0,this.retryDate=self.performance.now()+v,this.state=er.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+")");s||3===l||(a.resolved=!0)}else this.state=2===l?er.WAITING_LEVEL:er.ERROR;this.tickImmediate()}},i.reduceLengthAndFlushBuffer=function(e){if(this.state===er.PARSING||this.state===er.PARSED){var t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);var s=!n;return s&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+i+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),s}return!1},i.resetFragmentErrors=function(e){e===O&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==er.STOPPED&&(this.state=er.IDLE)},i.afterBufferFlushed=function(e,t,i){if(e){var r=Wt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===er.ENDED&&this.resetLoadingState()}},i.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==er.STOPPED&&(this.state=er.IDLE)},i.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}},i.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()},i.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},i.updateLevelTiming=function(e,t,i,r){var n=this,s=i.details;if(s){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 n.warn("Could not parse fragment "+e.sn+" "+a+" duration reliably ("+l+")"),t||!1;var h=r?0:Ui(s,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return n.hls.trigger(P.LEVEL_PTS_UPDATED,{details:s,level:i,drift:h,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(a=this.transmuxer)?void 0:a.error))){var o=new Error("Found no media in fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+" resetting transmuxer to fallback to playlist timing");if(this.warn(o.message),this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+i.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=er.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")},i.playlistLabel=function(){return this.playlistType===M?"level":"track"},i.fragInfo=function(e,t,i){var r,n;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(i?"part":"frag")+":["+(null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN).toFixed(3)+"-"+(null!=(n=t&&!i?e.endPTS:(i||e).end)?n:NaN).toFixed(3)+"]"+(i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):"")},i.treatAsGap=function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)},i.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},i.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},n(t,[{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"primaryPrefetch",get:function(){var e,t;return!(!ir(this.hls.config)||!(null==(e=this.hls.interstitialsManager)||null==(t=e.playingItem)?void 0:t.event))}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}(Ht);function ir(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var rr=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,i=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var i=new Uint8Array(t),r=0,n=0;n<e.length;n++){var s=e[n];i.set(s,r),r+=s.length}return i}(t,i),this.reset(),e):new Uint8Array(0)},t.reset=function(){this.chunks.length=0,this.dataLength=0},e}();function nr(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 sr(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 ar(e,t){var i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,(i|=(127&e[t+2])<<7)|127&e[t+3]}function or(e,t){for(var i=t,r=0;sr(e,t);)r+=10,r+=ar(e,t+6),nr(e,t+10)&&(r+=10),t+=r;if(r>0)return e.subarray(i,i+r)}function lr(e,t){return 255===e[t]&&240==(246&e[t+1])}function hr(e,t){return 1&e[t+1]?7:9}function ur(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function dr(e,t){return t+1<e.length&&lr(e,t)}function cr(e,t){if(dr(e,t)){var i=hr(e,t);if(t+i>=e.length)return!1;var r=ur(e,t);if(r<=i)return!1;var n=t+r;return n===e.length||dr(e,n)}return!1}function fr(e,t,i,r,n){if(!e.samplerate){var s=function(e,t,i,r){var n=t[i+2],s=n>>2&15;if(!(s>12)){var a=1+(n>>6&3),o=t[i+3]>>6&3|(1&n)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][s],u=s;5!==a&&29!==a||(u-=3);var d=[a<<3|(14&u)>>1,(1&u)<<7|o<<3];return $.log("manifest codec:"+r+", parsed codec:"+l+", channels:"+o+", rate:"+h+" (ADTS object type:"+a+" sampling index:"+s+")"),{config:d,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:r}}var c=new Error("invalid ADTS sampling index:"+s);e.emit(P.ERROR,P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}(t,i,r,n);if(!s)return;o(e,s)}}function gr(e){return 9216e4/e}function pr(e,t,i,r,n){var s,a=r+n*gr(e.samplerate),o=function(e,t){var i=hr(e,t);if(t+i<=e.length){var r=ur(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(o){var l=o.frameLength,h=o.headerLength,u=h+l,d=Math.max(0,i+u-t.length);d?(s=new Uint8Array(u-h)).set(t.subarray(i+h,t.length),0):s=t.subarray(i+h,i+u);var c={unit:s,pts:a};return d||e.samples.push(c),{sample:c,length:u,missing:d}}var f=t.length-i;return(s=new Uint8Array(f)).set(t.subarray(i,t.length),0),{sample:{unit:s,pts:a},length:f,missing:-1}}function vr(e,t){return sr(e,t)&&ar(e,t+6)+10<=e.length-t}function mr(e,t){if(e<0)return-mr(-e,t);var i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){var r=Math.floor(e*i);return(r%2==0?r:r+1)/i}return Math.round(e*i)/i}function yr(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1/0),function(e,t,i,r){var n=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),s=1;"BYTES_PER_ELEMENT"in r&&(s=r.BYTES_PER_ELEMENT);var a,o=(a=e)&&a.buffer instanceof ArrayBuffer&&void 0!==a.byteLength&&void 0!==a.byteOffset?e.byteOffset:0,l=(o+e.byteLength)/s,h=(o+t)/s,u=Math.floor(Math.max(0,Math.min(h,l)));return new r(n,u,Math.floor(Math.min(u+Math.max(i,0),l))-u)}(e,t,i,Uint8Array)}function Er(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Y(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,i=Y(e.data.subarray(t),!0);t+=i.length+1;var r=Y(e.data.subarray(t));return{key:e.type,info:i,data:r}}var n=Y(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?function(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var i=e.data.subarray(1).indexOf(0);if(-1!==i){var r=Y(yr(e.data,1,i)),n=e.data[2+i],s=e.data.subarray(3+i).indexOf(0);if(-1!==s){var a,o=Y(yr(e.data,3+i,s));return a="--\x3e"===r?Y(yr(e.data,4+i+s)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+s)),t.mimeType=r,t.pictureType=n,t.description=o,t.data=a,t}}}else console.log("Ignore frame with unrecognized character encoding")}(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,i=Y(e.data.subarray(t),!0);t+=i.length+1;var r=Y(e.data.subarray(t));return{key:e.type,info:i,data:r}}var n=Y(e.data.subarray(1));return{key:e.type,info:"",data:n}}}(e)}function Sr(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=ar(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}var Tr=10,Lr=10;function _r(e){for(var t=0,i=[];sr(e,t);){var r=ar(e,t+6);e[t+5]>>6&1&&(t+=Tr);for(var n=(t+=Tr)+r;t+Lr<n;){var s=Sr(e.subarray(t)),a=Er(s);a&&i.push(a),t+=s.size+Tr}nr(e,t)&&(t+=Tr)}return i}function br(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Ar(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Ir(e){for(var t=_r(e),i=0;i<t.length;i++){var r=t[i];if(br(r))return Ar(r)}}var Rr=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 Pr(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 kr=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,i){},t.demux=function(e,t){this.cachedData&&(e=be(this.cachedData,e),this.cachedData=null);var i,r=or(e,0),n=r?r.length:0,s=this._audioTrack,a=this._id3Track,o=r?Ir(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&_(o))&&(this.basePTS=Dr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Rr.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){var h=this.appendFrame(s,e,n);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i=n+=h.length):n=l}else vr(e,n)?(r=or(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Rr.audioId3,duration:Number.POSITIVE_INFINITY}),i=n+=r.length):n++;if(n===l&&i!==l){var u=e.slice(i);this.cachedData?this.cachedData=be(this.cachedData,u):this.cachedData=u}}return{audioTrack:s,videoTrack:Pr(),id3Track:a,textTrack:Pr()}},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},t.flush=function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Pr(),id3Track:this._id3Track,textTrack:Pr()}},t.destroy=function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},e}(),Dr=function(e,t,i){return _(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0)},wr=null,Cr=[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],Mr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Or=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],xr=[0,1,1,4];function Fr(e,t,i,r,n){if(!(i+24>t.length)){var s=Nr(t,i);if(s&&i+s.frameLength<=t.length){var a=r+n*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:t.subarray(i,i+s.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=s.channelCount,e.samplerate=s.sampleRate,e.samples.push(o),{sample:o,length:s.frameLength,missing:0}}}}function Nr(e,t){var i=e[t+1]>>3&3,r=e[t+1]>>1&3,n=e[t+2]>>4&15,s=e[t+2]>>2&3;if(1!==i&&0!==n&&15!==n&&3!==s){var a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Cr[14*(3===i?3-r:3===r?3:4)+n-1],h=Mr[3*(3===i?0:2===i?1:2)+s],u=3===o?1:2,d=Or[i][r],c=xr[r],f=8*d*c,g=Math.floor(d*l/h+a)*c;if(null===wr){var p=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);wr=p?parseInt(p[1]):0}return!!wr&&wr<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:u,frameLength:g,samplesPerFrame:f}}}function Br(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Ur(e,t){return t+1<e.length&&Br(e,t)}function Gr(e,t){if(t+1<e.length&&Br(e,t)){var i=Nr(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);var n=t+r;return n===e.length||Ur(e,n)}return!1}var Hr=function(e){function t(t,i){var r;return(r=e.call(this)||this).observer=void 0,r.config=void 0,r.observer=t,r.config=i,r}h(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,n){e.prototype.resetInitSegment.call(this,t,i,r,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:n,inputTimeScale:9e4,dropped:0}},t.probe=function(e,t){if(!e)return!1;var i=or(e,0),r=(null==i?void 0:i.length)||0;if(Gr(e,r))return!1;for(var n=e.length;r<n;r++)if(cr(e,r))return t.log("ADTS sync word found !"),!0;return!1},i.canParse=function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&lr(e,t)&&ur(e,t)<=e.length-t}(e,t)},i.appendFrame=function(e,t,i){fr(e,this.observer,t,i,e.manifestCodec);var r=pr(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r},t}(kr),Vr=function(e,t){var i=0,r=5;t+=r;for(var n=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);r>0;){a[0]=e[t];var o=Math.min(r,8),l=8-o;s[0]=4278190080>>>24+l<<l,n[0]=(a[0]&s[0])>>l,i=i?i<<o|n[0]:n[0],t+=1,r-=o}return i},Kr=function(e){function t(t){var i;return(i=e.call(this)||this).observer=void 0,i.observer=t,i}h(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,n){e.prototype.resetInitSegment.call(this,t,i,r,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:n,inputTimeScale:9e4,dropped:0}},i.canParse=function(e,t){return t+64<e.length},i.appendFrame=function(e,t,i){var r=Wr(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}},t.probe=function(e){if(!e)return!1;var t=or(e,0);if(!t)return!1;var i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Ir(t)&&Vr(e,i)<16},t}(kr);function Wr(e,t,i,r,n){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;var s=t[i+4]>>6;if(s>=3)return-1;var a=[48e3,44100,32e3][s],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+s];if(i+l>t.length)return-1;var h=t[i+6]>>5,u=0;2===h?u+=2:(1&h&&1!==h&&(u+=2),4&h&&(u+=2));var d=(t[i+6]<<8|t[i+7])>>12-u&1,c=[2,1,2,3,3,4,4,5][h]+d,f=t[i+5]>>3,g=7&t[i+5],p=new Uint8Array([s<<6|f<<1|g>>2,(3&g)<<6|h<<3|d<<2|o>>4,o<<4&224]),v=r+n*(1536/a*9e4),m=t.subarray(i,i+l);return e.config=p,e.channelCount=c,e.samplerate=a,e.samples.push({unit:m,pts:v}),l}var $r=function(e){function t(){return e.apply(this,arguments)||this}h(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,n){e.prototype.resetInitSegment.call(this,t,i,r,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:n,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=or(e,0),i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Ir(t)&&Vr(e,i)<=16)return!1;for(var r=e.length;i<r;i++)if(Gr(e,i))return $.log("MPEG Audio sync word found !"),!0;return!1},i.canParse=function(e,t){return function(e,t){return Br(e,t)&&4<=e.length-t}(e,t)},i.appendFrame=function(e,t,i){if(null!==this.basePTS)return Fr(e,t,i,this.basePTS,this.frameIndex)},t}(kr),qr=/\/emsg[-/]ID3/i,jr=function(){function e(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}var t=e.prototype;return t.resetTimeStamp=function(){},t.resetInitSegment=function(e,t,i,r){var n=this.videoTrack=Pr("video",1),s=this.audioTrack=Pr("audio",1),a=this.txtTrack=Pr("text",1);if(this.id3Track=Pr("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;n.id=h,n.timescale=a.timescale=u,n.codec=d,n.supplemental=c}if(o.audio){var f=o.audio,g=f.id,p=f.timescale,v=f.codec;s.id=g,s.timescale=p,s.codec=v}a.id=oe.text,n.sampleDuration=0,n.duration=s.duration=r}},t.resetContiguity=function(){this.remainderData=null},e.probe=function(e){return function(e){for(var t=e.byteLength,i=0;i<t;){var r=ue(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var i=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=be(this.remainderData,e));var s=function(e){var t={valid:null,remainder:null},i=ge(e,["moof"]);if(i.length<2)return t.remainder=e,t;var r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=s.remainder,r.samples=s.valid||new Uint8Array}else r.samples=i;var a=this.extractID3Track(r,t);return n.samples=Ae(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(t,this.timeOffset);return i.samples=Ae(e,t),{videoTrack:t,audioTrack:Pr(),id3Track:r,textTrack:Pr()}},t.extractID3Track=function(e,t){var i=this,r=this.id3Track;if(e.samples.length){var n=ge(e.samples,["emsg"]);n&&n.forEach((function(e){var n=function(e){var t=e[0],i="",r="",n=0,s=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==le(e.subarray(h,h+1));)i+=le(e.subarray(h,h+1)),h+=1;for(i+=le(e.subarray(h,h+1)),h+=1;"\0"!==le(e.subarray(h,h+1));)r+=le(e.subarray(h,h+1)),h+=1;r+=le(e.subarray(h,h+1)),h+=1,n=ue(e,12),s=ue(e,16),o=ue(e,20),l=ue(e,24),h=28}else if(1===t){n=ue(e,h+=4);var u=ue(e,h+=4),d=ue(e,h+=4);for(h+=4,a=Math.pow(2,32)*u+d,b(a)||(a=Number.MAX_SAFE_INTEGER,$.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=ue(e,h),l=ue(e,h+=4),h+=4;"\0"!==le(e.subarray(h,h+1));)i+=le(e.subarray(h,h+1)),h+=1;for(i+=le(e.subarray(h,h+1)),h+=1;"\0"!==le(e.subarray(h,h+1));)r+=le(e.subarray(h,h+1)),h+=1;r+=le(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(qr.test(n.schemeIdUri)){var s=Yr(n,t),a=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=n.payload;r.samples.push({data:o,len:o.byteLength,dts:s,pts:s,type:Rr.emsg,duration:a})}else if(i.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=Yr(n,t);r.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:Rr.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return r},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0},e}();function Yr(e,t){return _(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var zr=function(){function e(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new xt(t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,0)},t.decryptAacSample=function(e,t,i){var r=this,n=e[t].unit;if(!(n.length<=16)){var s=n.subarray(16,n.length-n.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then((function(s){var a=new Uint8Array(s);n.set(a,16),r.decrypter.isSync()||r.decryptAacSamples(e,t+1,i)}))}},t.decryptAacSamples=function(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,i),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0,n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i},t.getAvcDecryptedUnit=function(e,t){for(var i=new Uint8Array(t),r=0,n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e},t.decryptAvcSample=function(e,t,i,r,n){var s=this,a=ke(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then((function(o){n.data=s.getAvcDecryptedUnit(a,o),s.decrypter.isSync()||s.decryptAvcSamples(e,t,i+1,r)}))},t.decryptAvcSamples=function(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();for(var n=e[t].units;!(i>=n.length);i++){var s=n[i];if(!(s.data.length<=48||1!==s.type&&5!==s.type||(this.decryptAvcSample(e,t,i,r,s),this.decrypter.isSync())))return}}},e}(),Xr=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}},t.getLastNalUnit=function(e){var t,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){var n=r.units;i=n[n.length-1]}return i},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var i=t.samples,r=i.length;if(!r)return void t.dropped++;var n=i[r-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}},t.parseNALu=function(e,t,i){var r,n,s=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<s;)if(r=t[h++],a)if(1!==a)if(r)if(1===r){if(n=h-a-1,u>=0){var c={data:t.subarray(u,n),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)),n>0&&(f.data=be(f.data,t.subarray(0,n)),f.state=0))}h<s?(u=h,d=this.getNALuType(t,h),a=0):a=-1}else a=0;else a=3;else a=r?0:2;else a=r?0:1;if(u>=0&&a>=0){var g={data:t.subarray(u,s),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}(),Qr=function(){function e(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&$.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i},t.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},e}(),Jr=function(e){function t(){return e.apply(this,arguments)||this}h(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var n,s=this,a=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,h;switch(r.type){case 1:var u=!1;n=!0;var d,c=r.data;if(l&&c.length>4){var f=s.readSliceType(c);2!==f&&4!==f&&7!==f&&9!==f||(u=!0)}u&&null!=(d=o)&&d.frame&&!o.key&&(s.pushAccessUnit(o,e),o=s.VideoSample=null),o||(o=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=u;break;case 5:n=!0,null!=(a=o)&&a.frame&&!o.key&&(s.pushAccessUnit(o,e),o=s.VideoSample=null),o||(o=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:n=!0,Pe(r.data,1,i.pts,t.samples);break;case 7:var g,p;n=!0,l=!0;var v=r.data,m=s.readSPS(v);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(g=e.pixelRatio)?void 0:g[0])!==m.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[v];for(var y=v.subarray(1,4),E="avc1.",S=0;S<3;S++){var T=y[S].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:n=!0,e.pps=[r.data];break;case 9:n=!0,e.audFound=!0,null!=(h=o)&&h.frame&&(s.pushAccessUnit(o,e),o=null),o||(o=s.VideoSample=s.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}o&&n&&o.units.push(r)})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},i.getNALuType=function(e,t){return 31&e[t]},i.readSliceType=function(e){var t=new Qr(e);return t.readUByte(),t.readUEG(),t.readUEG()},i.skipScalingList=function(e,t){for(var i=8,r=8,n=0;n<e;n++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r},i.readSPS=function(e){var t,i,r,n=new Qr(e),s=0,a=0,o=0,l=0,h=n.readUByte.bind(n),u=n.readBits.bind(n),d=n.readUEG.bind(n),c=n.readBoolean.bind(n),f=n.skipBits.bind(n),g=n.skipEG.bind(n),p=n.skipUEG.bind(n),v=this.skipScalingList.bind(this);h();var m=h();if(u(5),f(3),h(),p(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),p(),p(),f(1),c())for(i=3!==y?8:12,r=0;r<i;r++)c()&&v(r<6?16:64,n)}p();var E=d();if(0===E)d();else if(1===E)for(f(1),g(),g(),t=d(),r=0;r<t;r++)g();p(),f(1);var S=d(),T=d(),L=u(1);0===L&&f(1),f(1),c()&&(s=d(),a=d(),o=d(),l=d());var _=[1,1];if(c()&&c())switch(h()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:_=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil(16*(S+1)-2*s-2*a),height:(2-L)*(T+1)*16-(L?2:4)*(o+l),pixelRatio:_}},t}(Xr),Zr=function(e){function t(){for(var t,i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return(t=e.call.apply(e,[this].concat(r))||this).initVPS=null,t}h(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var n,s=this,a=this.parseNALu(e,i.data,r),l=this.VideoSample,h=!1;i.data=null,l&&a.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,u;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=s.VideoSample=s.createVideoSample(!1,i.pts,i.dts)),l.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;n=!0,h&&null!=(d=l)&&d.frame&&!l.key&&(s.pushAccessUnit(l,e),l=s.VideoSample=null),l||(l=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:n=!0,null!=(a=l)&&a.frame&&!l.key&&(s.pushAccessUnit(l,e),l=s.VideoSample=null),l||(l=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 39:n=!0,Pe(r.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=o(e.params,s.readVPS(r.data)),s.initVPS=r.data),e.vps=[r.data];break;case 33:if(n=!0,h=!0,void 0===e.vps||e.vps[0]===s.initVPS||void 0===e.sps||s.matchSPS(e.sps[0],r.data)||(s.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var c=s.readSPS(r.data);for(var f in e.width=c.width,e.height=c.height,e.pixelRatio=c.pixelRatio,e.codec=c.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),c.params)e.params[f]=c.params[f]}s.pushParameterSet(e.sps,r.data,e.vps),l||(l=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),l.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];var g=s.readPPS(r.data);for(var p in g)e.params[p]=g[p]}s.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(u=l)&&u.frame&&(s.pushAccessUnit(l,e),l=null),l||(l=s.VideoSample=s.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}l&&n&&l.units.push(r)})),r&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)},i.pushParameterSet=function(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)},i.getNALuType=function(e,t){return(126&e[t])>>>1},i.ebsp2rbsp=function(e){for(var t=new Uint8Array(e.byteLength),i=0,r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)},i.pushAccessUnit=function(t,i){e.prototype.pushAccessUnit.call(this,t,i),this.initVPS&&(this.initVPS=null)},i.readVPS=function(e){var t=new Qr(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}},i.readSPS=function(e){var t=new Qr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var i=t.readBits(3);t.readBoolean();for(var r=t.readBits(2),n=t.readBoolean(),s=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),m=[],y=[],E=0;E<i;E++)m.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(var S=i;S<8;S++)t.readBits(2);for(var T=0;T<i;T++)m[T]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[T]&&t.readUByte();t.readUEG();var L=t.readUEG();3==L&&t.skipBits(1);var _=t.readUEG(),b=t.readUEG(),A=t.readBoolean(),I=0,R=0,P=0,k=0;A&&(I+=t.readUEG(),R+=t.readUEG(),P+=t.readUEG(),k+=t.readUEG());for(var D=t.readUEG(),w=t.readUEG(),C=t.readUEG(),M=t.readBoolean()?0:i;M<=i;M++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(var O=0;O<4;O++)for(var x=0;x<(3===O?2:6);x++)if(t.readBoolean()){var F=Math.min(64,1<<4+(O<<1));O>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var B=t.readUEG(),U=0,G=0;G<B;G++){var H=!1;if(0!==G&&(H=t.readBoolean()),H){G===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var V=0,K=0;K<=U;K++){var W=t.readBoolean(),$=!1;W||($=t.readBoolean()),(W||$)&&V++}U=V}else{var q=t.readUEG(),j=t.readUEG();U=q+j;for(var Y=0;Y<q;Y++)t.readUEG(),t.readBoolean();for(var z=0;z<j;z++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var X=t.readUEG(),Q=0;Q<X;Q++){for(var J=0;J<C+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,ie=!0,re=1,ne=0;t.readBoolean(),t.readBoolean();var se=!1;if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),(se=t.readBoolean())&&(I+=t.readUEG(),R+=t.readUEG(),P+=t.readUEG(),k+=t.readUEG()),t.readBoolean()&&(re=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){var oe=t.readBoolean(),le=t.readBoolean(),he=!1;(oe||le)&&((he=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),he&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=i;ue++){var de=!1;(ie=t.readBoolean())||t.readBoolean()?t.readEG():de=t.readBoolean();var ce=de?1:t.readUEG()+1;if(oe)for(var fe=0;fe<ce;fe++)t.readUEG(),t.readUEG(),he&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(le)for(var ge=0;ge<ce;ge++)t.readUEG(),t.readUEG(),he&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var pe=_,ve=b;if(A||se){var me=1,ye=1;1===L?me=ye=2:2==L&&(me=2),pe=_-me*R-me*I,ve=b-ye*k-ye*P}for(var Ee=r?["A","B","C"][r]:"",Se=a<<24|o<<16|l<<8|h,Te=0,Le=0;Le<32;Le++)Te=(Te|(Se>>Le&1)<<31-Le)>>>0;var _e=Te.toString(16);return 1===s&&"2"===_e&&(_e="6"),{codecString:"hvc1."+Ee+s+"."+_e+"."+(n?"H":"L")+v+".B0",params:{general_tier_flag:n,general_profile_idc:s,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[u,d,c,f,g,p],general_level_idc:v,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:w,min_spatial_segmentation_idc:Z,chroma_format_idc:L,frame_rate:{fixed:ie,fps:ne/re}},width:pe,height:ve,pixelRatio:[ee,te]}},i.readPPS=function(e){var t=new Qr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var i=t.readBoolean(),r=t.readBoolean(),n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}},i.matchSPS=function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)},t}(Xr),en=188,tn=function(){function e(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}e.probe=function(t,i){var r=e.syncOffset(t);return r>0&&i.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},e.syncOffset=function(e){for(var t=e.length,i=Math.min(940,t-en)+1,r=0;r<i;){for(var n=!1,s=-1,a=0,o=r;o<t;o+=en){if(71!==e[o]||t-o!==en&&71!==e[o+en]){if(a)return-1;break}if(a++,-1===s&&0!==(s=o)&&(i=Math.min(s+18612,e.length-en)+1),n||(n=0===rn(e,o)),n&&a>1&&(0===s&&a>2||o+en>i))return s}r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:oe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,i,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=r},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,i=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,i,r,n){var s;void 0===r&&(r=!1),void 0===n&&(n=!1),r||(this.sampleAes=null);var a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,u=a.pid,d=a.pesData,c=o.pid,f=l.pid,g=o.pesData,p=l.pesData,v=null,m=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=be(this.remainderData,t)).length,this.remainderData=null),E<en&&!n)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var S=Math.max(0,e.syncOffset(t));(E-=(E-S)%en)<t.byteLength&&!n&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var T=0,L=S;L<E;L+=en)if(71===t[L]){var _=!!(64&t[L+1]),b=rn(t,L),A=void 0;if((48&t[L+3])>>4>1){if((A=L+5+t[L+4])===L+en)continue}else A=L+4;switch(b){case u:if(_){if(d&&(s=ln(d,this.logger))){if(null===this.videoParser)switch(a.segmentCodec){case"avc":this.videoParser=new Jr;break;case"hevc":this.videoParser=new Zr}null!==this.videoParser&&this.videoParser.parsePES(a,h,s,!1)}d={data:[],size:0}}d&&(d.data.push(t.subarray(A,L+en)),d.size+=L+en-A);break;case c:if(_){if(g&&(s=ln(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s);break;case"ac3":this.parseAC3PES(o,s)}g={data:[],size:0}}g&&(g.data.push(t.subarray(A,L+en)),g.size+=L+en-A);break;case f:_&&(p&&(s=ln(p,this.logger))&&this.parseID3PES(l,s),p={data:[],size:0}),p&&(p.data.push(t.subarray(A,L+en)),p.size+=L+en-A);break;case 0:_&&(A+=t[A]+1),y=this._pmtId=nn(t,A);break;case y:_&&(A+=t[A]+1);var I=sn(t,A,this.typeSupported,r,this.observer,this.logger);(u=I.videoPid)>0&&(a.pid=u,a.segmentCodec=I.segmentVideoCodec),(c=I.audioPid)>0&&(o.pid=c,o.segmentCodec=I.segmentAudioCodec),(f=I.id3Pid)>0&&(l.pid=f),null===v||m||(this.logger.warn("MPEG-TS PMT found at "+L+" after unknown PID '"+v+"'. Backtracking to sync byte @"+S+" to parse all TS packets."),v=null,L=S-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:v=b}}else T++;T>0&&an(this.observer,new Error("Found "+T+" TS packet/s that do not start with 0x47"),void 0,this.logger),a.pesData=d,o.pesData=g,l.pesData=p;var R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return n&&this.extractRemainingSamples(R),R},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,i=e.audioTrack,r=e.videoTrack,n=e.id3Track,s=e.textTrack,a=r.pesData,o=i.pesData,l=n.pesData;if(a&&(t=ln(a,this.logger))){if(null===this.videoParser)switch(r.segmentCodec){case"avc":this.videoParser=new Jr;break;case"hevc":this.videoParser=new Zr}null!==this.videoParser&&(this.videoParser.parsePES(r,s,t,!0),r.pesData=null)}else r.pesData=a;if(o&&(t=ln(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(t=ln(l,this.logger))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l},t.demuxSampleAes=function(e,t,i){var r=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new zr(this.observer,this.config,t);return this.decrypt(r,n)},t.decrypt=function(e,t){return new Promise((function(i){var r=e.audioTrack,n=e.videoTrack;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(function(){n.samples?t.decryptAvcSamples(n.samples,0,0,(function(){i(e)})):i(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(function(){i(e)}))}))},t.destroy=function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0},t.parseAACPES=function(e,t){var i,r,n,s=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),s=a.missing}}for(i=s,r=o.length;i<r-1&&!dr(o,i);i++);if(i!==s){var d,c=i<r-1;if(d=c?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES",an(this.observer,new Error(d),c,this.logger),!c)return}if(fr(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)n=t.pts;else{if(!a)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=gr(e.samplerate);n=a.sample.pts+f}for(var g,p=0;i<r;){if(i+=(g=pr(e,o,i,n,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;i<r-1&&!dr(o,i);i++);}},t.parseMPEGPES=function(e,t){var i=t.data,r=i.length,n=0,s=0,a=t.pts;if(void 0!==a)for(;s<r;)if(Ur(i,s)){var o=Fr(e,i,s,a,n);if(!o)break;s+=o.length,n++}else s++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},t.parseAC3PES=function(e,t){var i=t.data,r=t.pts;if(void 0!==r)for(var n,s=i.length,a=0,o=0;o<s&&(n=Wr(e,i,o,r,a++))>0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var i=o({},t,{type:this._videoTrack?Rr.emsg:Rr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function rn(e,t){return((31&e[t+1])<<8)+e[t+2]}function nn(e,t){return(31&e[t+10])<<8|e[t+11]}function sn(e,t,i,r,n,s){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=rn(e,t),h=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){on("ADTS AAC",s);break}case 15:-1===a.audioPid&&(a.audioPid=l);break;case 21:-1===a.id3Pid&&(a.id3Pid=l);break;case 219:if(!r){on("H.264",s);break}case 27:-1===a.videoPid&&(a.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="mp3"):s.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){on("AC-3",s);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&h>0)for(var u=t+5,d=h;d>2;){106===e[u]&&(!0!==i.ac3?s.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=l,a.segmentAudioCodec="ac3"));var c=e[u+1]+2;u+=c,d-=c}break;case 194:case 135:return an(n,new Error("Unsupported EC-3 in M2TS found"),void 0,s),a;case 36:-1===a.videoPid&&(a.videoPid=l,a.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"))}t+=h+5}return a}function an(e,t,i,r){r.warn("parsing error: "+t.message),e.emit(P.ERROR,P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function on(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function ln(e,t){var i,r,n,s,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===((i=l[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>e.size-6)return null;var h=i[7];192&h&&(s=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?s-(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2)>54e5&&(t.warn(Math.round((s-a)/9e4)+"s delta between PTS and DTS, align them"),s=a):a=s);var u=(n=i[8])+9;if(e.size<=u)return null;e.size-=u;for(var d=new Uint8Array(e.size),c=0,f=l.length;c<f;c++){var g=(i=l[c]).byteLength;if(u){if(u>g){u-=g;continue}i=i.subarray(u),g-=u,u=0}d.set(i,o),o+=g}return r&&(r-=n+3),{data:d,pts:s,dts:a,len:r}}return null}var hn=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}(),un=Math.pow(2,32)-1,dn=function(){function e(){}return e.init=function(){var t;for(t in e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var i=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:i,audio:r};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=s,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,n))},e.box=function(e){for(var t=8,i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];for(var s=r.length,a=s;s--;)t+=r[s].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),s=0,t=8;s<a;s++)o.set(r[s],t),t+=r[s].byteLength;return o},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,i){i*=t;var r=Math.floor(i/(un+1)),n=Math.floor(i%(un+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,i,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,i))},e.moov=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(e.mvex(t)))},e.mvex=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trex(t[i]);return e.box.apply(null,[e.types.mvex].concat(r))},e.mvhd=function(t,i){i*=t;var r=Math.floor(i/(un+1)),n=Math.floor(i%(un+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,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,s)},e.sdtp=function(t){var i,r,n=t.samples||[],s=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,s)},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))},e.avc1=function(t){var i,r,n,s=[],a=[];for(i=0;i<t.sps.length;i++)n=(r=t.sps[i]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)n=(r=t.pps[i]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(r));var o=e.box(e.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,d>>24,d>>16&255,d>>8&255,255&d])))},e.esds=function(e){var t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2].concat(t,[6,1,2]))},e.audioStsd=function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){return e.box(e.types[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))},e.stsd=function(t){var i=t.segmentCodec;if("audio"===t.type){if("aac"===i)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===i&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===i&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===i)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===i&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+i+"/"+t.codec+")")},e.tkhd=function(t){var i=t.id,r=(t.duration||0)*(t.timescale||0),n=t.width||0,s=t.height||0,a=Math.floor(r/(un+1)),o=Math.floor(r%(un+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,s>>8&255,255&s,0,0]))},e.traf=function(t,i){var r=e.sdtp(t),n=t.id,s=Math.floor(i/(un+1)),a=Math.floor(i%(un+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,r.length+16+20+8+16+8+8),r)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var i=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,i){var r,n,s,a,o,l,h=t.samples||[],u=h.length,d=12+16*u,c=new Uint8Array(d);for(i+=8+d,c.set(["video"===t.type?1:0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<u;r++)s=(n=h[r]).duration,a=n.size,o=n.flags,l=n.cts,c.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*r);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var i=e.moov(t);return be(e.FTYP,i)},e.hvc1=function(t){for(var i=t.params,r=[t.vps,t.sps,t.pps],n=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),r.length]),s=n.length,a=0;a<r.length;a+=1){s+=3;for(var o=0;o<r[a].length;o+=1)s+=2+r[a][o].length}var l=new Uint8Array(s);l.set(n,0),s=n.length;for(var h=r.length-1,u=0;u<r.length;u+=1){l.set(new Uint8Array([32+u|(u===h?128:0),0,r[u].length]),s),s+=3;for(var d=0;d<r[u].length;d+=1)l.set(new Uint8Array([r[u][d].length>>8,255&r[u][d].length]),s),s+=2,l.set(r[u][d],s),s+=r[u][d].length}var c=e.box(e.types.hvcC,l),f=t.width,g=t.height,p=t.pixelRatio[0],v=t.pixelRatio[1];return e.box(e.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,255&f,g>>8&255,255&g,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,255&p,v>>24,v>>16&255,v>>8&255,255&v])))},e}();dn.types=void 0,dn.HDLR_TYPES=void 0,dn.STTS=void 0,dn.STSC=void 0,dn.STCO=void 0,dn.STSZ=void 0,dn.VMHD=void 0,dn.SMHD=void 0,dn.STSD=void 0,dn.FTYP=void 0,dn.DINF=void 0;function cn(e,t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);var n=e*t*i;return r?Math.round(n):n}function fn(e,t){return cn(e,1e3,1/9e4,t)}var gn=null,pn=null;function vn(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var mn=function(){function e(e,t,i,r){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=i,this.logger=r,this.ISGenerated=!1,null===gn){var n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);gn=n?parseInt(n[1]):0}if(null===pn){var s=navigator.userAgent.match(/Safari\/(\d+)/i);pn=s?parseInt(s[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,i=e[0].pts,r=e.reduce((function(e,r){var n=r.pts,s=n-e;return s<-4294967296&&(t=!0,s=(n=yn(n,i))-e),s>0?e:n}),i);return t&&this.logger.debug("PTS rollover detected"),r},t.remux=function(e,t,i,r,n,s,a,o){var l,h,u,d,c,f,g=n,p=n,v=e.pid>-1,m=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!v||E)&&(!m||S)||this.ISGenerated||a){if(this.ISGenerated){var T,L,_,b,A=this.videoTrackConfig;(A&&(t.width!==A.width||t.height!==A.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(L=A.pixelRatio)?void 0:L[0])||(null==(_=t.pixelRatio)?void 0:_[1])!==(null==(b=A.pixelRatio)?void 0:b[1]))||!A&&S||null===this.nextAudioPts&&E)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,n,s));var I,R=this.isVideoContiguous,P=-1;if(S&&(P=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!R&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,P>0){this.logger.warn("[mp4-remuxer]: Dropped "+P+" out of "+y+" video samples due to a missing keyframe");var k=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,I=p+=(t.samples[0].pts-k)/t.inputTimeScale}else-1===P&&(this.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),w=(yn(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,w),p+=Math.max(0,-w)}if(E){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,s)),h=this.remuxAudio(e,g,this.isAudioContiguous,s,m||S||o===O?p:void 0),S){var C=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,s)),l=this.remuxVideo(t,p,R,C)}}else S&&(l=this.remuxVideo(t,p,R,0));l&&(l.firstKeyFrame=P,l.independent=-1!==P,l.firstKeyFramePTS=I)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=En(i,n,this._initPTS,this._initDTS)),r.samples.length&&(d=Sn(r,n,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:c}},t.generateIS=function(e,t,i,r){var n,s,a,o=e.samples,l=t.samples,h=this.typeSupported,u={},d=this._initPTS,c=!d||r,f="audio/mp4";if(c&&(n=s=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):dn.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(a=e.inputTimeScale,d&&a===d.timescale?c=!1:n=s=o[0].pts-Math.round(a*i))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:dn.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*i);s=Math.min(s,yn(l[0].dts,g)-p),n=Math.min(n,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:n,timescale:a},this._initDTS={baseTime:s,timescale:a}):n=a=void 0,{tracks:u,initPTS:n,timescale:a}},t.remuxVideo=function(e,t,i,r){var n,s,a=e.inputTimeScale,l=e.samples,h=[],u=l.length,d=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,m=!1;if(!i||null===c){var y=t*a,E=l[0].pts-yn(l[0].dts,l[0].pts);gn&&null!==c&&Math.abs(y-E-c)<15e3?i=!0:c=y-E}for(var S=d.baseTime*a/d.timescale,T=0;T<u;T++){var L=l[T];L.pts=yn(L.pts-S,c),L.dts=yn(L.dts-S,c),L.dts<l[T>0?T-1:T].dts&&(m=!0)}m&&l.sort((function(e,t){var i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),n=l[0].dts;var _=l[l.length-1].dts-n,b=_?Math.round(_/(u-1)):g||e.inputTimeScale/30;if(i){var A=n-c,k=A>b,D=A<-1;if((k||D)&&(k?this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+fn(A,!0)+" ms ("+A+"dts) hole between fragments detected at "+t.toFixed(3)):this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+fn(-A,!0)+" ms ("+A+"dts) overlapping between fragments detected at "+t.toFixed(3)),!D||c>=l[0].pts||gn)){n=c;var w=l[0].pts-A;if(k)l[0].dts=n,l[0].pts=w;else for(var C=!0,M=0;M<l.length&&!(l[M].dts>w&&C);M++){var O=l[M].pts;if(l[M].dts-=A,l[M].pts-=A,M<l.length-1){var x=l[M+1].pts;C=x<=l[M].pts==x<=O}}this.logger.log("Video: Initial PTS/DTS adjusted: "+fn(w,!0)+"/"+fn(n,!0)+", delta: "+fn(A,!0)+" ms")}}for(var F=0,N=0,B=n=Math.max(0,n),U=0;U<u;U++){for(var G=l[U],H=G.units,V=H.length,K=0,W=0;W<V;W++)K+=H[W].data.length;N+=K,F+=V,G.length=K,G.dts<B?(G.dts=B,B+=b/4|0||1):B=G.dts,p=Math.min(G.pts,p),v=Math.max(G.pts,v)}s=l[u-1].dts;var $,q=N+4*F+8;try{$=new Uint8Array(q)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:I.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:q,reason:"fail allocating video mdat "+q})}var j=new DataView($.buffer);j.setUint32(0,q),$.set(dn.types.mdat,4);for(var Y=!1,z=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,ie=0,re=0,ne=te.length;re<ne;re++){var se=te[re],ae=se.data,oe=se.data.byteLength;j.setUint32(f,oe),f+=4,$.set(ae,f),f+=oe,ie+=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*a),ce=(r?p+r*a:this.nextAudioPts)-ee.pts;ce>de?((g=ce-ue)<0?g=ue:Y=!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);z=Math.min(z,g),Q=Math.max(Q,g),X=Math.min(X,le),J=Math.max(J,le),h.push(vn(ee.key,g,ie,fe))}if(h.length)if(gn){if(gn<70){var ge=h[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(pn&&J-X<Q-z&&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=n,ve=0,me=h.length;ve<me;ve++){var ye=pe+h[ve].duration,Ee=pe+h[ve].cts;if(ve<me-1){var Se=ye+h[ve+1].cts;h[ve].duration=Se-Ee}else h[ve].duration=ve?h[ve-1].duration:b;h[ve].cts=0,pe=ye}}g=Y||!g?b:g,this.nextAvcDts=c=s+g,this.videoSampleDuration=g,this.isVideoContiguous=!0;var Te={data1:dn.moof(e.sequenceNumber++,n,o(e,{samples:h})),data2:$,startPTS:p/a,endPTS:(v+g)/a,startDTS:n/a,endDTS:c/a,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,i,r,n){var s=e.inputTimeScale,a=s/(e.samplerate?e.samplerate:s),l=this.getSamplesPerFrame(e),h=l*a,u=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],f=void 0!==n,g=e.samples,p=d?0:8,v=this.nextAudioPts||-1,m=t*s,y=u.baseTime*s/u.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(r&&Math.abs(m-v)<9e3||Math.abs(yn(g[0].pts-y,m)-v)<20*h),g.forEach((function(e){e.pts=yn(e.pts-y,m)})),!i||v<0){if(g=g.filter((function(e){return e.pts>=0})),!g.length)return;v=0===n?0:r&&!f?Math.max(0,m):g[0].pts}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,S=0,T=v;S<g.length;S++){var L=g[S],_=L.pts,b=_-T,A=Math.abs(1e3*b/s);if(b<=-E*h&&f)0===S&&(this.logger.warn("Audio frame @ "+(_/s).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*b/s)+" ms."),this.nextAudioPts=v=T=_);else if(b>=E*h&&A<1e4&&f){var k=Math.round(b/h);(T=_-k*h)<0&&(k--,T+=h),0===S&&(this.nextAudioPts=v=T),this.logger.warn("[mp4-remuxer]: Injecting "+k+" audio frame @ "+(T/s).toFixed(3)+"s due to "+Math.round(1e3*b/s)+" ms gap.");for(var D=0;D<k;D++){var w=Math.max(T,0),C=hn.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);C||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),C=L.unit.subarray()),g.splice(S,0,{unit:C,pts:w}),T+=h,S++}}L.pts=T,T+=h}for(var M,O=null,x=null,F=0,N=g.length;N--;)F+=g[N].unit.byteLength;for(var B=0,U=g.length;B<U;B++){var G=g[B],H=G.unit,V=G.pts;if(null!==x)c[B-1].duration=Math.round((V-x)/a);else{if(i&&"aac"===e.segmentCodec&&(V=v),O=V,!(F>0))return;F+=p;try{M=new Uint8Array(F)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:I.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:F,reason:"fail allocating audio mdat "+F})}d||(new DataView(M.buffer).setUint32(0,F),M.set(dn.types.mdat,4))}M.set(H,p);var K=H.byteLength;p+=K,c.push(vn(!0,l,K,0)),x=V}var W=c.length;if(W){var $=c[c.length-1];this.nextAudioPts=v=x+a*$.duration;var q=d?new Uint8Array(0):dn.moof(e.sequenceNumber++,O/a,o({},e,{samples:c}));e.samples=[];var j=O/s,Y=v/s,z={data1:q,data2:M,startPTS:j,endPTS:Y,startDTS:j,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:W};return this.isAudioContiguous=!0,z}},e}();function yn(e,t){var i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function En(e,t,i,r){var n=e.samples.length;if(n){for(var s=e.inputTimeScale,a=0;a<n;a++){var o=e.samples[a];o.pts=yn(o.pts-i.baseTime*s/i.timescale,t*s)/s,o.dts=yn(o.dts-r.baseTime*s/r.timescale,t*s)/s}var l=e.samples;return e.samples=[],{samples:l}}}function Sn(e,t,i){var r=e.samples.length;if(r){for(var n=e.inputTimeScale,s=0;s<r;s++){var a=e.samples[s];a.pts=yn(a.pts-i.baseTime*n/i.timescale,t*n)/n}e.samples.sort((function(e,t){return e.pts-t.pts}));var o=e.samples;return e.samples=[],{samples:o}}}var Tn,Ln=function(){function e(e,t,i,r){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=r}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,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;var i=t.keyId;return i&&t.isCommonEncryption&&ge(e,["moov","trak"]).forEach((function(e){var t=ge(e,["mdia","minf","stbl","stsd"])[0].subarray(8),r=ge(t,["enca"]),n=r.length>0;n||(r=ge(t,["encv"])),r.forEach((function(e){ge(n?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=Le(e);if(t){var r=t.subarray(8,24);r.some((function(e){return 0!==e}))||($.log("[eme] Patching keyId in 'enc"+(n?"a":"v")+">sinf>>tenc' box: "+z(r)+" -> "+z(i)),t.set(i,8))}}))}))})),e}(e,r)),this.emitInitSegment=!0},t.generateInitSegment=function(e){var t=this.audioCodec,i=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var r=this.initData=ve(e);r.audio&&(t=_n(r.audio,Q)),r.video&&(i=_n(r.video,J));var n={};r.audio&&r.video?n.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:r.video.supplemental,initSegment:e,id:"main"}:r.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?n.video={container:"video/mp4",codec:i,supplemental:r.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n},t.remux=function(e,t,i,r,n,s){var a,o,l=this.initPTS,h=this.lastEndTime,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};_(h)||(h=this.lastEndTime=n||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 i=0,r=0,n=0,s=ge(e,["moof","traf"]),a=0;a<s.length;a++){var o=s[a],l=ge(o,["tfhd"])[0],h=t[ue(l,4)];if(h){var u=h.default,d=ue(l,0)|(null==u?void 0:u.flags),c=null==u?void 0:u.duration;8&d&&(c=ue(l,2&d?12:8));for(var f=h.timescale||9e4,g=ge(o,["trun"]),p=0;p<g.length;p++)!(i=_e(g[p]))&&c&&(i=c*ue(g[p],4)),h.type===J?r+=i/f:h.type===Q&&(n+=i/f)}}if(0===r&&0===n){for(var v=1/0,m=0,y=0,E=ge(e,["sidx"]),S=0;S<E.length;S++){var T=pe(E[S]);if(null!=T&&T.references){v=Math.min(v,T.earliestPresentationTime/T.timescale);var L=T.references.reduce((function(e,t){return e+t.info.duration||0}),0);y=(m=Math.max(m,L+T.earliestPresentationTime/T.timescale))-v}}if(y&&_(y))return y}return r||n}(d,f),p=function(e,t){return ge(t,["moof","traf"]).reduce((function(t,i){var r=ge(i,["tfdt"])[0],n=r[0],s=ge(i,["tfhd"]).reduce((function(t,i){var s=ue(i,4),a=e[s];if(a){var o=ue(r,4);if(1===n){if(o===se)return $.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;o*=se+1,o+=ue(r,8)}var l=o/(a.timescale||9e4);if(_(l)&&(null===t||l<t))return l}return t}),null);return null!==s&&_(s)&&(null===t||s<t)?s:t}),null)}(f,d),v=null===p?n:p;!s&&l||!function(e,t,i,r){if(null===e)return!0;var n=Math.max(r,1),s=t-e.baseTime/e.timescale;return Math.abs(s-i)>n}(l,v,n,g)&&c.timescale===l.timescale||(c.initPTS=v-n,l&&1===l.timescale&&this.logger.warn("Adjusting initPTS @"+n+" from "+l.baseTime/l.timescale+" to "+c.initPTS),this.initPTS=l={baseTime:c.initPTS,timescale:1});var m=e?v-l.baseTime/l.timescale:h,y=m+g;!function(e,t,i){ge(t,["moof","traf"]).forEach((function(t){ge(t,["tfhd"]).forEach((function(r){var n=ue(r,4),s=e[n];if(s){var a=s.timescale||9e4;ge(t,["tfdt"]).forEach((function(e){var t=e[0],r=i*a;if(r){var n=ue(e,4);if(0===t)n-=r,fe(e,4,n=Math.max(n,0));else{n*=Math.pow(2,32),n+=ue(e,8),n-=r,n=Math.max(n,0);var s=Math.floor(n/(se+1)),o=Math.floor(n%(se+1));fe(e,4,s),fe(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:m,startDTS:m,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=En(i,n,l,l),r.samples.length&&(u.text=Sn(r,n,l)),u},e}();function _n(e,t){var i=null==e?void 0:e.codec;return i&&i.length>4?i:t===Q?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?He(i,!1):($.warn('Unhandled audio codec "'+i+'" in mp4 MAP'),i||"mp4a"):($.warn('Unhandled video codec "'+i+'" in mp4 MAP'),i||"avc1")}try{Tn=self.performance.now.bind(self.performance)}catch(e){Tn=Date.now}var bn=[{demux:jr,remux:Ln},{demux:tn,remux:mn},{demux:Hr,remux:mn},{demux:$r,remux:mn}];bn.splice(2,0,{demux:Kr,remux:mn});var An=function(){function e(e,t,i,r,n,s){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=s}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,i,r){var n=this,s=i.transmuxing;s.executeStart=Tn();var a=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var h=r||o,u=h.contiguous,d=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,p=h.initSegmentChange,v=l.audioCodec,m=l.videoCodec,y=l.defaultInitPts,E=l.duration,S=l.initSegmentData,T=function(e,t){var i=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t),i}(a,t);if(T&&ii(T.method)){var L=this.getDecrypter(),_=ri(T.method);if(!L.isSync())return this.asyncResult=!0,this.decryptionPromise=L.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,_).then((function(e){var t=n.push(e,null,i);return n.decryptionPromise=null,t})),this.decryptionPromise;var b=L.softwareDecrypt(a,T.key.buffer,T.iv.buffer,_);if(i.part>-1){var A=L.flush();b=A?A.buffer:A}if(!b)return s.executeEnd=Tn(),In(i);a=new Uint8Array(b)}var k=this.needsProbing(d,c);if(k){var D=this.configureTransmuxer(a);if(D)return this.logger.warn("[transmuxer] "+D.message),this.observer.emit(P.ERROR,P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),s.executeEnd=Tn(),In(i)}(d||c||p||k)&&this.resetInitSegment(S,v,m,E,t),(d||p||k)&&this.resetInitialTimestamp(y),u||this.resetContiguity();var w=this.transmux(a,T,g,f,i);this.asyncResult=Rn(w);var C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,s.executeEnd=Tn(),w},t.flush=function(e){var t=this,i=e.transmuxing;i.executeStart=Tn();var r=this.decrypter,n=this.currentTransmuxState,s=this.decryptionPromise;if(s)return this.asyncResult=!0,s.then((function(){return t.flush(e)}));var a=[],o=n.timeOffset;if(r){var l=r.flush();l&&a.push(this.push(l.buffer,null,e))}var h=this.demuxer,u=this.remuxer;if(!h||!u){i.executeEnd=Tn();var d=[In(e)];return this.asyncResult?Promise.resolve(d):d}var c=h.flush(o);return Rn(c)?(this.asyncResult=!0,c.then((function(i){return t.flushRemux(a,i,e),a}))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)},t.flushRemux=function(e,t,i){var r=t.audioTrack,n=t.videoTrack,s=t.id3Track,a=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,h=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+i.sn+(i.part>-1?" part: "+i.part:"")+" of "+(this.id===M?"level":"track")+" "+i.level);var u=this.remuxer.remux(r,n,s,a,h,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Tn()},t.resetInitialTimestamp=function(e){var t=this.demuxer,i=this.remuxer;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,i,r,n){var s=this.demuxer,a=this.remuxer;s&&a&&(s.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,n))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,i,r,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,n):this.transmuxUnencrypted(e,i,r,n)},t.transmuxUnencrypted=function(e,t,i,r){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),s=n.audioTrack,a=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(s,a,o,l,t,i,!1,this.id),chunkMeta:r}},t.transmuxSampleAes=function(e,t,i,r,n){var s=this;return this.demuxer.demuxSampleAes(e,t,i).then((function(e){return{remuxResult:s.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,s.id),chunkMeta:n}}))},t.configureTransmuxer=function(e){for(var t,i=this.config,r=this.observer,n=this.typeSupported,s=0,a=bn.length;s<a;s++){var o;if(null!=(o=bn[s].demux)&&o.probe(e,this.logger)){t=bn[s];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,h=this.remuxer,u=t.remux,d=t.demux;h&&h instanceof u||(this.remuxer=new u(r,i,n,this.logger)),l&&l instanceof d||(this.demuxer=new d(r,i,n,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 xt(this.config)),e},e}(),In=function(e){return{remuxResult:{},chunkMeta:e}};function Rn(e){return"then"in e&&e.then instanceof Function}var Pn=function(e,t,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null},kn=function(e,t,i,r,n,s){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=s},Dn=[];function wn(e,t,i){if(!((r=t.remuxResult).audio||r.video||r.text||r.id3||r.initSegment))return!1;var r,n=[],s=t.remuxResult,a=s.audio,o=s.video;return a&&Cn(n,a),o&&Cn(n,o),e.postMessage({event:"transmuxComplete",data:t,instanceNo:i},n),!0}function Cn(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function Mn(e,t,i,r){t.reduce((function(t,i){return wn(e,i,r)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0],instanceNo:r}),e.postMessage({event:"flush",data:i,instanceNo:r})}function On(e,t,i){self.postMessage({event:e,data:t,instanceNo:i})}void 0!==i&&i&&self.addEventListener("message",(function(e){var t=e.data,i=t.instanceNo;if(void 0!==i){var r=Dn[i];if("reset"===t.cmd&&(delete Dn[t.resetNo],r&&r.destroy(),t.cmd="init"),"init"===t.cmd){var n=JSON.parse(t.config),s=new S;s.on(P.FRAG_DECRYPTED,On),s.on(P.ERROR,On);var a=W(n.debug,t.id);return function(e,t){var i=function(i){e[i]=function(e){On("workerLog",{logType:i,message:e},t)}};for(var r in e)i(r)}(a,i),Dn[i]=new An(s,t.typeSupported,n,"",t.id,a),void On("init",null,i)}if(r)switch(t.cmd){case"configure":r.configure(t.config);break;case"demux":var o=r.push(t.data,t.decryptdata,t.chunkMeta,t.state);Rn(o)?o.then((function(e){wn(self,e,i)})).catch((function(e){On(P.ERROR,{instanceNo:i,type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker push error"},i)})):wn(self,o,i);break;case"flush":var l=t.chunkMeta,h=r.flush(l);Rn(h)?h.then((function(e){Mn(self,e,l,i)})).catch((function(e){On(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker flush error"},i)})):Mn(self,h,l,i)}}}));var xn="1.6.2",Fn={},Nn=0,Bn=function(){function e(e,i,r,n){var s=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Nn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,i=s.hls;if(i&&null!=t&&t.event&&t.instanceNo===s.instanceNo)switch(t.event){case"init":var r,n=null==(r=s.workerContext)?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(t.data);break;case"flush":s.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=s.frag,t.data.part=s.part,t.data.id=s.id,i.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(s.hls){var t=new Error(e.message+" ("+e.filename+":"+e.lineno+")");s.hls.config.enableWorker=!1,s.hls.logger.warn('Error in "'+s.id+'" Web Worker, fallback to inline'),s.hls.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var a=e.config;this.hls=e,this.id=i,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;var o=function(e,t){(t=t||{}).frag=s.frag||void 0,e===P.ERROR&&(t.parent=s.id,t.part=s.part,s.error=t.error),s.hls.trigger(e,t)};this.observer=new S,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 "'+i+'"'),this.workerContext=function(e){var t=Fn[e];if(t)return t.clientCount++,t;var i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Fn[e]=r,r}(a.workerPath)):(h.log('injecting Web Worker for "'+i+'"'),this.workerContext=function(){var e=Fn[xn];if(e)return e.clientCount++,e;var i=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+t.toString()+")(true);"],{type:"text/javascript"}),r=self.URL.createObjectURL(i),n={worker:new self.Worker(r),objectURL:r,clientCount:1};return Fn[xn]=n,n}());var u=this.workerContext.worker;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:i,config:it(a)})}catch(t){h.warn('Error setting up "'+i+'" Web Worker, fallback to inline',t),this.terminateWorker(),this.error=null,this.transmuxer=new An(this.observer,l,a,"",i,e.logger)}}else this.transmuxer=new An(this.observer,l,a,"",i,e.logger)}var i=e.prototype;return i.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=Nn++;var t=this.hls.config,i=We(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:it(t)})}},i.terminateWorker=function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=Fn[e||xn];if(t&&1==t.clientCount--){var i=t.worker,r=t.objectURL;delete Fn[e||xn],r&&self.URL.revokeObjectURL(r),i.terminate()}}(this.hls.config.workerPath)}},i.destroy=function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null},i.push=function(e,t,i,r,n,s,a,o,l,h){var u,d,c=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,g=this.transmuxer,p=s?s.start:n.start,v=n.decryptdata,m=this.frag,y=!(m&&n.cc===m.cc),E=!(m&&l.level===m.level),S=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,L=0===S&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),_=!E&&(1===S||0===S&&(1===T||L&&T<=0)),b=self.performance.now();(E||S||0===n.stats.parsing.start)&&(n.stats.parsing.start=b),!s||!T&&_||(s.stats.parsing.start=b);var A=!(m&&(null==(u=n.initSegment)?void 0:u.url)===(null==(d=m.initSegment)?void 0:d.url)),I=new kn(y,_,o,E,p,A);if(!_||y||A){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+n.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===M?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+_+"\n accurateTimeOffset: "+o+"\n timeOffset: "+p+"\n initSegmentChange: "+A);var R=new Pn(i,r,t,a,h);this.configureTransmuxer(R)}if(this.frag=n,this.part=s,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:v,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(g){var P=g.push(e,v,l,I);Rn(P)?P.then((function(e){c.handleTransmuxComplete(e)})).catch((function(e){c.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(P)}},i.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var i=this.instanceNo,r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:e});else if(r){var n=r.flush(e);Rn(n)?n.then((function(i){t.handleFlushResult(i,e)})).catch((function(i){t.transmuxerError(i,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}},i.transmuxerError=function(e,t,i){this.hls&&(this.error=e,this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))},i.handleFlushResult=function(e,t){var i=this;e.forEach((function(e){i.handleTransmuxComplete(e)})),this.onFlush(t)},i.configureTransmuxer=function(e){var t=this.instanceNo,i=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)},i.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}(),Un=function(e){function t(t,i,r){var n;return(n=e.call(this,t,i,r,"audio-stream-controller",O)||this).mainAnchor=null,n.mainFragLoading=null,n.audioOnly=!1,n.bufferedTrack=null,n.switchingTrack=null,n.trackId=-1,n.waitingData=null,n.mainDetails=null,n.flushing=!1,n.bufferFlushed=!1,n.cachedTrackLoadedData=null,n.registerListeners(),n}h(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.resetItem()},i.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(P.LEVEL_LOADED,this.onLevelLoaded,this),t.on(P.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(P.BUFFER_RESET,this.onBufferReset,this),t.on(P.BUFFER_CREATED,this.onBufferCreated,this),t.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(P.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(P.FRAG_LOADING,this.onFragLoading,this),t.on(P.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){var t=this.hls;t&&(e.prototype.unregisterListeners.call(this),t.off(P.LEVEL_LOADED,this.onLevelLoaded,this),t.off(P.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(P.BUFFER_RESET,this.onBufferReset,this),t.off(P.BUFFER_CREATED,this.onBufferCreated,this),t.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(P.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(P.FRAG_LOADING,this.onFragLoading,this),t.off(P.FRAG_BUFFERED,this.onFragBuffered,this))},i.onInitPtsFound=function(e,t){var i=t.frag,r=t.id,n=t.initPTS,s=t.timescale;if(r===M){var a=i.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:n,timescale:s},this.log("InitPTS for cc: "+a+" found from main: "+n+"/"+s),this.mainAnchor=i,this.state===er.WAITING_INIT_PTS){var l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==a)&&(this.nextLoadPosition=this.findSyncFrag(i).start),this.tick()}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(i).start,o.abortRequests(),this.resetLoadingState()):this.state===er.IDLE&&this.tick()}},i.findSyncFrag=function(e){var t=this.getLevelDetails(),i=e.cc;return function(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){var r=i.start,n=i.end,s=e.fragments;if(!i.relurl){var a=e.fragmentHint;a&&(s=s.concat(a))}return ct(s,(function(e){return e.cc<t||e.end<=r?1:e.cc>t||e.start>=n?-1:0}))}return null}(t,i,e)||t&&vt(t.fragments,i)||e},i.startLoad=function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=er.STOPPED);var i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i,this.state=er.IDLE):this.state=er.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.doTick=function(){switch(this.state){case er.IDLE:this.doTickIdle();break;case er.WAITING_TRACK:var t=this.levels,i=this.trackId,r=null==t?void 0:t[i],n=null==r?void 0:r.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=er.WAITING_INIT_PTS}break;case er.FRAG_LOADING_WAITING_RETRY:var s,a=performance.now(),o=this.retryDate;if(!o||a>=o||null!=(s=this.media)&&s.seeking){var l=this.levels,h=this.trackId;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==l?void 0:l[h])||null),this.state=er.IDLE}break;case er.WAITING_INIT_PTS:var u=this.waitingData;if(u){var d=u.frag,c=u.part,f=u.cache,g=u.complete,p=this.mainAnchor;if(void 0!==this.initPTS[d.cc]){this.waitingData=null,this.state=er.FRAG_LOADING;var v={frag:d,part:c,payload:f.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(v),g&&e.prototype._handleFragmentLoadComplete.call(this,v)}else p&&p.cc!==u.frag.cc&&(this.log("Waiting fragment cc ("+d.cc+") cancelled because video is at cc "+p.cc),this.nextLoadPosition=this.findSyncFrag(p).start,this.clearWaitingFragment())}else this.state=er.IDLE}this.onTickEnd()},i.clearWaitingFragment=function(){var e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==er.STOPPED&&(this.state=er.IDLE))},i.resetLoadingState=function(){this.clearWaitingFragment(),e.prototype.resetLoadingState.call(this)},i.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)},i.doTickIdle=function(){var e,t=this.hls,i=this.levels,r=this.media,n=this.trackId,s=t.config;if(this.buffering&&(r||this.primaryPrefetch||!this.startFragRequested&&s.startFragPrefetch)&&null!=i&&i[n]){var a=i[n],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=er.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Q,O));var h=this.getFwdBufferInfo(l,O);if(null!==h){if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(P.BUFFER_EOS,{type:"audio"}),void(this.state=er.ENDED);var u=h.len,d=t.maxBufferLength,c=o.fragments,f=c[0].start,g=this.getLoadPosition(),p=this.flushing?g:h.end;if(this.switchingTrack&&r){var v=g;o.PTSKnown&&v<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(!(u>=d&&!this.switchingTrack&&p<c[c.length-1].start)){var m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,h,M,d)),m){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&te(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Rt&&(this.mainFragLoading=y=null),y&&te(y))){if(m.start>y.end){var E=this.fragmentTracker.getFragAtPos(p,M);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(m.start>y.end)return}this.loadFragment(m,a,p)}else this.bufferFlushed=!0}}}},i.onMediaDetaching=function(t,i){this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this,t,i)},i.onAudioTracksUpdated=function(e,t){var i=t.audioTracks;this.resetTransmuxer(),this.levels=i.map((function(e){return new et(e)}))},i.onAudioTrackSwitching=function(e,t){var i=!!t.url;this.trackId=t.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==er.STOPPED&&(this.setInterval(100),this.state=er.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},i.onLevelLoaded=function(e,t){this.mainDetails=t.details;var i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(P.AUDIO_TRACK_LOADED,i))},i.onAudioTrackLoaded=function(e,t){var i,r=this.levels,n=t.details,s=t.id,a=t.groupId,o=t.track;if(r){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==er.STOPPED&&(this.state=er.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+s+' "'+o.name+'" of "'+a+'" loaded ['+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration);var h=r[s],u=0;if(n.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var d;h.details&&(u=this.alignPlaylists(n,h.details,null==(d=this.levelLastLoaded)?void 0:d.details)),n.alignedSliding||(Ji(n,l),n.alignedSliding||Zi(n,l),u=n.fragmentStart)}h.details=n,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(P.AUDIO_TRACK_UPDATED,{details:n,id:s,groupId:t.groupId}),this.state!==er.WAITING_TRACK||this.waitForCdnTuneIn(n)||(this.state=er.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+s+' "'+o.name+'" of "'+a+'"')},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,n=e.payload,s=this.config,a=this.trackId,o=this.levels;if(o){var l=o[a];if(l){var h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);var u=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new Bn(this.hls,O,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){var g=r?r.index:-1,p=-1!==g,v=new Vt(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,p);d.push(n,f,u,"",i,r,h.totalduration,!1,v,c)}else this.log("Unknown video PTS for cc "+i.cc+", waiting for video PTS before demuxing audio frag "+i.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+a),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new rr,complete:!1}).cache.push(new Uint8Array(n)),this.state!==er.STOPPED&&(this.state=er.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},i.onBufferReset=function(){this.mediaBuffer=null},i.onBufferCreated=function(e,t){this.bufferFlushed=this.flushing=!1;var i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)},i.onFragLoading=function(e,t){!this.audioOnly&&t.frag.type===M&&te(t.frag)&&(this.mainFragLoading=t,this.state===er.IDLE&&this.tick())},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part;if(i.type===O)if(this.fragContextChanged(i))this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if(te(i)){this.fragPrevious=i;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(P.AUDIO_TRACK_SWITCHED,c({},n)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==M||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},i.onError=function(t,i){var r;if(i.fatal)this.state=er.ERROR;else switch(i.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(O,i);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==er.WAITING_TRACK||(null==(r=i.context)?void 0:r.type)!==w||(this.state=er.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}},i.onBufferFlushing=function(e,t){t.type!==J&&(this.flushing=!0)},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==J){this.flushing=!1,this.bufferFlushed=!0,this.state===er.ENDED&&(this.state=er.IDLE);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,O),this.tick())}},i._handleTransmuxComplete=function(e){var t,i="audio",r=this.hls,n=e.remuxResult,s=e.chunkMeta,a=this.getCurrentContext(s);if(a){var l=a.frag,h=a.part,u=a.level,d=u.details,c=n.audio,f=n.text,g=n.id3,p=n.initSegment;if(!this.fragContextChanged(l)&&d){if(this.state=er.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){var v=l.initSegment||l;this._bufferInitSegment(u,p.tracks,v,s),r.trigger(P.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:p.tracks})}if(c){var m=c.startPTS,y=c.endPTS,E=c.startDTS,S=c.endDTS;h&&(h.elementaryStreams[Q]={startPTS:m,endPTS:y,startDTS:E,endDTS:S}),l.setElementaryStreamInfo(Q,m,y,E,S),this.bufferFragmentData(c,l,h,s)}if(null!=g&&null!=(t=g.samples)&&t.length){var T=o({id:i,frag:l,details:d},g);r.trigger(P.FRAG_PARSING_METADATA,T)}if(f){var L=o({id:i,frag:l,details:d},f);r.trigger(P.FRAG_PARSING_USERDATA,L)}}else this.fragmentTracker.removeFragment(l)}else this.resetWhenMissingContext(s)},i._bufferInitSegment=function(e,t,i,r){if(this.state===er.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=O;var s=e.audioCodec;this.log("Init audio buffer, container:"+n.container+", codecs[level/parsed]=["+s+"/"+n.codec+"]"),s&&1===s.split(",").length&&(n.levelCodec=s),this.hls.trigger(P.BUFFER_CODECS,t);var a=n.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(P.BUFFER_APPENDING,o)}this.tickImmediate()}},i.loadFragment=function(t,i,r){var n,s=this.fragmentTracker.getState(t);if(this.switchingTrack||s===bt||s===It)if(te(t))if(null!=(n=i.details)&&n.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=er.WAITING_INIT_PTS;var a=this.mainDetails;a&&a.fragmentStart!==i.details.fragmentStart&&Zi(i.details,a)}else e.prototype.loadFragment.call(this,t,i,r);else this._loadInitSegment(t,i);else this.clearTrackerIfNeeded(t)},i.flushAudioIfNeeded=function(t){if(this.media&&this.bufferedTrack){var i=this.bufferedTrack;ot({name:i.name,lang:i.lang,assocLang:i.assocLang,characteristics:i.characteristics,audioCodec:i.audioCodec,channels:i.channels},t,lt)||(ut(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}},i.completeAudioSwitch=function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(P.AUDIO_TRACK_SWITCHED,c({},e))},t}(tr),Gn=function(e){function t(t,i){var r;return(r=e.call(this,i,t.logger)||this).hls=void 0,r.canLoad=!1,r.timer=-1,r.hls=t,r}h(t,e);var i=t.prototype;return i.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},i.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},i.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},i.stopLoad=function(){this.canLoad=!1,this.clearTimer()},i.switchParams=function(e,t,i){var r=null==t?void 0:t.renditionReports;if(r){for(var n=-1,s=0;s<r.length;s++){var a=r[s],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){n=s;break}o===e.substring(0,o.length)&&(n=s)}if(-1!==n){var l=r[n],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=i&&Je(i);return new Ze(h,u>=0?u:void 0,c)}}},i.loadPlaylist=function(e){this.clearTimer()},i.loadingPlaylist=function(e,t){this.clearTimer()},i.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},i.getUrlWithDirectives=function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}return e},i.playlistLoaded=function(e,t,i){var r=t.details,n=t.stats,s=self.performance.now(),a=n.loading.first?Math.max(0,s-n.loading.first):0;r.advancedDateTime=Date.now()-a;var o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){var l=Math.max(o||0,0);r.appliedTimelineOffset=l,r.fragments.forEach((function(e){e.start=e.playlistOffset+l}))}if(r.live||null!=i&&i.live){var h="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){Gi(i,r);var u=r.playlistParsingError;if(u){this.warn(u);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var c,f=t.networkDetails;return void d.trigger(P.ERROR,{type:I.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:u,reason:u.message,level:t.level||void 0,parent:null==(c=r.fragments[0])?void 0:c.type,networkDetails:f,stats:n})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=n.loading.start);var g,p=this.hls.mainForwardBufferInfo,v=p?p.end-p.len:0,m=Wi(r,1e3*(r.edge-v));if(r.requestScheduled+m<s?r.requestScheduled=s:r.requestScheduled+=m,this.log("live playlist "+e+" "+(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;var y=void 0,E=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){var S=this.hls.config.lowLatencyMode,T=r.lastPartSn,L=r.endSN,_=r.lastPartIndex,b=T===L;-1!==_?b?(y=L+1,E=S?0:_):(y=T,E=S?_+1:r.maxPartIndex):y=L+1;var A=r.age,k=A+r.ageHeader,D=Math.min(k-r.partTarget,1.5*r.targetduration);if(D>0){if(k>3*r.targetduration)this.log("Playlist last advanced "+A.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=i&&i.tuneInGoal&&k-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+i.tuneInGoal+" to: "+D+" with playlist age: "+r.age),D=0;else{var w=Math.floor(D/r.targetduration);y+=w,void 0!==E&&(E+=Math.round(D%r.targetduration/r.partTarget)),this.log("CDN Tune-in age: "+r.ageHeader+"s last advanced "+A.toFixed(2)+"s goal: "+D+" skip sn "+w+" to part "+E)}r.tuneInGoal=D}if(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E),S||!b)return r.requestScheduled=s,void this.loadingPlaylist(h,g)}else(r.canBlockReload||r.canSkipUntil)&&(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E));g&&void 0!==y&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-2*a,m/2)),this.scheduleLoading(h,g,r)}else this.clearTimer()},i.scheduleLoading=function(e,t,i){var r=this,n=i||e.details;if(n){var s=self.performance.now(),a=n.requestScheduled;if(s>=a)this.loadingPlaylist(e,t);else{var o=a-s;this.log("reload live playlist "+(e.name||e.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return r.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},i.getDeliveryDirectives=function(e,t,i,r){var n=Je(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=""),new Ze(i,r,n)},i.checkRetry=function(e){var t=this,i=e.details,r=mt(e),n=e.errorAction,s=n||{},a=s.action,o=s.retryCount,l=void 0===o?0:o,h=s.retryConfig,u=!!n&&!!h&&(5===a||!n.resolved&&2===a);if(u){var d;if(l>=h.maxNumRetry)return!1;if(r&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" without delivery-directives'),this.loadPlaylist();else{var c=Et(h,l);this.clearTimer(),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" in '+c+"ms")}e.levelRetry=!0,n.resolved=!0}return u},t}(B);function Hn(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(!Vn(e[i].attrs,t[i].attrs))return!1;return!0}function Vn(e,t,i){var r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((function(i){return e[i]!==t[i]}))}function Kn(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var Wn=function(e){function t(t){var i;return(i=e.call(this,t,"audio-track-controller")||this).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.registerListeners(),i}h(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(P.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(P.ERROR,this.onError,this)},i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,e.prototype.destroy.call(this)},i.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.audioTracks||[]},i.onAudioTrackLoaded=function(e,t){var i=t.id,r=t.groupId,n=t.details,s=this.tracksInGroup[i];if(s&&s.groupId===r){var a=s.details;s.details=t.details,this.log("Audio track "+i+' "'+s.name+'" lang:'+s.lang+" group:"+r+" loaded ["+n.startSN+"-"+n.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Audio track with id:"+i+" and group:"+r+" not found in active group "+(null==s?void 0:s.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var s=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(s.length)this.selectDefaultTrack&&!s.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),s.forEach((function(e,t){e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=s;var a=this.hls.config.audioPreference;if(!n&&a){var o=at(a,s,lt);if(o>-1)n=s[o];else{var l=at(a,this.tracks);n=this.tracks[l]}}var h=this.findTrackId(n);-1===h&&n&&(h=this.findTrackId(null));var u={audioTracks:s};this.log("Updating audio tracks, "+s.length+" track(s) found in group(s): "+(null==i?void 0:i.join(","))),this.hls.trigger(P.AUDIO_TRACKS_UPDATED,u);var d=this.trackId;if(-1!==h&&-1===d)this.setAudioTrack(h);else if(s.length&&-1===d){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+s.length);this.warn(f.message),this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==w||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&ot(e,r,lt))return r;var n=at(e,this.tracksInGroup,lt);if(n>-1){var s=this.tracksInGroup[n];return this.setAudioTrack(n),s}if(r){var a=t.loadLevel;-1===a&&(a=t.firstAutoLevel);var o=function(e,t,i,r,n){var s=t[r],a=t.reduce((function(e,t,i){var r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[s.uri];a.length>1&&(r=Math.max.apply(Math,a));var o=s.videoRange,l=s.frameRate,h=s.codecSet.substring(0,4),u=ht(t,r,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;var r=t.audioGroups,s=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return at(e,s,n)>-1}));return u>-1?u:ht(t,r,(function(t){var r=t.audioGroups,s=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return at(e,s,n)>-1}))}(e,t.levels,i,a,lt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=at(e,i);if(l>-1)return i[l]}}}return null},i.setAudioTrack=function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(!(e===this.trackId&&r===i&&n||(this.log("Switching to audio-track "+e+' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId+" channels:"+r.channels),this.trackId=e,this.currentTrack=r,this.hls.trigger(P.AUDIO_TRACK_SWITCHING,c({},r)),n))){var s=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(s)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=0;i<t.length;i++){var r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||ot(e,r,lt)))return i}if(e){for(var n=e.name,s=e.lang,a=e.assocLang,o=e.characteristics,l=e.audioCodec,h=e.channels,u=0;u<t.length;u++)if(ot({name:n,lang:s,assocLang:a,characteristics:o,audioCodec:l,channels:h},t[u],lt))return u;for(var d=0;d<t.length;d++){var c=t[d];if(Vn(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var g=t[f];if(Vn(e.attrs,g.attrs,["LANGUAGE"]))return f}}return-1},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var i=this.currentTrack;this.shouldLoadPlaylist(i)&&ut(i.url,this.hls)&&this.scheduleLoading(i,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,n=t.groupId,s=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading audio-track "+r+' "'+t.name+'" lang:'+t.lang+" group:"+n+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+s),this.hls.trigger(P.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:i||null,track:t})},n(t,[{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}}])}(Gn),$n=function(){function e(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}var t=e.prototype;return t.destroy=function(){this.tracks=this.queues=null},t.append=function(e,t,i){if(null!==this.queues&&null!==this.tracks){var r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}},t.appendBlocker=function(e){var t=this;return new Promise((function(i){var r={label:"async-blocker",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(r,e)}))},t.prependBlocker=function(e){var t=this;return new Promise((function(i){if(t.queues){var r={label:"async-blocker-prepend",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(r)}}))},t.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(e){var t,i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))}))},t.unblockAudio=function(e){null!==this.queues&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")},t.executeNext=function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var i=t[0];try{i.execute()}catch(t){var r;if(i.onError(t),null===this.queues||null===this.tracks)return;var n=null==(r=this.tracks[e])?void 0:r.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}},t.shiftAndExecuteNext=function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))},t.current=function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null},t.toString=function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},t.list=function(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?"SourceBuffer"+(r.updating?" updating":"")+(i.ended?" ended":"")+(i.ending?" ending":""):"none"},t.listOps=function(e){var t;return(null==(t=this.queues)?void 0:t[e].map((function(e){return e.label})).join(", "))||""},e}(),qn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,jn="HlsJsTrackRemovedError",Yn=function(e){function t(t){var i;return(i=e.call(this,t)||this).name=jn,i}return h(t,e),t}(p(Error)),zn=function(e){function t(t,i){var r,n;return(r=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.details=null,r._objectUrl=null,r.operationQueue=null,r.bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.lastMpegAudioChunk=null,r.blockedAudioAppend=null,r.lastVideoAppendEnd=0,r.appendSource=void 0,r.transferData=void 0,r.overrides=void 0,r.appendErrors={audio:0,video:0,audiovideo:0},r.tracks={},r.sourceBuffers=[[null,null],[null,null]],r._onEndStreaming=function(e){var t;r.hls&&"open"===(null==(t=r.mediaSource)?void 0:t.readyState)&&r.hls.pauseBuffering()},r._onStartStreaming=function(e){r.hls&&r.hls.resumeBuffering()},r._onMediaSourceOpen=function(e){var t=r,i=t.media,n=t.mediaSource;e&&r.log("Media source opened"),i&&n&&(n.removeEventListener("sourceopen",r._onMediaSourceOpen),i.removeEventListener("emptied",r._onMediaEmptied),r.updateDuration(),r.hls.trigger(P.MEDIA_ATTACHED,{media:i,mediaSource:n}),null!==r.mediaSource&&r.checkPendingTracks())},r._onMediaSourceClose=function(){r.log("Media source closed")},r._onMediaSourceEnded=function(){r.log("Media source ended")},r._onMediaEmptied=function(){var e=r,t=e.mediaSrc,i=e._objectUrl;t!==i&&r.error("Media element src was set while attaching MediaSource ("+i+" > "+t+")")},r.hls=t,r.fragmentTracker=i,r.appendSource=(n=q(t.config.preferManagedMediaSource),"undefined"!=typeof self&&n===self.ManagedMediaSource),r.initTracks(),r.registerListeners(),r}h(t,e);var i=t.prototype;return i.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},i.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null},i.registerListeners=function(){var e=this.hls;e.on(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)},i.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)},i.transferMedia=function(){var e=this,t=this.media,i=this.mediaSource;if(!t)return null;var r={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var s=this.isQueued();(n||s)&&this.warn("Transfering MediaSource with"+(s?" operations in queue":"")+(n?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var a=this.transferData;return!this.sourceBufferCount&&a&&a.mediaSource===i?o(r,a.tracks):this.sourceBuffers.forEach((function(t){var i=t[0];i&&(r[i]=o({},e.tracks[i]),e.removeBuffer(i)),t[0]=t[1]=null})),{media:t,mediaSource:i,tracks:r}},i.initTracks=function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},i.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},i.onManifestParsed=function(e,t){var i,r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(r+" bufferCodec event(s) expected."),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()},i.onMediaAttaching=function(e,t){var i=this.media=t.media,r=q(this.appendSource);if(this.transferData=this.overrides=void 0,i&&r){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var s=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(s),n)this._objectUrl=i.src,this.attachTransferred();else{var a=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&s instanceof o,Xn(i),function(e,t){var i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,a),i.load()}catch(e){i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}},i.assignMediaSource=function(e){var t,i;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(i=e.constructor)?void 0:i.name)),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))},i.attachTransferred=function(){var e=this,t=this.media,i=this.transferData;if(i&&t){var r=this.tracks,n=i.tracks,s=n?Object.keys(n):null,a=s?s.length:0,o=function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()};if(n&&s&&a){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+it(r,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+it(n,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!j(n,r)){i.mediaSource=null,i.tracks=void 0;var l=t.currentTime,h=this.details,u=Math.max(l,(null==h?void 0:h.fragments[0].start)||0);return u-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+u):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(n)+'"->"'+Object.keys(r)+'") start time: '+u+" currentTime: "+l),this.onMediaDetaching(P.MEDIA_DETACHING,{}),this.onMediaAttaching(P.MEDIA_ATTACHING,i),void(t.currentTime=u))}this.transferData=void 0,s.forEach((function(t){var i=t,r=n[i];if(r){var s=r.buffer;if(s){var a=e.fragmentTracker,o=r.id;if(a.hasFragments(o)||a.hasParts(o)){var l=Wt.getBuffered(s);a.detectEvictedFragments(i,l,o,null,!0)}var h=Qn(i),u=[i,s];e.sourceBuffers[h]=u,s.updating&&e.operationQueue&&e.operationQueue.prependBlocker(i),e.trackSourceBuffer(i,r)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},i.onMediaDetaching=function(e,t){var i=this,r=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,s=this.mediaSource,a=this._objectUrl;if(s){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===s.readyState;try{for(var l=s.sourceBuffers,h=l.length;h--;)o&&l[h].abort(),s.removeSourceBuffer(l[h]);o&&s.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(n.removeAttribute("src"),this.appendSource&&Xn(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(P.MEDIA_DETACHED,t)},i.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];i&&e.resetBuffer(i)})),this.initTracks()},i.resetBuffer=function(e){var t,i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},i.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[Qn(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)},i.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new $n(this.tracks)},i.onBufferCodecs=function(e,t){var i=this,r=this.tracks,n=Object.keys(t);this.log('BUFFER_CODECS: "'+n+'" (current SB count '+this.sourceBufferCount+")");var s="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),a=!s&&this.sourceBufferCount&&this.media&&n.some((function(e){return!r[e]}));s||a?this.warn('Unsupported transition between "'+Object.keys(r)+'" and "'+n+'" SourceBuffers'):(n.forEach((function(e){var n,s,a,o=t[e],l=o.id,h=o.codec,u=o.levelCodec,d=o.container,c=o.metadata,f=o.supplemental,g=r[e],p=null==(n=i.transferData)||null==(s=n.tracks)?void 0:s[e],v=null!=p&&p.buffer?p:g,m=(null==v?void 0:v.pendingCodec)||(null==v?void 0:v.codec),y=null==v?void 0:v.levelCodec;g||(g=r[e]={buffer:void 0,listeners:[],codec:h,supplemental:f,container:d,levelCodec:u,metadata:c,id:l});var E=Ve(m,y),S=null==E?void 0:E.replace(qn,"$1"),T=Ve(h,u),L=null==(a=T)?void 0:a.replace(qn,"$1");T&&E&&S!==L&&("audio"===e.slice(0,5)&&(T=He(T,i.appendSource)),i.log("switching codec "+m+" to "+T),T!==(g.pendingCodec||g.codec)&&(g.pendingCodec=T),g.container=d,i.appendChangeType(e,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())},i.appendChangeType=function(e,t,i){var r=this,n=t+";codecs="+i,s={label:"change-type="+n,execute:function(){var s=r.tracks[e];if(s){var a=s.buffer;null!=a&&a.changeType&&(r.log("changing "+e+" sourceBuffer type to "+n),a.changeType(n),s.codec=i,s.container=t)}r.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(s,e,this.isPending(this.tracks[e]))},i.blockAudio=function(e){var t,i=this,r=e.start,n=r+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(r,M))?void 0:t.gap)){var s={label:"block-audio",execute:function(){var e,t=i.tracks.video;(i.lastVideoAppendEnd>n||null!=t&&t.buffer&&Wt.isBuffered(t.buffer,n)||!0===(null==(e=i.fragmentTracker.getAppendedFrag(n,M))?void 0:e.gap))&&(i.blockedAudioAppend=null,i.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){i.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:s,frag:e},this.append(s,"audio",!0)}},i.unblockAudio=function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))},i.onBufferAppending=function(e,t){var i=this,r=this.tracks,n=t.data,s=t.type,a=t.parent,o=t.frag,l=t.part,h=t.chunkMeta,u=h.buffering[s],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=r.audio,v=!1;"audio"===s&&"audio/mpeg"===(null==p?void 0:p.container)&&(v=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var m=this.tracks.video,y=null==m?void 0:m.buffer;if(y&&"initSegment"!==d){var E=l||o,S=this.blockedAudioAppend;if("audio"!==s||"main"===a||this.blockedAudioAppend){if("video"===s){var T=E.end;if(S){var L=S.frag.start;(T>L||T<this.lastVideoAppendEnd||Wt.isBuffered(y,L))&&this.unblockAudio()}this.lastVideoAppendEnd=T}}else{var _=E.start+.05*E.duration,b=y.buffered,A=this.currentOp("video");b.length||A?!A&&!Wt.isBuffered(y,_)&&this.lastVideoAppendEnd<_&&this.blockAudio(E):this.blockAudio(E)}}var k=(l||o).start,D={label:"append-"+s,execute:function(){if(u.executeStart=self.performance.now(),v){var e=i.tracks[s];if(e){var t=e.buffer;if(t){var r=k-t.timestampOffset;Math.abs(r)>=.1&&(i.log("Updating audio SourceBuffer timestampOffset to "+k+" (delta: "+r+") sn: "+d+")"),t.timestampOffset=k)}}}i.appendExecutor(n,s)},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={};i.sourceBuffers.forEach((function(e){var i=e[0],r=e[1];i&&(t[i]=Wt.getBuffered(r))})),i.appendErrors[s]=0,"audio"===s||"video"===s?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(P.BUFFER_APPENDED,{type:s,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:t})},onError:function(e){var t,r={type:I.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1},n=null==(t=i.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR)r.details=R.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&i.mediaSourceOpenOrEnded&&!n)r.errorAction=_t(!0);else if(e.name===jn&&0===i.sourceBufferCount)r.errorAction=_t(!0);else{var a=++i.appendErrors[s];i.warn("Failed "+a+"/"+i.hls.config.appendErrorMaxRetry+' times to append segment in "'+s+'" sourceBuffer ('+(n||"no media error")+")"),(a>=i.hls.config.appendErrorMaxRetry||n)&&(r.fatal=!0)}i.hls.trigger(P.ERROR,r)}};this.append(D,s,this.isPending(this.tracks[s]))},i.getFlushOp=function(e,t,i){var r=this;return this.log('queuing "'+e+'" remove '+t+"-"+i),{label:"remove",execute:function(){r.removeExecutor(e,t,i)},onStart:function(){},onComplete:function(){r.hls.trigger(P.BUFFER_FLUSHED,{type:e})},onError:function(n){r.warn("Failed to remove "+t+"-"+i+' from "'+e+'" SourceBuffer',n)}}},i.onBufferFlushing=function(e,t){var i=this,r=t.type,n=t.startOffset,s=t.endOffset;r?this.append(this.getFlushOp(r,n,s),r):this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.append(i.getFlushOp(t,n,s),t)}))},i.onFragParsed=function(e,t){var i=this,r=t.frag,n=t.part,s=[],a=n?n.elementaryStreams:r.elementaryStreams;a[Z]?s.push("audiovideo"):(a[Q]&&s.push("audio"),a[J]&&s.push("video")),0===s.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+r.type+" level: "+r.level+" sn: "+r.sn),this.blockBuffers((function(){var e=self.performance.now();r.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:r.stats;i.hls.trigger(P.FRAG_BUFFERED,{frag:r,part:n,stats:t,id:r.type})}),s).catch((function(e){i.warn("Fragment buffered callback "+e),i.stepOperationQueue(i.sourceBufferTypes)}))},i.onFragChanged=function(e,t){this.trimBuffers()},i.onBufferEos=function(e,t){var i,r=this;this.sourceBuffers.forEach((function(e){var i=e[0];if(i){var n=r.tracks[i];t.type&&t.type!==i||(n.ending=!0,n.ended||(n.ended=!0,r.log(i+" buffer reached EOS")))}}));var n=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,i=e[0];return i&&!(null!=(t=r.tracks[i])&&t.ended)}))&&(n?(this.log("Queueing EOS"),this.blockUntilOpen((function(){r.tracksEnded();var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream(),r.hls.trigger(P.BUFFERED_TO_END,void 0)):e&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(P.BUFFERED_TO_END,void 0)))},i.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];if(null!==i){var r=e.tracks[i];r&&(r.ending=!1)}}))},i.onLevelUpdated=function(e,t){var i=t.details;i.fragments.length&&(this.details=i,this.updateDuration())},i.updateDuration=function(){var e=this,t=this.getDurationAndRange();t&&this.blockUntilOpen((function(){return e.updateMediaSource(t)}))},i.onError=function(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var i,r=null==(i=t.errorAction)?void 0:i.nextAutoLevel;_(r)&&r!==t.frag.level&&this.resetAppendErrors()}},i.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},i.trimBuffers=function(){var e=this.hls,t=this.details,i=this.media;if(i&&null!==t&&this.sourceBufferCount){var r=e.config,n=i.currentTime,s=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(_(a)&&a>=0){var o=Math.max(a,s),l=Math.floor(n/s)*s-o;this.flushBackBuffer(n,s,l)}if(_(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){var h=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),u=Math.max(h,s),d=Math.floor(n/s)*s+u;this.flushFrontBuffer(n,s,d)}}},i.flushBackBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(e){var t=e[0],n=e[1];if(n){var s=Wt.getBuffered(n);if(s.length>0&&i>s.start(0)){var a;r.hls.trigger(P.BACK_BUFFER_REACHED,{bufferEnd:i});var o=r.tracks[t];if(null!=(a=r.details)&&a.live)r.hls.trigger(P.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=o&&o.ended)return void r.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");r.hls.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}}))},i.flushFrontBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(t){var n=t[0],s=t[1];if(s){var a=Wt.getBuffered(s),o=a.length;if(o<2)return;var l=a.start(o-1),h=a.end(o-1);if(i>l||e>=l&&e<=h)return;r.hls.trigger(P.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}}))},i.getDurationAndRange=function(){var e,t=this.details,i=this.mediaSource;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;var r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,r)}}return{duration:1/0}}var s=null==(e=this.overrides)?void 0:e.duration;if(s)return _(s)?{duration:s}:null;var a=this.media.duration;return r>(_(i.duration)?i.duration:0)&&r>a||!_(a)?{duration:r}:null},i.updateMediaSource=function(e){var t=e.duration,i=e.start,r=e.end,n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==t&&(_(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),n.duration=t),void 0!==i&&void 0!==r&&(this.log("MediaSource duration is set to "+n.duration+". Setting seekable range to "+i+"-"+r+"."),n.setLiveSeekableRange(i,r)))},i.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,i=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+it(i)),this.tracksReady){var r,n=null==(r=this.transferData)?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}},i.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(i){var r=i[0],n=i[1];if(r){var s=e.tracks[r];t[r]={buffer:n,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}})),this.hls.trigger(P.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var i=t[0];e.executeNext(i)}))}else{var i=new Error("could not create source buffer for media codec(s)");this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:i,reason:i.message})}},i.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,i=this.mediaSource;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(var r in e){var n=r,s=e[n];if(this.isPending(s)){var a=this.getTrackCodec(s,n),o=s.container+";codecs="+a;s.codec=a,this.log("creating sourceBuffer("+o+")"+(this.currentOp(n)?" Queued":"")+" "+it(s));try{var l=i.addSourceBuffer(o),h=Qn(n),u=[n,l];t[h]=u,s.buffer=l}catch(e){var d;return this.error("error while trying to add sourceBuffer: "+e.message),this.shiftAndExecuteNext(n),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[n],void this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:s.id})}this.trackSourceBuffer(n,s)}}this.bufferCreated()},i.getTrackCodec=function(e,t){var i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&Oe(i,"video")&&(r=function(e,t){var i=[];if(e)for(var r=e.split(","),n=0;n<r.length;n++)Me(r[n],"video")||i.push(r[n]);return t&&i.push(t),i.join(",")}(r,i));var n=Ve(r,e.levelCodec);return n?"audio"===t.slice(0,5)?He(n,this.appendSource):n:""},i.trackSourceBuffer=function(e,t){var i=this,r=t.buffer;if(r){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(function(e,t){var r=t.removedRanges;null!=r&&r.length&&i.hls.trigger(P.BUFFER_FLUSHED,{type:e})}))}},i.onSBUpdateStart=function(e){var t=this.currentOp(e);t&&t.onStart()},i.onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)},i.onSBUpdateError=function(e,t){var i,r=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(i=this.mediaSource)?void 0:i.readyState));this.error(""+r,t),this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});var n=this.currentOp(e);n&&n.onError(r)},i.removeExecutor=function(e,t,i){var r=this.media,n=this.mediaSource,s=this.tracks[e],a=null==s?void 0:s.buffer;if(!r||!n||!a)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(e);var o=_(r.duration)?r.duration:1/0,l=_(n.duration)?n.duration:1/0,h=Math.max(0,t),u=Math.min(i,o,l);u>h&&(!s.ending||s.ended)?(s.ended=!1,this.log("Removing ["+h+","+u+"] from the "+e+" SourceBuffer"),a.remove(h,u)):this.shiftAndExecuteNext(e)},i.appendExecutor=function(e,t){var i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new Yn("Attempting to append to the "+t+" SourceBuffer, but it does not exist");i.ending=!1,i.ended=!1,r.appendBuffer(e)},i.blockUntilOpen=function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((function(e){t.warn("SourceBuffer blocked callback "+e),t.stepOperationQueue(t.sourceBufferTypes)}));else try{e()}catch(e){this.warn("Callback run without blocking "+this.operationQueue+" "+e)}},i.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],i=e[1];return t&&i.updating}))},i.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var i=t[0];return i&&!!e.currentOp(i)}))},i.isPending=function(e){return!!e&&!e.buffer},i.blockBuffers=function(e,t){var i=this;if(void 0===t&&(t=this.sourceBufferTypes),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var r=this.operationQueue,n=t.map((function(e){return i.appendBlocker(e)}));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then((function(t){r===i.operationQueue&&(e(),i.stepOperationQueue(i.sourceBufferTypes))}))},i.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var i,r=null==(i=t.tracks[e])?void 0:i.buffer;r&&!r.updating&&t.shiftAndExecuteNext(e)}))},i.append=function(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)},i.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},i.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},i.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},i.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},i.addBufferListener=function(e,t,i){var r=this.tracks[e];if(r){var n=r.buffer;if(n){var s=i.bind(this,e);r.listeners.push({event:t,listener:s}),n.addEventListener(t,s)}}},i.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var i=t.buffer;i&&(t.listeners.forEach((function(e){i.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},n(t,[{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){var r=e.tracks[i];return t[i]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var i,r,n=t[0];return n&&(!(null!=(i=e.tracks[n])&&i.ended)||(null==(r=e.tracks[n])?void 0:r.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,i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){return t+(e.isPending(e.tracks[i])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(e,t){return e+(t[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(e){return e[0]})).filter((function(e){return!!e}))}}])}(B);function Xn(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function Qn(e){return"audio"===e?1:0}var Jn,Zn=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 i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})},t.onMediaAttaching=function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},t.onManifestParsed=function(e,t){var i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&_(this.autoLevelCapping)&&this.detectPlayerSize()},t.onBufferCodecs=function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping(),this.media=null},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+i+": "+e[i].height+"p@"+e[i].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var i=this,r=this.hls.levels;if(!r.length)return-1;var n=r.filter((function(e,r){return i.isLevelAllowed(e)&&r<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},t.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,i){if(null==e||!e.length)return-1;for(var r,n,s=e.length-1,a=Math.max(t,i),o=0;o<e.length;o+=1){var l=e[o];if((l.width>=a||l.height>=a)&&(r=l,!(n=e[o+1])||r.width!==n.width||r.height!==n.height)){s=o;break}}return s},n(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)}}])}(),es="m",ts="a",is="v",rs="av",ns="i",ss="tt",as="h",os="CMCD-Request",ls="CMCD-Session",hs="CMCD-Status",us=((Jn={})["CMCD-Object"]=["br","d","ot","tb"],Jn[os]=["bl","dl","mtp","nor","nrr","su"],Jn[ls]=["cid","pr","sf","sid","st","v"],Jn[hs]=["bs","rtp"],Jn),ds=function e(t,i){Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=i},cs="Dict";function fs(e,t,i){return function(e,t,i,r){return new Error("failed to "+e+' "'+(n=t,(Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n))+'" as ')+i,{cause:r});var n}("serialize",e,t,i)}var gs=function(e){this.description=e},ps="Bare Item",vs="Boolean",ms="Byte Sequence";var ys="Integer";function Es(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw fs(e,ys);return e.toString()}var Ss="Decimal";function Ts(e){var t=mr(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw fs(e,Ss);var i=t.toString();return i.includes(".")?i:i+".0"}var Ls="String",_s=/[\x00-\x1f\x7f]+/,bs="Token";function As(e){var t,i=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw fs(i,bs);return i}function Is(e){switch(typeof e){case"number":if(!_(e))throw fs(e,ps);return Number.isInteger(e)?Es(e):Ts(e);case"string":return function(e){if(_s.test(e))throw fs(e,Ls);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(e);case"symbol":return As(e);case"boolean":return function(e){if("boolean"!=typeof e)throw fs(e,vs);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@"+Es(e.getTime()/1e3)}(e);if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw fs(e,ms);return":"+(t=e,btoa(String.fromCharCode.apply(String,t))+":");var t}(e);if(e instanceof gs)return As(e);default:throw fs(e,ps)}}var Rs="Key";function Ps(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw fs(e,Rs);return e}function ks(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],i=e[1];return!0===i?";"+Ps(t):";"+Ps(t)+"="+Is(i)})).join("")}function Ds(e){return e instanceof ds?""+Is(e.value)+ks(e.params):Is(e)}var ws=function(e){return Math.round(e)},Cs=function(e){return 100*ws(e/100)},Ms={br:ws,d:ws,bl:Cs,dl:Cs,mtp:Cs,nor:function(e,t){return(null==t?void 0:t.baseUrl)&&(e=function(e,t){var i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;for(var n=i.pathname.split("/").slice(1),s=r.pathname.split("/").slice(1,-1);n[0]===s[0];)n.shift(),s.shift();for(;s.length;)s.shift(),n.unshift("..");return n.join("/")}(e,t.baseUrl)),encodeURIComponent(e)},rtp:Cs,tb:ws};function Os(e,t){return void 0===t&&(t={}),e?function(e,t){return function(e,t){if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e)throw fs(e,cs);var i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map((function(e){var t=e[0],i=e[1];i instanceof ds==0&&(i=new ds(i));var r,n=Ps(t);return!0===i.value?n+=ks(i.params):(n+="=",Array.isArray(i.value)?n+="("+(r=i).value.map(Ds).join(" ")+")"+ks(r.params):n+=Ds(i)),n})).join(","+r)}(e,t)}(function(e,t){var i={};if(null==e||"object"!=typeof e)return i;var r=Object.keys(e).sort(),n=o({},Ms,null==t?void 0:t.formatters),s=null==t?void 0:t.filter;return r.forEach((function(r){if(!(null==s?void 0:s(r))){var a=e[r],o=n[r];o&&(a=o(a,t)),"v"===r&&1===a||"pr"==r&&1===a||function(e){return"number"==typeof e?_(e):null!=e&&""!==e&&!1!==e}(a)&&(function(e){return"ot"===e||"sf"===e||"st"===e}(r)&&"string"==typeof a&&(a=new gs(a)),i[r]=a)}})),i}(e,t),o({whitespace:!1},t)):""}var xs=/CMCD=[^&#]+/;var Fs=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){t.initialized&&(t.starved=!0),t.buffering=!0},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1},this.applyPlaylistData=function(e){try{t.apply(e,{ot:es,su:!t.initialized})}catch(e){t.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var i=e.frag,r=e.part,n=t.hls.levels[i.level],s=t.getObjectType(i),a={d:1e3*(r||i).duration,ot:s};s!==is&&s!==ts&&s!=rs||(a.br=n.bitrate/1e3,a.tb=t.getTopBandwidth(s)/1e3,a.bl=t.getBufferLength(s));var o=r?t.getNextPart(r):t.getNextFrag(i);null!=o&&o.url&&o.url!==i.url&&(a.nor=o.url),t.apply(e,a)}catch(e){t.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;var i=this.config=e.config,r=i.cmcd;null!=r&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHED,this.onMediaDetached,this),e.on(P.BUFFER_CREATED,this.onBufferCreated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHED,this.onMediaDetached,this),e.off(P.BUFFER_CREATED,this.onBufferCreated,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},t.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},t.onBufferCreated=function(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer},t.createData=function(){var e;return{v:1,sf:as,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},t.apply=function(e,t){void 0===t&&(t={}),o(t,this.createData());var i=t.ot===ns||t.ot===is||t.ot===rs;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var r=this.includeKeys;r&&(t=Object.keys(t).reduce((function(e,i){return r.includes(i)&&(e[i]=t[i]),e}),{}));var n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),function(e,t,i){o(e,function(e,t){void 0===t&&(t={});var i={};if(!e)return i;var r=Object.entries(e),n=Object.entries(us).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),s=r.reduce((function(e,t){var i,r,s=t[0],a=t[1],o=(null===(i=n.find((function(e){return e[1].includes(s)})))||void 0===i?void 0:i[0])||os;return null!==(r=e[o])&&void 0!==r||(e[o]={}),e[o][s]=a,e}),{});return Object.entries(s).reduce((function(e,i){var r=i[0],n=i[1];return e[r]=Os(n,t),e}),i)}(t,i))}(e.headers,t,n)):e.url=function(e,t,i){var r=function(e,t){if(void 0===t&&(t={}),!e)return"";var i=Os(e,t);return"CMCD="+encodeURIComponent(i)}(t,i);if(!r)return e;if(xs.test(e))return e.replace(xs,r);var n=e.includes("?")?"&":"?";return""+e+n+r}(e.url,t,n)},t.getNextFrag=function(e){var t,i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){var r=e.sn-i.startSN;return i.fragments[r+1]}},t.getNextPart=function(e){var t,i,r=e.index,n=e.fragment,s=null==(t=this.hls.levels[n.level])||null==(i=t.details)?void 0:i.partList;if(s)for(var a=n.sn,o=s.length-1;o>=0;o--){var l=s[o];if(l.index===r&&l.fragment.sn===a)return s[o+1]}},t.getObjectType=function(e){var t=e.type;return"subtitle"===t?ss:"initSegment"===e.sn?ns:"audio"===t?ts:"main"===t?this.hls.audioTracks.length?is:rs:void 0},t.getTopBandwidth=function(e){var t,i=0,r=this.hls;if(e===ts)t=r.audioTracks;else{var n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;t=r.levels.slice(0,a)}for(var o,l=s(t);!(o=l()).done;){var h=o.value;h.bitrate>i&&(i=h.bitrate)}return i>0?i:NaN},t.getBufferLength=function(e){var t=this.media,i=e===ts?this.audioBuffer:this.videoBuffer;return i&&t?1e3*Wt.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var r=e.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(e,i,r){t(e),this.loader.load(e,i,r)},n(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var r=e.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(e,i,r){t(e),this.loader.load(e,i,r)},n(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},e}(),Ns=function(e){function t(t){var i;return(i=e.call(this,"content-steering",t.logger)||this).hls=void 0,i.loader=null,i.uri=null,i.pathwayId=".",i._pathwayPriority=null,i.timeToLoad=300,i.reloadTimer=-1,i.updated=0,i.started=!1,i.enabled=!0,i.levels=null,i.audioTracks=null,i.subtitleTracks=null,i.penalizedPathways={},i.hls=t,i.registerListeners(),i}h(t,e);var i=t.prototype;return i.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)},i.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))},i.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},i.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},i.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},i.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},i.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},i.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},i.onManifestLoaded=function(e,t){var i=t.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())},i.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},i.onError=function(e,t){var i=t.errorAction;if(2===(null==i?void 0:i.action)&&1===i.flags){var r=this.levels,n=this._pathwayPriority,s=this.pathwayId;if(t.context){var a=t.context,o=a.groupId,l=a.pathwayId,h=a.type;o&&r?s=this.getPathwayForGroupId(o,h,s):l&&(s=l)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==s),i.resolved||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+s+" levels: "+(r?r.length:r)+" priorities: "+it(n)+" penalized: "+it(this.penalizedPathways))}},i.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var i=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+i+'"'),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t},i.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},i.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((function(e){r-i[e]>3e5&&delete i[e]}));for(var n=0;n<e.length;n++){var s=e[n];if(!(s in i)){if(s===this.pathwayId)return;var a=this.hls.nextLoadLevel,o=this.hls.levels[a];if((t=this.getLevelsForPathway(s)).length>0){this.log('Setting Pathway to "'+s+'"'),this.pathwayId=s,Yi(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}}}},i.getPathwayForGroupId=function(e,t,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),n=0;n<r.length;n++)if(t===w&&r[n].hasAudioGroup(e)||t===C&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i},i.clonePathways=function(e){var t=this,i=this.levels;if(i){var r={},n={};e.forEach((function(e){var s=e.ID,a=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!i.some((function(e){return e.pathwayId===s}))){var l=t.getLevelsForPathway(a).map((function(e){var t=new Jt(e.attrs);t["PATHWAY-ID"]=s;var i=t.AUDIO&&t.AUDIO+"_clone_"+s,a=t.SUBTITLES&&t.SUBTITLES+"_clone_"+s;i&&(r[t.AUDIO]=i,t.AUDIO=i),a&&(n[t.SUBTITLES]=a,t.SUBTITLES=a);var l=Us(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new et({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var u=1;u<e.audioGroups.length;u++)h.addGroupId("audio",e.audioGroups[u]+"_clone_"+s);if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)h.addGroupId("text",e.subtitleGroups[d]+"_clone_"+s);return h}));i.push.apply(i,l),Bs(t.audioTracks,r,o,s),Bs(t.subtitleTracks,n,o,s)}}))}},i.loadSteeringManifest=function(e){var t,i=this,r=this.hls.config,n=r.loader;this.loader&&this.loader.destroy(),this.loader=new n(r);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+e)}if("data:"!==t.protocol){var s=0|(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+s)}var a={responseType:"json",url:t.href},o=r.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},u={onSuccess:function(e,r,n,s){i.log('Loaded steering manifest: "'+t+'"');var a=e.data;if(1===(null==a?void 0:a.VERSION)){i.updated=performance.now(),i.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,t).href}catch(e){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}i.scheduleRefresh(i.uri||n.url),l&&i.clonePathways(l);var u={steeringManifest:a,url:t.toString()};i.hls.trigger(P.STEERING_MANIFEST_LOADED,u),h&&i.updatePathwayPriority(h)}else i.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(e,t,r,n){if(i.log("Error loading steering manifest: "+e.code+" "+e.text+" ("+t.url+")"),i.stopLoad(),410===e.code)return i.enabled=!1,void i.log("Steering manifest "+t.url+" no longer available");var s=1e3*i.timeToLoad;if(429!==e.code)i.scheduleRefresh(i.uri||t.url,s);else{var a=i.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(s=1e3*parseFloat(o))}i.log("Steering manifest "+t.url+" rate limited")}},onTimeout:function(e,t,r){i.log("Timeout loading steering manifest ("+t.url+")"),i.scheduleRefresh(i.uri||t.url)}};this.log("Requesting steering manifest: "+t),this.loader.load(a,h,u)},i.scheduleRefresh=function(e,t){var i=this;void 0===t&&(t=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var t,r=null==(t=i.hls)?void 0:t.media;!r||r.ended?i.scheduleRefresh(e,1e3*i.timeToLoad):i.loadSteeringManifest(e)}),t)},n(t,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}}])}(B);function Bs(e,t,i,r){e&&Object.keys(t).forEach((function(n){var s=e.filter((function(e){return e.groupId===n})).map((function(e){var s=o({},e);return s.details=void 0,s.attrs=new Jt(s.attrs),s.url=s.attrs.URI=Us(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),s.groupId=s.attrs["GROUP-ID"]=t[n],s.attrs["PATHWAY-ID"]=r,s}));e.push.apply(e,s)}))}function Us(e,t,i,r){var n,s=r.HOST,a=r.PARAMS,o=r[i];t&&(n=null==o?void 0:o[t])&&(e=n);var l=new self.URL(e);return s&&!n&&(l.host=s),a&&Object.keys(a).sort().forEach((function(e){e&&l.searchParams.set(e,a[e])})),l.href}var Gs=function(e){function t(i){var r;return(r=e.call(this,"eme",i.logger)||this).hls=void 0,r.config=void 0,r.media=null,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,n='"'+e.type+'" event: init data type: "'+t+'"';if(r.debug(n),null!==i){if(!r.keyFormatPromise){var s=Object.keys(r.keySystemAccessPromises);s.length||(s=pi(r.config));var a=s.map(gi).filter((function(e){return!!e}));r.keyFormatPromise=r.getKeyFormatPromise(a)}r.keyFormatPromise.then((function(s){var a,o,l=ci(s);if("sinf"===t){if(l!==oi.FAIRPLAY)return void r.warn('Ignoring unexpected "'+e.type+'" event with init data type: "'+t+'" for selected key-system '+l);var h=le(new Uint8Array(i));try{var u=Le(ni(JSON.parse(h).sinf));if(!u)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(u.subarray(8,24)),o=oi.FAIRPLAY}catch(e){return void r.warn(n+" Failed to parse sinf: "+e)}}else{if(l!==oi.WIDEVINE&&l!==oi.PLAYREADY)return void r.warn('Ignoring unexpected "'+e.type+'" event with init data type: "'+t+'" for selected key-system '+l);var d=function(e){var t=[];if(e instanceof ArrayBuffer)for(var i=e.byteLength,r=0;r+32<i;){var n=De(new DataView(e,r));t.push(n),r+=n.size}return t}(i),c=d.filter((function(e){return!!e.systemId&&fi(e.systemId)===l}));c.length>1&&r.warn(n+" Using first of "+c.length+" pssh found for selected key-system "+l);var f=c[0];if(!f)return void(0===d.length||d.some((function(e){return!e.systemId}))?r.warn(n+" contains incomplete or invalid pssh data"):r.log("ignoring "+n+" for "+d.map((function(e){return fi(e.systemId)})).join(",")+" pssh data in favor of playlist keys"));if(o=fi(f.systemId),0===f.version&&f.data)if(o===oi.WIDEVINE){var g=f.data.length-22;a=new Uint8Array(f.data.subarray(g,g+16))}else o===oi.PLAYREADY&&(a=yi(f.data))}if(o&&a){for(var p,v=z(a),m=r,y=m.keyIdToKeySessionPromise,E=m.mediaKeySessions,S=y[v],T=function(){var e=E[L],n=e.decryptdata;if(!n.keyId)return 0;var s=z(n.keyId);return v===s||-1!==n.uri.replace(/-/g,"").indexOf(v)?(S=y[s],n.pssh||(delete y[s],n.pssh=new Uint8Array(i),n.keyId=a,(S=y[v]=S.then((function(){return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-key-match")}))).catch((function(e){return r.handleError(e)}))),1):void 0},L=0;L<E.length&&(0===(p=T())||1!==p);L++);if(!S){if(o!==l)return void r.log('Ignoring "'+e.type+'" event with '+o+" init data for selected key-system "+l);S=y[v]=r.getKeySystemSelectionPromise([o]).then((function(e){var n,s=e.keySystem,o=e.mediaKeys;r.throwIfDestroyed();var l=new Si("ISO-23001-7",v,null!=(n=gi(s))?n:"");return l.pssh=new Uint8Array(i),l.keyId=a,r.attemptSetMediaKeys(s,o).then((function(){r.throwIfDestroyed();var e=r.createMediaKeySessionContext({decryptdata:l,keySystem:s,mediaKeys:o});return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-no-match")}))})),S.catch((function(e){return r.handleError(e)}))}}}))}},r.onWaitingForKey=function(e){r.log('"'+e.type+'" event')},r.hls=i,r.config=i.config,r.registerListeners(),r}h(t,e);var i=t.prototype;return i.destroy=function(){var e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);var t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null},i.registerListeners=function(){this.hls.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(P.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(P.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(P.MANIFEST_LOADED,this.onManifestLoaded,this)},i.unregisterListeners=function(){this.hls.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(P.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(P.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(P.MANIFEST_LOADED,this.onManifestLoaded,this)},i.getLicenseServerUrl=function(e){var t=this.config,i=t.drmSystems,r=t.widevineLicenseUrl,n=i[e];return n?n.licenseUrl:e===oi.WIDEVINE&&r?r:void 0},i.getLicenseServerUrlOrThrow=function(e){var t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error('no license server URL configured for key-system "'+e+'"');return t},i.getServerCertificateUrl=function(e){var t=this.config.drmSystems[e];if(t)return t.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+e+'"]')},i.attemptKeySystemAccess=function(e){var t=this,i=this.hls.levels,r=function(e,t,i){return!!e&&i.indexOf(e)===t},n=i.map((function(e){return e.audioCodec})).filter(r),s=i.map((function(e){return e.videoCodec})).filter(r);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((function(i,r){var a=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,s).then((function(e){return i({keySystem:o,mediaKeys:e})})).catch((function(t){e.length?a(e):r(t instanceof Hs?t:new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};a(e)}))},i.requestMediaKeySystemAccess=function(e,t){var i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function "+i;return null===mi&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(r))}return i(e,t)},i.getMediaKeysPromise=function(e,t,i){var r=this,n=function(e,t,i,r){var n;switch(e){case oi.FAIRPLAY:n=["cenc","sinf"];break;case oi.WIDEVINE:case oi.PLAYREADY:n=["cenc"];break;case oi.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+e)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((function(e){return{contentType:"audio/mp4; codecs="+e,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}})),videoCapabilities:i.map((function(e){return{contentType:"video/mp4; codecs="+e,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}}))}]}(n,t,i,r)}(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e],a=null==s?void 0:s.keySystemAccess;if(!a){this.log('Requesting encrypted media "'+e+'" key-system access with config: '+it(n)),a=this.requestMediaKeySystemAccess(e,n);var o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch((function(t){r.log('Failed to obtain access to key-system "'+e+'": '+t)})),a.then((function(t){r.log('Access for key-system "'+t.keySystem+'" obtained');var i=r.fetchServerCertificate(e);return r.log('Create media-keys for "'+e+'"'),o.mediaKeys=t.createMediaKeys().then((function(t){return r.log('Media-keys created for "'+e+'"'),i.then((function(i){return i?r.setMediaKeysServerCertificate(t,e,i):t}))})),o.mediaKeys.catch((function(t){r.error('Failed to create media-keys for "'+e+'"}: '+t)})),o.mediaKeys}))}return a.then((function(){return s.mediaKeys}))},i.createMediaKeySessionContext=function(e){var t=e.decryptdata,i=e.keySystem,r=e.mediaKeys;this.log('Creating key-system session "'+i+'" keyId: '+z(t.keyId||[]));var n=r.createSession(),s={decryptdata:t,keySystem:i,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s},i.renewKeySession=function(e){var t=e.decryptdata;if(t.pssh){var i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)},i.getKeyIdString=function(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return z(e.keyId)},i.updateKeySession=function(e,t){var i,r=e.mediaKeysSession;return this.log('Updating key-session "'+r.sessionId+'" for keyID '+z((null==(i=e.decryptdata)?void 0:i.keyId)||[])+"\n } (data length: "+(t?t.byteLength:t)+")"),r.update(t)},i.selectKeySystemFormat=function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: "+e.sn+" "+e.type+": "+e.level+") key formats "+t.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise},i.getKeyFormatPromise=function(e){var t=this;return new Promise((function(i,r){var n=pi(t.config),s=e.map(ci).filter((function(e){return!!e&&-1!==n.indexOf(e)}));return t.getKeySystemSelectionPromise(s).then((function(e){var t=e.keySystem,n=gi(t);n?i(n):r(new Error('Unable to find format for key-system "'+t+'"'))})).catch(r)}))},i.loadKey=function(e){var t=this,i=e.keyInfo.decryptdata,r=this.getKeyIdString(i),n="(keyId: "+r+' format: "'+i.keyFormat+'" method: '+i.method+" uri: "+i.uri+")";this.log("Starting session for key "+n);var s=this.keyIdToKeySessionPromise[r];return s||(s=this.getKeySystemForKeyPromise(i).then((function(r){var s=r.keySystem,a=r.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: "+e.frag.sn+" "+e.frag.type+": "+e.frag.level+" using key "+n),t.attemptSetMediaKeys(s,a).then((function(){return t.throwIfDestroyed(),t.createMediaKeySessionContext({keySystem:s,mediaKeys:a,decryptdata:i})}))})),(this.keyIdToKeySessionPromise[r]=s.then((function(e){var r=i.pssh?i.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",r,"playlist-key")}))).catch((function(e){return t.handleError(e)}))),s},i.throwIfDestroyed=function(e){if(!this.hls)throw new Error("invalid state")},i.handleError=function(e){this.hls&&(this.error(e.message),e instanceof Hs?this.hls.trigger(P.ERROR,e.data):this.hls.trigger(P.ERROR,{type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))},i.getKeySystemForKeyPromise=function(e){var t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){var r=ci(e.keyFormat),n=r?[r]:pi(this.config);return this.attemptKeySystemAccess(n)}return i},i.getKeySystemSelectionPromise=function(e){if(e.length||(e=pi(this.config)),0===e.length)throw new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+it({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(e)},i.attemptSetMediaKeys=function(e,t){var i=this,r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+e+'"');var n=Promise.all(r).then((function(){if(!i.media)throw new Error("Attempted to set mediaKeys without media element attached");return i.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(n),n.then((function(){i.log('Media-keys set for "'+e+'"'),r.push(n),i.setMediaKeysQueue=i.setMediaKeysQueue.filter((function(e){return-1===r.indexOf(e)}))}))},i.generateRequestWithPreferredKeySession=function(e,t,i,r){var n,s,a=this,o=null==(n=this.config.drmSystems)||null==(s=n[e.keySystem])?void 0:s.generateRequest;if(o)try{var l=o.call(this.hls,t,i,e);if(!l)throw new Error("Invalid response from configured generateRequest filter");t=l.initDataType,i=l.initData?l.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){var h;if(this.warn(e.message),null!=(h=this.hls)&&h.config.debug)throw e}if(null===i)return this.log('Skipping key-session request for "'+r+'" (no initData)'),Promise.resolve(e);var u=this.getKeyIdString(e.decryptdata);this.log('Generating key-session request for "'+r+'": '+u+" (init data type: "+t+" length: "+(i?i.byteLength:null)+")");var d=new S,c=e._onmessage=function(t){var i=e.mediaKeysSession;if(i){var r=t.messageType,n=t.message;a.log('"'+r+'" message event for session "'+i.sessionId+'" message size: '+n.byteLength),"license-request"===r||"license-renewal"===r?a.renewLicense(e,n).catch((function(e){d.eventNames().length?d.emit("error",e):a.handleError(e)})):"license-release"===r?e.keySystem===oi.FAIRPLAY&&(a.updateKeySession(e,si("acknowledged")),a.removeSession(e)):a.warn('unhandled media key message type "'+r+'"')}else d.emit("error",new Error("invalid state"))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){a.onKeyStatusChange(e);var i=e.keyStatus;d.emit("keyStatus",i),"expired"===i&&(a.warn(e.keySystem+" expired for key "+u),a.renewKeySession(e))}else d.emit("error",new Error("invalid state"))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",f);var g=new Promise((function(e,t){d.on("error",t),d.on("keyStatus",(function(i){i.startsWith("usable")?e():"output-restricted"===i?t(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},'key status changed to "'+i+'"')):"expired"===i?t(new Error("key expired while generating request")):a.warn('unhandled key status change "'+i+'"')}))}));return e.mediaKeysSession.generateRequest(t,i).then((function(){var t;a.log('Request generated for key-session "'+(null==(t=e.mediaKeysSession)?void 0:t.sessionId)+'" keyId: '+u)})).catch((function(e){throw new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},"Error generating key-session request: "+e)})).then((function(){return g})).catch((function(t){throw d.removeAllListeners(),a.removeSession(e),t})).then((function(){return d.removeAllListeners(),e}))},i.onKeyStatusChange=function(e){var t=this;e.mediaKeysSession.keyStatuses.forEach((function(i,r){if("string"==typeof r&&"object"==typeof i){var n=r;r=i,i=n}t.log('key status change "'+i+'" for keyStatuses keyId: '+z("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))+" session keyId: "+z(new Uint8Array(e.decryptdata.keyId||[]))+" uri: "+e.decryptdata.uri),e.keyStatus=i}))},i.fetchServerCertificate=function(e){var t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log('Fetching server certificate for "'+e+'"'),new Promise((function(n,s){var a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(e,t,i,r){n(e.data)},onError:function(t,i,n,o){s(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:c({url:a.url,data:void 0},t)},'"'+e+'" certificate request failed ('+r+"). Status: "+t.code+" ("+t.text+")"))},onTimeout:function(t,i,n){s(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:a.url,data:void 0}},'"'+e+'" certificate request timed out ('+r+")"))},onAbort:function(e,t,i){s(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()},i.setMediaKeysServerCertificate=function(e,t,i){var r=this;return new Promise((function(n,s){e.setServerCertificate(i).then((function(s){r.log("setServerCertificate "+(s?"success":"not supported by CDM")+" ("+(null==i?void 0:i.byteLength)+') on "'+t+'"'),n(e)})).catch((function(e){s(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))},i.renewLicense=function(e,t){var i=this;return this.requestLicense(e,new Uint8Array(t)).then((function(t){return i.updateKeySession(e,new Uint8Array(t)).catch((function(e){throw new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))}))},i.unpackPlayReadyKeyMessage=function(e,t){var i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var r=(new DOMParser).parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0)for(var s,a=0,o=n.length;a<o;a++){var l,h,u=null==(l=(s=n[a]).querySelector("name"))?void 0:l.textContent,d=null==(h=s.querySelector("value"))?void 0:h.textContent;u&&d&&e.setRequestHeader(u,d)}var c=r.querySelector("Challenge"),f=null==c?void 0:c.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return si(atob(f))},i.setupLicenseXHR=function(e,t,i,r){var n=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then((function(){if(!i.decryptdata)throw new Error("Key removed");return s.call(n.hls,e,t,i,r)})).catch((function(a){if(!i.decryptdata)throw a;return e.open("POST",t,!0),s.call(n.hls,e,t,i,r)})).then((function(i){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))},i.requestLicense=function(e,t){var i=this,r=this.config.keyLoadPolicy.default;return new Promise((function(n,s){var a=i.getLicenseServerUrlOrThrow(e.keySystem);i.log("Sending license request to URL: "+a);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var h=i.config.licenseResponseCallback;if(h)try{l=h.call(i.hls,o,a,e)}catch(e){i.error(e)}n(l)}else{var u=r.errorRetry,d=u?u.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>d||o.status>=400&&o.status<500)s(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+a+"). Status: "+o.status+" ("+o.statusText+")"));else{var c=d-i._requestLicenseFailureCount+1;i.warn("Retrying license request, "+c+" attempts left"),i.requestLicense(e,t).then(n,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,i.setupLicenseXHR(o,a,e,t).then((function(t){var r=t.xhr,n=t.licenseChallenge;e.keySystem==oi.PLAYREADY&&(n=i.unpackPlayReadyKeyMessage(r,n)),r.send(n)}))}))},i.onMediaAttached=function(e,t){if(this.config.emeEnabled){var i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}},i.onMediaDetached=function(){var e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)},i._clear=function(e){var i,r=this,n=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Si.clearKeyUriToKeyIdMap();var s=n.length;t.CDMCleanupPromise=Promise.all(n.map((function(e){return r.removeSession(e)})).concat(null==e||null==(i=e.setMediaKeys(null))?void 0:i.catch((function(e){var t;r.log("Could not clear media keys: "+e),null==(t=r.hls)||t.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+e)})})))).then((function(){s&&(r.log("finished closing key sessions and clearing media keys"),n.length=0)})).catch((function(e){var t;r.log("Could not close sessions and clear media keys: "+e),null==(t=r.hls)||t.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+e)})}))},i.onManifestLoading=function(){this.keyFormatPromise=null},i.onManifestLoaded=function(e,t){var i=t.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+r.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(r)}},i.removeSession=function(e){var t=this,i=e.mediaKeysSession,r=e.licenseXhr;if(i){this.log("Remove licenses and keys and close session "+i.sessionId),e._onmessage&&(i.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);var s=function(e){var t;return"persistent-license"===e.sessionType||!(null==(t=e.sessionTypes)||!t.some((function(e){return"persistent-license"===e})))}(this.config.drmSystemOptions)?new Promise((function(e,t){self.setTimeout((function(){return t(new Error("MediaKeySession.remove() timeout"))}),8e3),i.remove().then(e)})):Promise.resolve();return s.catch((function(e){var i;t.log("Could not remove session: "+e),null==(i=t.hls)||i.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+e)})})).then((function(){return i.close()})).catch((function(e){var i;t.log("Could not close session: "+e),null==(i=t.hls)||i.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+e)})}))}},t}(B);Gs.CDMCleanupPromise=void 0;var Hs=function(e){function t(t,i){var r;return(r=e.call(this,i)||this).data=void 0,t.error||(t.error=new Error(i)),r.data=t,t.err=t.error,r}return h(t,e),t}(p(Error)),Vs=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 i=this.hls.config;if(i.capLevelOnFPSDrop){var r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,i){var r=performance.now();if(t){if(this.lastTime){var n=r-this.lastTime,s=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*s/n,l=this.hls;if(l.trigger(P.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:i}),o>0&&s>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=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}();function Ks(e){for(var t=5381,i=e.length;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}var Ws=.025,$s=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function qs(e,t,i){return e.identifier+"-"+(i+1)+"-"+Ks(t)}var js=function(){function e(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}var t=e.prototype;return t.setDateRange=function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)},t.reset=function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)},t.isAssetPastPlayoutLimit=function(e){if(e>=this.assetList.length)return!0;var t=this.playoutLimit;return!(e<=0||isNaN(t))&&this.assetList[e].startOffset>t},t.findAssetIndex=function(e){return this.assetList.indexOf(e)},t.toString=function(){return'["'+(e=this).identifier+'" '+(e.cue.pre?"<pre>":e.cue.post?"<post>":"")+e.timelineStart.toFixed(2)+"-"+e.resumeTime.toFixed(2)+"]";var e},n(e,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return Ys(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-Ys(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=_(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return Ys(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Ws))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?$s.Range:$s.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}}])}();function Ys(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Ws)?t.start:t.start+t.duration}function zs(e,t,i){var r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function Xs(e){var t=e.timelineStart,i=e.duration||0;return'["'+e.identifier+'" '+t.toFixed(2)+"-"+(t+i).toFixed(2)+"]"}var Qs=function(){function e(e,t,i,r){var n=this;this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){var e=n.interstitial.playoutLimit,t=n.currentTime;n.startOffset+t>=e&&n.hls.trigger(P.PLAYOUT_LIMIT_REACHED,{})};var s=this.hls=new e(t);this.interstitial=i,this.assetItem=r;var a=r.uri;try{a=zs(a,s.sessionId).href}catch(e){}s.loadSource(a);var o=function(){n.hasDetails=!0};s.once(P.LEVEL_LOADED,o),s.once(P.AUDIO_TRACK_LOADED,o),s.once(P.SUBTITLE_TRACK_LOADED,o),s.on(P.MEDIA_ATTACHING,(function(e,t){var i=t.media;n.removeMediaListeners(),n.mediaAttached=i,n.interstitial.playoutLimit&&i.addEventListener("timeupdate",n.checkPlayout)}))}var t=e.prototype;return t.bufferedInPlaceToEnd=function(e){var t;if(!this.interstitial.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;var i=this.timelineOffset,r=Wt.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=this._bufferedEosTime-.02},t.getAssetTime=function(e){var t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)},t.removeMediaListeners=function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))},t.bufferSnapShot=function(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},t.destroy=function(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null},t.attachMedia=function(e){this.hls.attachMedia(e)},t.detachMedia=function(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()},t.resumeBuffering=function(){this.hls.resumeBuffering()},t.pauseBuffering=function(){this.hls.pauseBuffering()},t.transferMedia=function(){return this.bufferSnapShot(),this.hls.transferMedia()},t.on=function(e,t,i){this.hls.on(e,t)},t.once=function(e,t,i){this.hls.once(e,t)},t.off=function(e,t,i){this.hls.off(e,t)},t.toString=function(){var e,t;return"HlsAssetPlayer: "+Xs(this.assetItem)+" "+(null==(e=this.hls)?void 0:e.sessionId)+" "+(null!=(t=this.interstitial)&&t.appendInPlace?"append-in-place":"")},n(e,[{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=Wt.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){return this.assetItem.duration||0}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var i=e-t;if(Math.abs(i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}}])}(),Js=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials-sched",i)||this).onScheduleUpdate=void 0,r.eventMap={},r.events=null,r.items=null,r.durations={primary:0,playout:0,integrated:0},r.onScheduleUpdate=t,r}h(t,e);var i=t.prototype;return i.destroy=function(){this.reset(),this.onScheduleUpdate=null},i.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(e){return e.reset()})),this.events=this.items=null},i.resetErrorsInRange=function(e,t){return this.events?this.events.reduce((function(i,r){return e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i}),0):0},i.getEvent=function(e){return e&&this.eventMap[e]||null},i.hasEvent=function(e){return e in this.eventMap},i.findItemIndex=function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);var r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(n=r[i])&&n.event;){var n;i--}return i},i.findItemIndexAtTime=function(e,t){var i=this.items;if(i)for(var r=0;r<i.length;r++){var n=i[r];if(t&&"primary"!==t&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1},i.findJumpRestrictedIndex=function(e,t){var i=this.items;if(i)for(var r=e;r<=t&&i[r];r++){var n=i[r].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return r}return-1},i.findEventIndex=function(e){var t=this.items;if(t)for(var i=t.length;i--;){var r;if((null==(r=t[i].event)?void 0:r.identifier)===e)return i}return-1},i.findAssetIndex=function(e,t){var i=e.assetList,r=i.length;if(r>1)for(var n=0;n<r;n++){var s=i[n];if(!s.error){var a=s.timelineStart;if(t===a||t>a&&t<a+(s.duration||0))return n}}return 0},i.parseInterstitialDateRanges=function(e,t){var i=this,r=e.main.details,n=r.dateRanges,s=this.events,a=this.parseDateRanges(n,{url:r.url},t),o=Object.keys(n),l=s?s.filter((function(e){return!o.includes(e.identifier)})):[];a.length&&a.sort((function(e,t){var i=e.cue.pre,r=e.cue.post,n=t.cue.pre,s=t.cue.post;if(i&&!n)return-1;if(n&&!i)return 1;if(r&&!s)return 1;if(s&&!r)return-1;if(!(i||n||r||s)){var a=e.startTime,o=t.startTime;if(a!==o)return a-o}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=a,l.forEach((function(e){i.removeEvent(e)})),this.updateSchedule(e,l)},i.updateSchedule=function(e,t){void 0===t&&(t=[]);var i=this.events||[];if(i.length||t.length||this.length<2){var r=this.items,n=this.parseSchedule(i,e);(t.length||(null==r?void 0:r.length)!==n.length||n.some((function(e,t){return Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005})))&&(this.items=n,this.onScheduleUpdate(t,r))}},i.parseDateRanges=function(e,t,i){for(var r=[],n=Object.keys(e),s=0;s<n.length;s++){var a=n[s],o=e[a];if(o.isInterstitial){var l=this.eventMap[a];l?l.setDateRange(o):(l=new js(o,t),this.eventMap[a]=l,!1===i&&(l.appendInPlace=i)),r.push(l)}}return r},i.parseSchedule=function(e,t){var i=[],r=t.main.details,n=r.live?1/0:r.edge,s=0;if((e=e.filter((function(e){return!(e.error||e.cue.once&&e.hasPlayed)}))).length){this.resolveOffsets(e,t);var a=0,o=0;if(e.forEach((function(t,r){var l=t.cue.pre,h=t.cue.post,u=e[r-1]||null,d=t.appendInPlace,c=h?n:t.startOffset,f=t.duration,g=t.timelineOccupancy===$s.Range?f:0,p=t.resumptionOffset,v=(null==u?void 0:u.startTime)===c,m=c+t.cumulativeDuration,y=d?m+f:c+p;if(l||!h&&c<=0){var E=o;o+=g,t.timelineStart=m;var S=s;s+=f,i.push({event:t,start:m,end:y,playout:{start:S,end:s},integrated:{start:E,end:o}})}else{if(!(c<=n))return;if(!v){var T=c-a;if(T>.033){var L=a,_=o;o+=T;var b=s;s+=T;var A={previousEvent:e[r-1]||null,nextEvent:t,start:L,end:L+T,playout:{start:b,end:s},integrated:{start:_,end:o}};i.push(A)}else T>0&&u&&(u.cumulativeDuration+=T,i[i.length-1].end=c)}h&&(y=m),t.timelineStart=m;var I=o;o+=g;var R=s;s+=f,i.push({event:t,start:m,end:y,playout:{start:R,end:s},integrated:{start:I,end:o}})}var P=t.resumeTime;a=h||P>n?n:P})),a<n){var l,h=a,u=o,d=n-a;o+=d;var c=s;s+=d,i.push({previousEvent:(null==(l=i[i.length-1])?void 0:l.event)||null,nextEvent:null,start:a,end:h+d,playout:{start:c,end:s},integrated:{start:u,end:o}})}this.setDurations(n,s,o)}else i.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return i},i.setDurations=function(e,t,i){this.durations={primary:e,playout:t,integrated:i}},i.resolveOffsets=function(e,t){var i=this,r=t.main.details,n=r.live?1/0:r.edge,s=0,a=-1;e.forEach((function(o,l){var h=o.cue.pre,u=o.cue.post,d=h?0:u?n:o.startTime;i.updateAssetDurations(o),a===d?o.cumulativeDuration=s:(s=0,a=d),!u&&o.snapOptions.in&&(o.resumeAnchor=ft(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(i.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&i.warn("Could not change append strategy for abutting event "+o));var c=_(o.resumeOffset)?o.resumeOffset:o.duration;s+=c}))},i.primaryCanResumeInPlaceAt=function(e,t){var i=this,r=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(r-n)>Ws?(this.log('"'+e.identifier+'" resumption '+r+" not aligned with estimated timeline end "+n),!1):t?!Object.keys(t).some((function(n){var s=t[n].details,a=s.edge;if(r>=a)return i.log('"'+e.identifier+'" resumption '+r+" past "+n+" playlist end "+a),!1;var o=ft(null,s.fragments,r);if(!o)return i.log('"'+e.identifier+'" resumption '+r+" does not align with any fragments in "+n+" playlist ("+s.fragStart+"-"+s.fragmentEnd+")"),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-r)<Ws+l||Math.abs(o.end-r)<Ws+l||(i.log('"'+e.identifier+'" resumption '+r+" not aligned with "+n+" fragment bounds ("+o.start+"-"+o.end+" sn: "+o.sn+" cc: "+o.cc+")"),0))})):(this.log('"'+e.identifier+'" resumption '+r+" can not be aligned with media (none selected)"),!1)},i.updateAssetDurations=function(e){if(e.assetListLoaded){var t=e.timelineStart,i=0,r=!1,n=!1;e.assetList.forEach((function(e,s){var a=t+i;e.startOffset=i,e.timelineStart=a,r||(r=null===e.duration),n||(n=!!e.error);var o=e.error?0:e.duration||0;i+=o})),e.duration=r&&!n?Math.max(i,e.duration):i}},i.removeEvent=function(e){e.reset(),delete this.eventMap[e.identifier]},n(t,[{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"assetIdAtEnd",get:function(){var e,t,i=null==(e=this.items)||null==(t=e[this.length-1])?void 0:t.event;if(i){var r=i.assetList,n=r[r.length-1];if(n)return n.identifier}return null}}])}(B);function Zs(e){return"["+(e.event?'"'+e.event.identifier+'"':"primary")+": "+e.start.toFixed(2)+"-"+e.end.toFixed(2)+"]"}var ea=function(){function e(e){this.hls=void 0,this.hls=e}var t=e.prototype;return t.destroy=function(){this.hls=null},t.loadAssetList=function(e,t){var i,r=this,n=e.assetListUrl;try{i=zs(n,this.hls.sessionId,e.baseUrl)}catch(t){var s=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,t,n);return void this.hls.trigger(P.ERROR,s)}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);var a=this.hls.config,o=new(0,a.loader)(a),l={responseType:"json",url:i.href},h=a.interstitialAssetListLoadPolicy.default,u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,i,n,s){var a=t.data,o=null==a?void 0:a.ASSETS;if(Array.isArray(o))e.assetListResponse=a,r.hls.trigger(P.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:s});else{var l=r.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,i,s);r.hls.trigger(P.ERROR,l)}},onError:function(t,i,n,s){var a=r.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status "+t.code+" "+t.text+" ("+i.url+")"),i.url,s,n);r.hls.trigger(P.ERROR,a)},onTimeout:function(t,i,n){var s=r.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST ("+i.url+")"),i.url,t,n);r.hls.trigger(P.ERROR,s)}};return o.load(l,u,d),this.hls.trigger(P.ASSET_LIST_LOADING,{event:e}),o},t.assignAssetListError=function(e,t,i,r,n,s){return e.error=i,{type:I.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:s,stats:n}},e}();function ta(e,t,i){ia(e,t,i),e.addEventListener(t,i)}function ia(e,t,i){e.removeEventListener(t,i)}function ra(e){null==e||e.play().catch((function(){}))}var na=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials",t.logger)||this).HlsPlayerClass=void 0,r.hls=void 0,r.assetListLoader=void 0,r.mediaSelection=null,r.altSelection=null,r.media=null,r.detachedData=null,r.requiredTracks=null,r.manager=null,r.playerQueue=[],r.bufferedPos=-1,r.timelinePos=-1,r.schedule=void 0,r.playingItem=null,r.bufferingItem=null,r.waitingItem=null,r.endedItem=null,r.playingAsset=null,r.endedAsset=null,r.bufferingAsset=null,r.shouldPlay=!1,r.onPlay=function(){r.shouldPlay=!0},r.onPause=function(){r.shouldPlay=!1},r.onSeeking=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled){var t=e-r.timelinePos;if(!(Math.abs(t)<1/7056e5)){var i=t<=-.01;r.timelinePos=e,r.bufferedPos=e;var n=r.playingItem;if(n)if(i&&r.schedule.resetErrorsInRange(e,e-t)&&r.updateSchedule(),r.checkBuffer(),i&&e<n.start||e>=n.end){var s,a=r.schedule.findItemIndexAtTime(r.timelinePos);if(!r.isInterstitial(n)&&null!=(s=r.media)&&s.paused&&(r.shouldPlay=!1),!i){var o=r.findItemIndex(n);if(a>o){var l=r.schedule.findJumpRestrictedIndex(o+1,a);if(l>o)return void r.setSchedulePosition(l)}}r.setSchedulePosition(a)}else{var h=r.playingAsset;if(h){var u=h.timelineStart,d=h.duration||0;(i&&e<u||e>=u+d)&&r.setScheduleToAssetAtTime(e,h)}else if(r.playingLastItem&&r.isInterstitial(n)){var c=n.event.assetList[0];c&&(r.endedItem=r.playingItem,r.playingItem=null,r.setScheduleToAssetAtTime(e,c))}}else r.checkBuffer()}}},r.onTimeupdate=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&e>r.timelinePos){r.timelinePos=e,e>r.bufferedPos&&r.checkBuffer();var t=r.playingItem;if(t&&!r.playingLastItem){if(e>=t.end){r.timelinePos=t.end;var i=r.findItemIndex(t);r.setSchedulePosition(i+1)}var n=r.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&r.setScheduleToAssetAtTime(e,n)}}},r.onScheduleUpdate=function(e,t){var i=r.schedule,n=r.playingItem,s=i.events||[],a=i.items||[],o=i.durations,l=e.map((function(e){return e.identifier})),h=!(!s.length&&!l.length);if(h&&r.log("INTERSTITIALS_UPDATED ("+s.length+"): "+s+"\nSchedule: "+a.map((function(e){return Zs(e)}))),l.length&&r.log("Removed events "+l),r.playerQueue.forEach((function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(n){Math.abs(i)>Ws&&r.warn(n+' ("'+e.assetId+'" '+e.timelineOffset+"->"+t+")")}}})),n){var u=r.updateItem(n,r.timelinePos);r.itemsMatch(n,u)&&(r.playingItem=u,r.waitingItem=r.endedItem=null)}else r.waitingItem=r.updateItem(r.waitingItem),r.endedItem=r.updateItem(r.endedItem);var d=r.bufferingItem;if(d){var c=r.updateItem(d,r.bufferedPos);r.itemsMatch(d,c)?r.bufferingItem=c:d.event&&(r.bufferingItem=r.playingItem,r.clearInterstitial(d.event,null))}if(e.forEach((function(e){e.assetList.forEach((function(e){r.clearAssetPlayer(e.identifier,null)}))})),h||t){if(r.hls.trigger(P.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:a.slice(0),durations:o,removedIds:l}),r.isInterstitial(n)&&l.includes(n.event.identifier))return r.warn('Interstitial "'+n.event.identifier+'" removed while playing'),void r.primaryFallback(n.event);r.checkBuffer()}},r.hls=t,r.HlsPlayerClass=i,r.assetListLoader=new ea(t),r.schedule=new Js(r.onScheduleUpdate,t.logger),r.registerListeners(),r}h(t,e);var i=t.prototype;return i.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.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(P.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(P.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(P.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(P.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this),e.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(P.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(P.MEDIA_ENDED,this.onMediaEnded,this),e.on(P.ERROR,this.onError,this),e.on(P.DESTROYING,this.onDestroying,this)},i.unregisterListeners=function(){var e=this.hls;e&&(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.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(P.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(P.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(P.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(P.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this),e.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(P.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(P.MEDIA_ENDED,this.onMediaEnded,this),e.off(P.ERROR,this.onError,this),e.off(P.DESTROYING,this.onDestroying,this))},i.startLoad=function(){this.resumeBuffering()},i.stopLoad=function(){this.pauseBuffering()},i.resumeBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()},i.pauseBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},i.onDestroying=function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)},i.removeMediaListeners=function(e){ia(e,"play",this.onPlay),ia(e,"pause",this.onPause),ia(e,"seeking",this.onSeeking),ia(e,"timeupdate",this.onTimeupdate)},i.onMediaAttaching=function(e,t){var i=this.media=t.media;ta(i,"seeking",this.onSeeking),ta(i,"timeupdate",this.onTimeupdate),ta(i,"play",this.onPlay),ta(i,"pause",this.onPause)},i.onMediaAttached=function(e,t){var i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();var n=this.findItemIndex(i);this.setSchedulePosition(n)}},i.clearScheduleState=function(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}},i.isInterstitial=function(e){return!(null==e||!e.event)},i.retreiveMediaSource=function(e,t){var i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)},i.transferMediaFromPlayer=function(e,t){var i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});var n=e.transferMedia();this.log("transfer MediaSource from "+e+" "+it(n)),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))},i.transferMediaTo=function(e,t){var i,r,n=this;if(e.media!==t){var s,a=null,o=this.hls,l=e!==o,h=l&&e.interstitial.appendInPlace,u=null==(i=this.detachedData)?void 0:i.mediaSource;if(o.media)h&&(a=o.transferMedia(),this.detachedData=a),s="Primary";else if(u){var d=this.getBufferingPlayer();d?(a=d.transferMedia(),s=""+d):s="detached MediaSource"}else s="detached media";if(!a)if(u)a=this.detachedData,this.log("using detachedData: MediaSource "+it(a));else if(!this.detachedData||o.media===t){var c=this.playerQueue;c.length>1&&c.forEach((function(e){if(l&&e.interstitial.appendInPlace!==h){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets "+t)}})),this.hls.detachMedia(),this.detachedData={media:t}}var f=a&&"mediaSource"in a&&"closed"!==(null==(r=a.mediaSource)?void 0:r.readyState),g=f&&a?a:t;if(this.log((f?"transfering MediaSource":"attaching media")+" to "+(l?e:"Primary")+" from "+s),g===a){var p=l&&e.assetId===this.schedule.assetIdAtEnd;g.overrides={duration:this.schedule.duration,endOfStream:!l||p,cueRemoval:!l}}e.attachMedia(g)}},i.onInterstitialCueEnter=function(){this.onTimeupdate()},i.checkStart=function(){var e=this.schedule,t=e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){var n=this.hls.startPosition;if(this.timelinePos=n,t.length&&t[0].cue.pre){var s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(n>=0||!this.primaryLive){var a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){var l=e.findItemIndex(r);this.setSchedulePosition(l)}}},i.advanceAfterAssetEnded=function(e,t,i){var r=i+1;if(e.isAssetPastPlayoutLimit(r)||e.assetList[r].error){var n=this.schedule.items;if(n){var s=t+1;if(s>=n.length)return void this.setSchedulePosition(-1);var a=e.resumeTime;this.timelinePos<a&&(this.timelinePos=a,this.checkBuffer()),this.setSchedulePosition(s)}}else this.setSchedulePosition(t,r)},i.setScheduleToAssetAtTime=function(e,t){var i=this.schedule,r=t.parentIdentifier,n=i.getEvent(r);if(n){var s=i.findEventIndex(r),a=i.findAssetIndex(n,e);this.setSchedulePosition(s,a)}},i.setSchedulePosition=function(e,t){var i=this.schedule.items;if(i&&!this.playbackDisabled){this.log("setSchedulePosition "+e+", "+t);var r=e>=0?i[e]:null,n=this.playingItem,s=this.playingLastItem;if(this.isInterstitial(n)){var a,o=n.event,l=this.playingAsset,h=null==l?void 0:l.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(n,r)||void 0!==t&&h!==(null==(a=o.assetList)?void 0:a[t].identifier))){var d,c=o.findAssetIndex(l);this.log("INTERSTITIAL_ASSET_ENDED "+(c+1)+"/"+o.assetList.length+" "+Xs(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(P.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:c,event:o,schedule:i.slice(0),scheduleIndex:e,player:u}),this.retreiveMediaSource(h,r),!u.media||null!=(d=this.detachedData)&&d.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+Zs(n)),o.hasPlayed=!0,this.hls.trigger(P.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once)){this.updateSchedule();var f=this.schedule.items;if(r&&f){var g=this.schedule.findItemIndex(r);this.advanceSchedule(g,f,t,n,s)}return}}this.advanceSchedule(e,i,t,n,s)}},i.advanceSchedule=function(e,t,i,r,n){var s=this,a=e>=0?t[e]:null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach((function(t){var i=t.interstitial,r=s.schedule.findEventIndex(i.identifier);(r<e||r>e+1)&&s.clearInterstitial(i,a)})),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);var h=a.event;void 0===i&&(i=this.schedule.findAssetIndex(h,this.timelinePos));var u=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);var d=this.preloadAssets(h,i);if(this.eventItemsMatch(a,u||r)||(this.waitingItem=a,this.log("INTERSTITIAL_STARTED "+Zs(a)+" "+(h.appendInPlace?"append in place":"")),this.hls.trigger(P.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+h);if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!o)return void this.log("Waiting for attachMedia to start Interstitial "+h);this.waitingItem=this.endedItem=null,this.playingItem=a;var c=h.assetList[i];if(!c){var f=t[e+1],g=this.media;return f&&g&&!this.isInterstitial(f)&&g.currentTime<f.start&&(g.currentTime=this.timelinePos=f.start),void this.advanceAfterAssetEnded(h,e,i||0)}if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){var p=h.assetList.length;this.warn("asset "+(i+1)+"/"+p+" player destroyed "+h),d=this.createAssetPlayer(h,c,i)}if(!this.eventItemsMatch(a,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,i,t,e,o),this.shouldPlay&&ra(d.media)}else null!==a?(this.resumePrimary(a,e,r),this.shouldPlay&&ra(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))},i.resumePrimary=function(e,t,i){var r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming "+Zs(e)),null==(r=this.detachedData)||!r.mediaSource){var n=this.timelinePos;(n<e.start||n>=e.end)&&(n=this.getPrimaryResumption(e,t),this.timelinePos=n),this.attachPrimary(n,e)}if(i){var s=this.schedule.items;s&&(this.log("resumed "+Zs(e)),this.hls.trigger(P.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}},i.getPrimaryResumption=function(e,t){var i=e.start;if(this.primaryLive){var r=this.primaryDetails;if(0===t)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i},i.isAssetBuffered=function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:Wt.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)},i.attachPrimary=function(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var r=this.primaryMedia;if(r){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}},i.startLoadingPrimaryAt=function(e,t){var i,r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()},i.onManifestLoading=function(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(P.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(P.BUFFER_CODECS,this.onBufferCodecs,this)},i.onLevelUpdated=function(e,t){if(-1!==t.level){var i=this.hls.levels[t.level],r=c(c({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}},i.onAudioTrackUpdated=function(e,t){var i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(r){var n=c(c({},r),{},{audio:i});this.mediaSelection=n}else this.altSelection=c(c({},this.altSelection),{},{audio:i})},i.onSubtitleTrackUpdated=function(e,t){var i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(r){var n=c(c({},r),{},{subtitles:i});this.mediaSelection=n}else this.altSelection=c(c({},this.altSelection),{},{subtitles:i})},i.onAudioTrackSwitching=function(e,t){var i=st(t);this.playerQueue.forEach((function(e){return e.hls.setAudioOption(t)||e.hls.setAudioOption(i)}))},i.onSubtitleTrackSwitch=function(e,t){var i=st(t);this.playerQueue.forEach((function(e){return e.hls.setSubtitleOption(t)||-1!==t.id&&e.hls.setSubtitleOption(i)}))},i.onBufferCodecs=function(e,t){var i=t.tracks;i&&(this.requiredTracks=i)},i.onBufferAppended=function(e,t){this.checkBuffer()},i.onBufferFlushed=function(e,t){var i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){var r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}},i.onBufferedToEnd=function(e){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var i=0;i<t.length;i++){var r=t[i];if(r.cue.post){var n,s=this.schedule.findEventIndex(r.identifier),a=null==(n=this.schedule.items)?void 0:n[s];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}},i.onMediaEnded=function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1},i.updateItem=function(e,t){var i=this.schedule.items;return e&&i&&i[this.findItemIndex(e,t)]||null},i.itemsMatch=function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))},i.eventItemsMatch=function(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))},i.findItemIndex=function(e,t){return e?this.schedule.findItemIndex(e,t):-1},i.updateSchedule=function(){var e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])},i.checkBuffer=function(e){var t=this.schedule.items;if(t){var i=Wt.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,t,e)}},i.updateBufferedPos=function(e,t,i){var r=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e))if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var s=this.playingItem,a=this.findItemIndex(s),o=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,h,u=this.findItemIndex(n),d=Math.min(u+1,t.length-1),c=t[d];if((-1===o&&n&&e>=n.end||null!=(l=c.event)&&l.appendInPlace&&e+.01>=c.start)&&(o=d),d-a>1&&!1===(null==n||null==(h=n.event)?void 0:h.appendInPlace))return;if(this.bufferedPos=e,o>u&&o>a)this.bufferedToItem(c);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&c.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(c)&&this.preloadAssets(c.event,0)}}else i&&s&&!this.itemsMatch(s,n)&&(o===a?this.bufferedToItem(s):o===a+1&&this.bufferedToItem(t[o]))}},i.assetsBuffered=function(e,t){var i=this;return 0!==e.event.assetList.length&&!e.event.assetList.some((function(e){var r=i.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))}))},i.setBufferingItem=function(e){var t=this,i=this.bufferingItem,r=this.schedule;if(this.itemsMatch(e,i))this.bufferingItem!==e&&(this.bufferingItem=e);else{var n=r.items,s=r.events;if(!n||!s)return i;var a=this.isInterstitial(e),o=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){var l=o?o.remaining:i?i.end-this.timelinePos:0;this.log("buffered to boundary "+Zs(e)+(i?" ("+l.toFixed(2)+" remaining)":"")),a?e.event.assetList.forEach((function(e){var i=t.getAssetPlayer(e.identifier);i&&i.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((function(e){return e.pauseBuffering()})))}this.hls.trigger(P.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return i},i.bufferedToItem=function(e,t){void 0===t&&(t=0);var i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;var r=this.detachedData;r&&r.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}},i.preloadPrimary=function(e){var t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)},i.bufferedToEvent=function(e,t){var i=e.event,r=0===i.assetList.length&&!i.assetListLoader,n=i.cue.once;if(r||!n){var s=this.preloadAssets(i,t);if(null!=s&&s.interstitial.appendInPlace){var a=i.assetList[t],o=this.primaryMedia;a&&o&&this.bufferAssetPlayer(s,o)}}},i.preloadAssets=function(e,t){var i=e.assetUrl,r=e.assetList.length,n=0===r&&!e.assetListLoader,s=e.cue.once;if(n){var a,o=e.timelineStart;if(e.appendInPlace){var l,h=this.playingItem;this.isInterstitial(h)||(null==h||null==(l=h.nextEvent)?void 0:l.identifier)!==e.identifier||this.flushFrontBuffer(o+.25)}var u=0;if(!this.playingItem&&this.primaryLive&&-1===(u=this.hls.startPosition)&&(u=this.hls.liveSyncPosition||0),u&&!e.cue.pre&&!e.cue.post){var d=u-o;d>0&&(a=Math.round(1e3*d)/1e3)}if(this.log("Load interstitial asset "+(t+1)+"/"+(i?1:r)+" "+e+(a?" live-start: "+u+" start-offset: "+a:"")),i)return this.createAsset(e,0,0,o,e.duration,i);var c=this.assetListLoader.loadAssetList(e,a);c&&(e.assetListLoader=c)}else if(!s&&r){for(var f=t;f<r;f++){var g=e.assetList[f],p=this.getAssetPlayerQueueIndex(g.identifier);-1!==p&&!this.playerQueue[p].destroyed||g.error||this.createAssetPlayer(e,g,f)}return this.getAssetPlayer(e.assetList[t].identifier)}return null},i.flushFrontBuffer=function(e){var t=this,i=this.requiredTracks;i&&(this.log("Removing front buffer starting at "+e),Object.keys(i).forEach((function(i){t.hls.trigger(P.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})))},i.getAssetPlayerQueueIndex=function(e){for(var t=this.playerQueue,i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1},i.getAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null},i.getBufferingPlayer=function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null},i.createAsset=function(e,t,i,r,n,s){var a={parentIdentifier:e.identifier,identifier:qs(e,s,t),duration:n,startOffset:i,timelineStart:r,uri:s};return this.createAssetPlayer(e,a,t)},i.createAssetPlayer=function(e,t,i){var r=this;this.log("create HLSAssetPlayer for "+Xs(t));var n=this.hls,s=n.userConfig,a=s.videoPreference,l=n.loadLevelObj||n.levels[n.currentLevel];(a||l)&&(a=o({},a),l.videoCodec&&(a.videoCodec=l.videoCodec),l.videoRange&&(a.allowedVideoRanges=[l.videoRange]));var h=n.audioTracks[n.audioTrack],u=n.subtitleTracks[n.subtitleTrack],d=0;if(this.primaryLive||e.appendInPlace){var f=this.timelinePos-t.timelineStart;if(f>1){var g=t.duration;g&&f<g&&(d=f)}}var p=t.identifier,v=c(c({},s),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:p,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:h||s.audioPreference,subtitlePreference:u||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(v.timelineOffset=t.timelineStart));var m=v.cmcd;null!=m&&m.sessionId&&m.contentId&&(v.cmcd=o({},m,{contentId:Ks(t.uri)})),this.getAssetPlayer(p)&&this.warn("Duplicate date range identifier "+e+" and asset "+p);var y=new Qs(this.HlsPlayerClass,v,e,t);this.playerQueue.push(y),e.assetList[i]=t;var E=function(n){if(n.live){var s=new Error("Interstitials MUST be VOD assets "+e),a={fatal:!0,type:I.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:s};r.handleAssetItemError(a,e,r.schedule.findEventIndex(e.identifier),i,s.message)}else{var o=n.edge-n.fragmentStart,l=t.duration;(null===l||o>l)&&(r.log('Interstitial asset "'+p+'" duration change '+l+" > "+o),t.duration=o,r.updateSchedule())}};y.on(P.LEVEL_UPDATED,(function(e,t){var i=t.details;return E(i)})),y.on(P.LEVEL_PTS_UPDATED,(function(e,t){var i=t.details;return E(i)}));var S=function(e,t){var i=r.getAssetPlayer(p);if(i&&t.tracks){i.off(P.BUFFER_CODECS,S),i.tracks=t.tracks;var n=r.primaryMedia;r.bufferingAsset===i.assetItem&&n&&!i.media&&r.bufferAssetPlayer(i,n)}};y.on(P.BUFFER_CODECS,S);var T=function(){var i,n=r.getAssetPlayer(p);if(r.log("buffered to end of asset "+n),n){var s=r.schedule.findEventIndex(e.identifier),a=e.findAssetIndex(t),o=a+1,l=null==(i=r.schedule.items)?void 0:i[s];if(r.isInterstitial(l))if(-1===a||e.isAssetPastPlayoutLimit(o)||e.assetList[o].error){var h,u=null==(h=r.schedule.items)?void 0:h[s+1];u&&r.bufferedToItem(u)}else r.bufferedToItem(l,o)}};y.on(P.BUFFERED_TO_END,T);var L=function(t){return function(){if(r.getAssetPlayer(p)){r.shouldPlay=!0;var i=r.schedule.findEventIndex(e.identifier);r.advanceAfterAssetEnded(e,i,t)}}};return y.once(P.MEDIA_ENDED,L(i)),y.once(P.PLAYOUT_LIMIT_REACHED,L(1/0)),y.on(P.ERROR,(function(t,n){var s=r.getAssetPlayer(p);if(n.details!==R.BUFFER_STALLED_ERROR)r.handleAssetItemError(n,e,r.schedule.findEventIndex(e.identifier),i,"Asset player error "+n.error+" "+e);else if(null!=s&&s.media){var a=s.currentTime,o=s.duration-a;a&&e.appendInPlace&&o/s.media.playbackRate<.5?(r.log("Advancing buffer past end of asset "+p+" "+e+" at "+s.media.currentTime),T()):(r.warn("Stalled at "+a+" of "+(a+o)+" in asset "+p+" "+e),r.onTimeupdate(),r.checkBuffer(!0))}})),y.on(P.DESTROYING,(function(){if(r.getAssetPlayer(p)){var t=new Error("Asset player destroyed unexpectedly "+p),n={fatal:!0,type:I.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};r.handleAssetItemError(n,e,r.schedule.findEventIndex(e.identifier),i,t.message)}})),this.hls.trigger(P.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:y}),y},i.clearInterstitial=function(e,t){var i=this;e.assetList.forEach((function(e){i.clearAssetPlayer(e.identifier,t)})),e.reset()},i.clearAssetPlayer=function(e,t){var i=this.getAssetPlayerQueueIndex(e);if(-1!==i){this.log('clearAssetPlayer "'+e+'" toSegment: '+(t?Zs(t):t));var r=this.playerQueue[i];this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}},i.emptyPlayerQueue=function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]},i.startAssetPlayer=function(e,t,i,r,n){var s=e.interstitial,a=e.assetItem,o=e.assetId,l=s.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log("INTERSTITIAL_ASSET_STARTED "+(t+1)+"/"+l+" "+e),this.hls.trigger(P.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:s,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)},i.bufferAssetPlayer=function(e,t){var i,r,n=e.interstitial,s=e.assetItem,a=e.assetId,o=this.schedule.findEventIndex(n.identifier),l=null==(i=this.schedule.items)?void 0:i[o];if(l){this.setBufferingItem(l),this.bufferingAsset=s;var h=this.getBufferingPlayer();if(h!==e){var u=n.appendInPlace;if(!u||!1!==(null==h?void 0:h.interstitial.appendInPlace)){var d=(null==h?void 0:h.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(u&&s!==this.playingAsset){if(!e.tracks)return;if(d&&!j(d,e.tracks)){var c=new Error('Asset "'+a+"\" SourceBuffer tracks ('"+Object.keys(e.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(d)+"')"),f={fatal:!0,type:I.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:c},g=n.findAssetIndex(s);return void this.handleAssetItemError(f,n,o,g,c.message)}}this.transferMediaTo(e,t)}}}},i.handleAssetItemError=function(e,t,i,r,n){if(e.details!==R.BUFFER_STALLED_ERROR){var s=t.assetList[r]||null,a=null;if(s){var l=this.getAssetPlayerQueueIndex(s.identifier);a=this.playerQueue[l]||null}var h=this.schedule.items,u=o({},e,{fatal:!1,errorAction:_t(!0),asset:s,assetListIndex:r,event:t,schedule:h,scheduleIndex:i,player:a});if(this.warn("Asset item error: "+e.error),this.hls.trigger(P.INTERSTITIAL_ASSET_ERROR,u),e.fatal){var d=new Error(n);s&&(this.playingAsset!==s&&this.clearAssetPlayer(s.identifier,null),s.error=d),t.assetList.some((function(e){return!e.error}))?t.appendInPlace&&(t.error=d):t.error=d,this.primaryFallback(t)}}},i.primaryFallback=function(e){var t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log('Fallback to primary from event "'+e.identifier+'" start: '+t+" pos: "+this.timelinePos+" playing: "+(i?Zs(i):"<none>")+" error: "+e.error),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));var r=this.timelinePos;-1===r&&(r=this.hls.startPosition);var n=this.updateItem(i,r);if(this.itemsMatch(i,n))this.clearInterstitial(e,null);else{var s=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(s)}}else this.checkStart()},i.onAssetListLoaded=function(e,t){var i,r=this,n=t.event,s=n.identifier,a=t.assetListResponse.ASSETS;if(this.schedule.hasEvent(s)){var o=n.timelineStart,l=n.duration,h=0;a.forEach((function(e,t){var i=parseFloat(e.DURATION);r.createAsset(n,t,h,o+h,i,e.URI),h+=i})),n.duration=h,this.log("Loaded asset-list with duration: "+h+" (was: "+l+") "+n);var u=this.waitingItem,d=(null==u?void 0:u.event.identifier)===s;this.updateSchedule();var c=null==(i=this.bufferingItem)?void 0:i.event;if(d){var f,g=this.schedule.findEventIndex(s),p=null==(f=this.schedule.items)?void 0:f[g];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return n.error=new Error("Interstitial no longer within playback range "+this.timelinePos+" "+n),void this.primaryFallback(n);this.setBufferingItem(p)}this.setSchedulePosition(g)}else if((null==c?void 0:c.identifier)===s&&c.appendInPlace){var v=n.assetList[0],m=this.getAssetPlayer(v.identifier),y=this.primaryMedia;v&&m&&y&&this.bufferAssetPlayer(m,y)}}},i.onError=function(e,t){switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:var i=t.interstitial;i&&this.primaryFallback(i);break;case R.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}},n(t,[{key:"interstitialsManager",get:function(){if(!this.manager){if(!this.hls)return null;var e=this,t=function(){return e.bufferingItem||e.waitingItem},i=function(t){return t?e.getAssetPlayer(t.identifier):t},r=function(t,r,s,a,o){if(t){var l=t[r].start,h=t.event;if(h){if("playout"===r||h.timelineOccupancy!==$s.Point){var u=i(s);(null==u?void 0:u.interstitial)===h&&(l+=u.assetItem.startOffset+u[o])}}else l+=("bufferedPos"===a?n():e[a])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?s("primary"):Math.max(t,0)},s=function(t){var i;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:e.schedule.durations[t]},a=function(t,n){var s,a,o=e.effectivePlayingItem;if(null==o||null==(s=o.event)||!s.restrictions.skip){e.log("seek to "+t+' "'+n+'"');var l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,n),u=null==(a=e.schedule.items)?void 0:a[h],d=e.getBufferingPlayer(),c=null==d?void 0:d.interstitial,f=null==c?void 0:c.appendInPlace,g=l&&e.itemsMatch(l,u);if(l&&(f||g)){var p=i(e.playingAsset),v=(null==p?void 0:p.media)||e.primaryMedia;if(v){var m="primary"===n?v.currentTime:r(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-m,E=(f?m:v.currentTime)+y;if(E>=0&&(!p||f||E<=p.duration))return void(v.currentTime=E)}}if(u){var S=t;if("primary"!==n){var T=t-u[n].start;S=u.start+T}var L=!e.isInterstitial(u);if(e.isInterstitial(l)&&!l.event.appendInPlace||!L&&!u.event.appendInPlace){if(l){var _=e.findItemIndex(l);if(h>_){var b=e.schedule.findJumpRestrictedIndex(_+1,h);if(b>_)return void e.setSchedulePosition(b)}var A=0;if(L)e.timelinePos=S,e.checkBuffer();else{var I,R=null==u||null==(I=u.event)?void 0:I.assetList;if(R)for(var P=t-(u[n]||u).start,k=R.length;k--;){var D=R[k];if(D.duration&&P>=D.startOffset&&P<D.startOffset+D.duration){A=k;break}}}e.setSchedulePosition(h,A)}}else{var w=e.media||(f?null==d?void 0:d.media:null);w&&(w.currentTime=S)}}}},o=function(){var i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;var r=t();return e.isInterstitial(r)?r:null},l={get currentTime(){var t=o(),i=e.effectivePlayingItem;return i&&i===t?r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){var i=o(),r=e.effectivePlayingItem;r&&r===i&&a(t+r.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,i=null==(t=o())?void 0:t.event.assetList;return i?i.map((function(t){return e.getAssetPlayer(t.identifier)})):[]},get playingIndex(){var t,i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};this.manager={get events(){var t,i;return(null==(t=e.schedule)||null==(i=t.events)?void 0:i.slice(0))||[]},get schedule(){var t,i;return(null==(t=e.schedule)||null==(i=t.items)?void 0:i.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return s("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return s("integrated")},get seekableStart(){var t;return function(t,i){if(0!==t&&e.schedule.length){var r,n=e.schedule.findItemIndexAtTime(t),s=null==(r=e.schedule.items)?void 0:r[n];if(s)return t+(s[i].start-s.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){var r=e.findItemIndex(t);if(i.appendInPlace){var n=t.playout.start+t.event.duration;a(n+.001,"playout")}else e.advanceAfterAssetEnded(i,r,1/0)}}}}return this.manager}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t,i;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var n=this.media;!n&&null!=(e=this.bufferingItem)&&null!=(t=e.event)&&t.appendInPlace&&(n=this.primaryMedia);var s=null==(i=n)?void 0:i.currentTime;if(void 0!==s&&_(s))return s}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e,t;return null==(e=this.mediaSelection)||null==(t=e.main)?void 0:t.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}}])}(B),sa=function(e){function t(t,i,r){var n;return(n=e.call(this,t,i,r,"subtitle-stream-controller",x)||this).currentTrackId=-1,n.tracksBuffered=[],n.mainDetails=null,n.registerListeners(),n}h(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.mainDetails=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(P.LEVEL_LOADED,this.onLevelLoaded,this),t.on(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(P.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(P.LEVEL_LOADED,this.onLevelLoaded,this),t.off(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(P.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.startLoad=function(e,t){this.stopLoad(),this.state=er.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.mainDetails=null},i.onMediaDetaching=function(t,i){this.tracksBuffered=[],e.prototype.onMediaDetaching.call(this,t,i)},i.onLevelLoaded=function(e,t){this.mainDetails=t.details},i.onSubtitleFragProcessed=function(e,t){var i=t.frag,r=t.success;if(te(i)&&(this.fragPrevious=i),this.state=er.IDLE,r){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var s,a=i.start,o=0;o<n.length;o++)if(a>=n[o].start&&a<=n[o].end){s=n[o];break}var l=i.start+i.duration;s?s.end=l:(s={start:a,end:l},n.push(s)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}}},i.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach((function(e){for(var t=0;t<e.length;)if(e[t].end<=n)e.shift();else{if(!(e[t].start<n))break;e[t].start=n,t++}})),this.fragmentTracker.removeFragmentsInRange(i,n,x)}},i.onError=function(e,t){var i=t.frag;(null==i?void 0:i.type)===x&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==er.STOPPED&&(this.state=er.IDLE))},i.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks;this.levels&&Hn(this.levels,r)?this.levels=r.map((function(e){return new et(e)})):(this.tracksBuffered=[],this.levels=r.map((function(e){var t=new et(e);return i.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,x),this.fragPrevious=null,this.mediaBuffer=null)},i.onSubtitleTrackSwitch=function(e,t){var i;if(this.currentTrackId=t.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==er.STOPPED&&this.setInterval(500)}else this.clearInterval()},i.onSubtitleTrackLoaded=function(e,t){var i,r=this.currentTrackId,n=this.levels,s=t.details,a=t.id;if(n){var o=n[a];if(!(a>=n.length)&&o){if(this.log("Subtitle track "+a+" loaded ["+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+",duration:"+s.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges,s.live||null!=(i=o.details)&&i.live){var l=this.mainDetails;if(s.deltaUpdateFailed||!l)return;var h,u=l.fragments[0];o.details?0===this.alignPlaylists(s,o.details,null==(h=this.levelLastLoaded)?void 0:h.details)&&u&&Ki(s,u.start):s.hasProgramDateTime&&l.hasProgramDateTime?(Zi(s,l),s.fragmentStart):u&&Ki(s,u.start)}o.details=s,this.levelLastLoaded=o,a===r&&(this.hls.trigger(P.SUBTITLE_TRACK_UPDATED,{details:s,id:a,groupId:t.groupId}),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===er.IDLE&&(ft(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+a)},i._handleFragmentLoadComplete=function(e){var t=this,i=e.frag,r=e.payload,n=i.decryptdata,s=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=n&&n.key&&n.iv&&ii(n.method)){var a=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,ri(n.method)).catch((function(e){throw s.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((function(e){var t=performance.now();s.trigger(P.FRAG_DECRYPTED,{frag:i,payload:e,stats:{tstart:a,tdecrypt:t}})})).catch((function(e){t.warn(e.name+": "+e.message),t.state=er.IDLE}))}},i.doTick=function(){if(this.media){if(this.state===er.IDLE){var e=this.currentTrackId,t=this.levels,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;var r=this.config,n=this.getLoadPosition(),s=Wt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),a=s.end,o=s.len,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var h=l.fragments,u=h.length,d=l.edge,c=null,f=this.fragPrevious;if(a<d){var g=r.maxFragLookUpTolerance,p=a>d-g?0:g;!(c=ft(f,h,Math.max(h[0].start,a),p))&&f&&f.start<h[0].start&&(c=h[0])}else c=h[u-1];if(!(c=this.filterReplacedPrimary(c,i.details)))return;var v=h[c.sn-l.startSN-1];if(v&&v.cc===c.cc&&this.fragmentTracker.getState(v)===bt&&(c=v),this.fragmentTracker.getState(c)===bt){var m=this.mapToInitFragWhenRequired(c);m&&this.loadFragment(m,i,a)}}}else this.state=er.IDLE},i.loadFragment=function(t,i,r){te(t)?e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i)},n(t,[{key:"mediaBufferTimeRanges",get:function(){return new aa(this.tracksBuffered[this.currentTrackId]||[])}}])}(tr),aa=function(e){this.buffered=void 0;var t=function(t,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+i+") is greater than the maximum bound ("+r+")");return e[i][t]};this.buffered={get length(){return e.length},end:function(i){return t("end",i,e.length)},start:function(i){return t("start",i,e.length)}}};function oa(e,t){var i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function la(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(i){$.debug("[texttrack-utils]: "+i);try{var r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){$.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===i&&(e.mode=i)}function ha(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===i&&(e.mode=i)}function ua(e,t,i,r){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var s=function(e,t,i){var r=[],n=function(e,t){if(t<=e[0].startTime)return 0;var i=e.length-1;if(t>e[i].endTime)return-1;for(var r,n=0,s=i;n<=s;)if(t<e[r=Math.floor((s+n)/2)].startTime)s=r-1;else{if(!(t>e[r].startTime&&n<i))return r;n=r+1}return e[n].startTime-t<t-e[s].startTime?n:s}(e,t);if(n>-1)for(var s=n,a=e.length;s<a;s++){var o=e[s];if(o.startTime>=t&&o.endTime<=i)r.push(o);else if(o.startTime>i)return r}return r}(e.cues,t,i),a=0;a<s.length;a++)r&&!r(s[a])||e.removeCue(s[a]);"disabled"===n&&(e.mode=n)}function da(e){for(var t=[],i=0;i<e.length;i++){var r=e[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[i])}return t}var ca=function(e){function t(t){var i;return(i=e.call(this,t,"subtitle-track-controller")||this).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var e=null,t=da(i.media.textTracks),r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}var n=i.findTrackForTextTrack(e);i.subtitleTrack!==n&&i.setSubtitleTrack(n)}},i.registerListeners(),i}h(t,e);var i=t.prototype;return i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,e.prototype.destroy.call(this)},i.registerListeners=function(){var e=this.hls;e.on(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_PARSED,this.onManifestParsed,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(P.ERROR,this.onError,this)},i.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_PARSED,this.onManifestParsed,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(P.ERROR,this.onError,this)},i.onMediaAttached=function(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},i.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},i.onMediaDetaching=function(e,t){var i=this.media;if(i){var r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r||da(i.textTracks).forEach((function(e){ha(e)}))}},i.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},i.onSubtitleTrackLoaded=function(e,t){var i=t.id,r=t.groupId,n=t.details,s=this.tracksInGroup[i];if(s&&s.groupId===r){var a=s.details;s.details=t.details,this.log("Subtitle track "+i+' "'+s.name+'" lang:'+s.lang+" group:"+r+" loaded ["+n.startSN+"-"+n.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Subtitle track with id:"+i+" and group:"+r+" not found in active group "+(null==s?void 0:s.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var s=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(s.length)this.selectDefaultTrack&&!s.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),s.forEach((function(e,t){e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=s;var a=this.hls.config.subtitlePreference;if(!n&&a){this.selectDefaultTrack=!1;var o=at(a,s);if(o>-1)n=s[o];else{var l=at(a,this.tracks);n=this.tracks[l]}}var h=this.findTrackId(n);-1===h&&n&&(h=this.findTrackId(null));var u={subtitleTracks:s};this.log("Updating subtitle tracks, "+s.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(P.SUBTITLE_TRACKS_UPDATED,u),-1!==h&&-1===this.trackId&&this.setSubtitleTrack(h)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=this.selectDefaultTrack,r=0;r<t.length;r++){var n=t[r];if((!i||n.default)&&(i||e)&&(!e||ot(n,e)))return r}if(e){for(var s=0;s<t.length;s++){var a=t[s];if(Vn(e.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(var o=0;o<t.length;o++){var l=t[o];if(Vn(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1},i.findTrackForTextTrack=function(e){if(e)for(var t=this.tracksInGroup,i=0;i<t.length;i++)if(Kn(t[i],e))return i;return-1},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==C||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setSubtitleOption=function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var i=this.currentTrack;if(i&&ot(e,i))return i;var r=at(e,this.tracksInGroup);if(r>-1){var n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}if(i)return null;var s=at(e,t);if(s>-1)return t[s]}}return null},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,n=t.groupId,s=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading subtitle "+r+' "'+t.name+'" lang:'+t.lang+" group:"+n+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+s),this.hls.trigger(P.SUBTITLE_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:i||null,track:t})},i.toggleTrackModes=function(){var e=this.media;if(e){var t,i=da(e.textTracks),r=this.currentTrack;if(r&&((t=i.filter((function(e){return Kn(r,e)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+r.name+'" and language "'+r.lang+'"')),[].slice.call(i).forEach((function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")})),t){var n=this.subtitleDisplay?"showing":"hidden";t.mode!==n&&(t.mode=n)}}},i.setSubtitleTrack=function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!_(e))this.warn("Invalid subtitle track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),r){var n=!!r.details&&!r.details.live;if(e!==this.trackId||r!==i||!n){this.log("Switching to subtitle-track "+e+(r?' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId:""));var s=r.id,a=r.groupId,o=void 0===a?"":a,l=r.name,h=r.type,u=r.url;this.hls.trigger(P.SUBTITLE_TRACK_SWITCH,{id:s,groupId:o,name:l,type:h,url:u});var d=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(d)}}else this.hls.trigger(P.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e},n(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}}])}(Gn),fa={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},ga=function(e){return String.fromCharCode(fa[e]||e)},pa=15,va=100,ma={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ya={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ea={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Sa={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ta=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],La=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var i="function"==typeof t?t():t;$.log(this.time+" ["+e+"] "+i)}},e}(),_a=function(e){for(var t=[],i=0;i<e.length;i++)t.push(e[i].toString(16));return t},ba=function(){function e(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}var t=e.prototype;return t.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},t.setStyles=function(e){for(var t=["foreground","underline","italics","background","flash"],i=0;i<t.length;i++){var r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}},t.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},t.equals=function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash},t.copy=function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash},t.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},e}(),Aa=function(){function e(){this.uchar=" ",this.penState=new ba}var t=e.prototype;return t.reset=function(){this.uchar=" ",this.penState.reset()},t.setChar=function(e,t){this.uchar=e,this.penState.copy(t)},t.setPenState=function(e){this.penState.copy(e)},t.equals=function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)},t.copy=function(e){this.uchar=e.uchar,this.penState.copy(e.penState)},t.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},e}(),Ia=function(){function e(e){this.chars=[],this.pos=0,this.currPenState=new ba,this.cueStartTime=null,this.logger=void 0;for(var t=0;t<va;t++)this.chars.push(new Aa);this.logger=e}var t=e.prototype;return t.equals=function(e){for(var t=0;t<va;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0},t.copy=function(e){for(var t=0;t<va;t++)this.chars[t].copy(e.chars[t])},t.isEmpty=function(){for(var e=!0,t=0;t<va;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e},t.setCursor=function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>va&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=va)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)},t.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},t.insertChar=function(e){var t=this;e>=144&&this.backSpace();var i=ga(e);this.pos>=va?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+i+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t<va;t++)this.chars[t].reset()},t.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},t.clearToEndOfRow=function(){this.clearFromPos(this.pos)},t.getTextString=function(){for(var e=[],t=!0,i=0;i<va;i++){var r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")},t.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),Ra=function(){function e(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var t=0;t<pa;t++)this.rows.push(new Ia(e));this.logger=e}var t=e.prototype;return t.reset=function(){for(var e=0;e<pa;e++)this.rows[e].clear();this.currRow=14},t.equals=function(e){for(var t=!0,i=0;i<pa;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t},t.copy=function(e){for(var t=0;t<pa;t++)this.rows[t].copy(e.rows[t])},t.isEmpty=function(){for(var e=!0,t=0;t<pa;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},t.backSpace=function(){this.rows[this.currRow].backSpace()},t.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},t.insertChar=function(e){this.rows[this.currRow].insertChar(e)},t.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},t.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},t.setCursor=function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)},t.setPAC=function(e){this.logger.log(2,(function(){return"pacData = "+it(e)}));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var i=0;i<pa;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var s=n.rows[r].cueStartTime,a=this.logger.time;if(null!==s&&null!==a&&s<a)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[r+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var h=e.indent,u=Math.max(h-1,0);l.setCursor(e.indent),e.color=l.chars[u].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)},t.setBkgData=function(e){this.logger.log(2,(function(){return"bkgData = "+it(e)})),this.backSpace(),this.setPen(e),this.insertChar(32)},t.setRollUpRows=function(e){this.nrRollUpRows=e},t.rollUp=function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return e.getDisplayText()}));var t=this.currRow+1-this.nrRollUpRows,i=this.rows.splice(t,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")},t.getDisplayText=function(e){e=e||!1;for(var t=[],i="",r=-1,n=0;n<pa;n++){var s=this.rows[n].getTextString();s&&(r=n+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i},t.getTextAndFormat=function(){return this.rows},e}(),Pa=function(){function e(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Ra(i),this.nonDisplayedMemory=new Ra(i),this.lastOutputScreen=new Ra(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(function(){return"MODE="+e})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},t.insertChars=function(e){for(var t=this,i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return r+": "+t.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())},t.ccRCL=function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},t.ccBS=function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},t.ccAOF=function(){},t.ccAON=function(){},t.ccDER=function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},t.ccRU=function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},t.ccFON=function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},t.ccRDC=function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},t.ccTR=function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")},t.ccRTD=function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")},t.ccEDM=function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},t.ccCR=function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},t.ccENM=function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},t.ccEOC=function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+e.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)},t.ccTO=function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},t.ccMIDROW=function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var i=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][i]}this.logger.log(2,"MIDROW: "+it(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),ka=function(){function e(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var r=this.logger=new La;this.channels=[null,new Pa(e,t,r),new Pa(e+1,i,r)]}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var i=this;this.logger.time=e;for(var r=function(e){var r=127&t[e],n=127&t[e+1],s=!1,a=null;if(0===r&&0===n)return 0;i.logger.log(3,(function(){return"["+_a([t[e],t[e+1]])+"] -> ("+_a([r,n])+")"}));var o=i.cmdHistory;if(r>=16&&r<=31){if(function(e,t,i){return i.a===e&&i.b===t}(r,n,o))return Da(null,null,o),i.logger.log(3,(function(){return"Repeated command ("+_a([r,n])+") is dropped"})),0;Da(r,n,i.cmdHistory),(s=i.parseCmd(r,n))||(s=i.parseMidrow(r,n)),s||(s=i.parsePAC(r,n)),s||(s=i.parseBackgroundAttributes(r,n))}else Da(null,null,o);if(!s&&(a=i.parseChars(r,n))){var l=i.currentChannel;l&&l>0?i.channels[l].insertChars(a):i.logger.log(2,"No channel found yet. TEXT-MODE?")}s||a||i.logger.log(2,(function(){return"Couldn't parse cleaned data "+_a([r,n])+" orig: "+_a([t[e],t[e+1]])}))},n=0;n<t.length;n+=2)r(n)},t.parseCmd=function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0},t.parseMidrow=function(e,t){var i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+_a([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var r=e<=23?1:2;i=t>=64&&t<=95?1===r?ma[e]:Ea[e]:1===r?ya[e]:Sa[e];var n=this.channels[r];return!!n&&(n.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)},t.interpretPAC=function(e,t){var i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r},t.parseChars=function(e,t){var i,r,n=null,s=null;return e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19?(r=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+ga(r)+"' in channel "+i})),n=[r]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]),n&&this.logger.log(3,(function(){return"Char codes = "+_a(n).join(",")})),n},t.parseBackgroundAttributes=function(e,t){var i;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;var r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=Ta[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(r),!0},t.reset=function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}Da(null,null,this.cmdHistory)},t.cueSplitAtTime=function(e){for(var t=0;t<this.channels.length;t++){var i=this.channels[t];i&&i.cueSplitAtTime(e)}},e}();function Da(e,t,i){i.a=e,i.b=t}var wa=function(){if(null!=ai&&ai.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function n(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var n=1;n<arguments.length;n++){var s=arguments[n];for(var a in s)e[a]=s[a]}return e}function s(t,s,a){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var h="",u=!1,d=t,c=s,f=a,g=null,p="",v=!0,m="auto",y="start",E=50,S="middle",T=50,L="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return u},set:function(e){u=!!e}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return p},set:function(t){var r=function(t){return i(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");p=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return v},set:function(e){v=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return S},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return L},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");L=t,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}(),Ca=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function Ma(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}var i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}var Oa=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,i){for(var r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}},t.integer=function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},t.percent=function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1},e}();function xa(e,t,i,r){var n=r?e.split(r):[e];for(var s in n)if("string"==typeof n[s]){var a=n[s].split(i);2===a.length&&t(a[0],a[1])}}var Fa=new wa(0,0,""),Na="middle"===Fa.align?"middle":"center";function Ba(e,t,i){var r=e;function n(){var t=Ma(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function s(){e=e.replace(/^\s+/,"")}if(s(),t.startTime=n(),s(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),s(),t.endTime=n(),s(),function(e,t){var r=new Oa;xa(e,(function(e,t){var n;switch(e){case"region":for(var s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),r.integer(e,n[0]),r.percent(e,n[0])&&r.set("snapToLines",!1),r.alt(e,n[0],["auto"]),2===n.length&&r.alt("lineAlign",n[1],["start",Na,"end"]);break;case"position":n=t.split(","),r.percent(e,n[0]),2===n.length&&r.alt("positionAlign",n[1],["start",Na,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",Na,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");var n=r.get("line","auto");"auto"===n&&-1===Fa.line&&(n=-1),t.line=n,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",Na);var s=r.get("position","auto");"auto"===s&&50===Fa.position&&(s="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=s}(e,t)}function Ua(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var Ga=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new Ca,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function i(){var e=t.buffer,i=0;for(e=Ua(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;var r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var r="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var n=(r=i()).match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var s=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:r=i(),t.state){case"HEADER":/:/.test(r)?xa(r,(function(e,t){}),/:/):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new wa(0,0,""),t.state="CUE",-1===r.indexOf("--\x3e")){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Ba(r,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var a=-1!==r.indexOf("--\x3e");if(!r||a&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=r;continue;case"BADCUE":r||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},t.flush=function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this},e}(),Ha=/\r\n|\n\r|\n|\r/g,Va=function(e,t,i){return void 0===i&&(i=0),e.slice(i,i+t.length)===t};function Ka(e,t,i){return Ks(e.toString())+Ks(t.toString())+Ks(i)}var Wa="stpp.ttml.im1t",$a=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,qa=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ja={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ya(e,t,i,r){var n=ge(new Uint8Array(e),["mdat"]);if(0!==n.length){var s,a,l,h=n.map((function(e){return Y(e)})),u=(s=t.baseTime,1,void 0===(a=t.timescale)&&(a=1),void 0===l&&(l=!1),cn(s,1,1/a,l));try{h.forEach((function(e){return i(function(e,t){var i=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((function(e,t){return e[t]=i.getAttribute("ttp:"+t)||r[t],e}),{}),s="preserve"!==i.getAttribute("xml:space"),a=Xa(za(i,"styling","style")),l=Xa(za(i,"layout","region")),h=za(i,"body","[begin]");return[].map.call(h,(function(e){var i=Qa(e,s);if(!i||!e.hasAttribute("begin"))return null;var r=eo(e.getAttribute("begin"),n),h=eo(e.getAttribute("dur"),n),u=eo(e.getAttribute("end"),n);if(null===r)throw Za(e);if(null===u){if(null===h)throw Za(e);u=r+h}var d=new wa(r-t,u-t,i);d.id=Ka(d.startTime,d.endTime,d.text);var c=function(e,t,i){var r="http://www.w3.org/ns/ttml#styling",n=null,s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return s&&i.hasOwnProperty(s)&&(n=i[s]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((function(i,s){var a=Ja(t,r,s)||Ja(e,r,s)||Ja(n,r,s);return a&&(i[s]=a),i}),{})}(l[e.getAttribute("region")],a[e.getAttribute("style")],a),f=c.textAlign;if(f){var g=ja[f];g&&(d.lineAlign=g),d.align=f}return o(d,c),d})).filter((function(e){return null!==e}))}(e,u))}))}catch(e){r(e)}}else r(new Error("Could not parse IMSC1 mdat"))}function za(e,t,i){var r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Xa(e){return e.reduce((function(e,t){var i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function Qa(e,t){return[].slice.call(e.childNodes).reduce((function(e,i,r){var n;return"br"===i.nodeName&&r?e+"\n":null!=(n=i.childNodes)&&n.length?Qa(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function Ja(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Za(e){return new Error("Could not parse ttml timestamp "+e)}function eo(e,t){if(!e)return null;var i=Ma(e);return null===i&&($a.test(e)?i=function(e,t){var i=$a.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):qa.test(e)&&(i=function(e,t){var i=qa.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}var to=function(){function e(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}var t=e.prototype;return t.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},t.newCue=function(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}(),io=function(){function e(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(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_LOADED,this.onManifestLoaded,this),e.on(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(P.FRAG_LOADING,this.onFragLoading,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this),e.on(P.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(P.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(P.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(P.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=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_LOADED,this.onManifestLoaded,this),e.off(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(P.FRAG_LOADING,this.onFragLoading,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this),e.off(P.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(P.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(P.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(P.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){var e=new to(this,"textTrack1"),t=new to(this,"textTrack2"),i=new to(this,"textTrack3"),r=new to(this,"textTrack4");this.cea608Parser1=new ka(1,e,t),this.cea608Parser2=new ka(3,i,r)},t.addCues=function(e,t,i,r,n){for(var s,a,o,l,h=!1,u=n.length;u--;){var d=n[u],c=(s=d[0],a=d[1],o=t,l=i,Math.min(a,l)-Math.max(s,o));if(c>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],i),h=!0,c/(i-t)>.5))return}if(h||n.push([t,i]),this.config.renderTextTracksNatively){var f=this.captionsTracks[e];this.Cues.newCue(f,t,i,r)}else{var g=this.Cues.newCue(null,t,i,r);this.hls.trigger(P.CUES_PARSED,{type:"captions",cues:g,track:e})}},t.onInitPtsFound=function(e,t){var i=this,r=t.frag,n=t.id,s=t.initPTS,a=t.timescale,o=this.unparsedVttFrags;n===M&&(this.initPTS[r.cc]={baseTime:s,timescale:a}),o.length&&(this.unparsedVttFrags=[],o.forEach((function(e){i.onFragLoaded(P.FRAG_LOADED,e)})))},t.getExistingTrack=function(e,t){var i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var n=i.textTracks[r];if(no(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null},t.createCaptionsTrack=function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)},t.createNativeTrack=function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,i=this.captionsTracks,r=this.media,n=t[e],s=n.label,a=n.languageCode,o=this.getExistingTrack(s,a);if(o)i[e]=o,ha(i[e]),oa(i[e],r);else{var l=this.createTextTrack("captions",s,a);l&&(l[e]=!0,i[e]=l)}}},t.createNonNativeTrack=function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(P.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}},t.createTextTrack=function(e,t,i){var r=this.media;if(r)return r.addTextTrack(e,t,i)},t.onMediaAttaching=function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()},t.onMediaDetaching=function(e,t){var i=!!t.transferMedia;if(this.media=null,!i){var r=this.captionsTracks;Object.keys(r).forEach((function(e){ha(r[e]),delete r[e]})),this.nonNativeCaptionsTracks={}}},t.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},t._cleanTracks=function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var i=0;i<t.length;i++)ha(t[i])}},t.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks||[],n=r.some((function(e){return e.textCodec===Wa}));if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Hn(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var s=this.media,a=s?da(s.textTracks):null;if(this.tracks.forEach((function(e,t){var r;if(a){for(var n=null,s=0;s<a.length;s++)if(a[s]&&no(a[s],e)){n=a[s],a[s]=null;break}n&&(r=n)}if(r)ha(r);else{var o=ro(e);(r=i.createTextTrack(o,e.name,e.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)})),null!=a&&a.length){var o=a.filter((function(e){return null!==e})).map((function(e){return e.label}));o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: "+o.join(", ")+". Replace media element for each source to clear TextTracks and captions menu.")}}else if(this.tracks.length){var l=this.tracks.map((function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}}));this.hls.trigger(P.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}},t.onManifestLoaded=function(e,t){var i=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var r="textTrack"+t[1],n=i.captionsProperties[r];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}}))},t.closedCaptionsForLevel=function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]},t.onFragLoading=function(e,t){if(this.enabled&&t.frag.type===M){var i,r,n=this.cea608Parser1,s=this.cea608Parser2,a=this.lastSn,o=t.frag,l=o.cc,h=o.sn,u=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;n&&s&&(h!==a+1||h===a&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),s.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=u}},t.onFragLoaded=function(e,t){var i=t.frag,r=t.payload;if(i.type===x)if(r.byteLength){var n=i.decryptdata,s="stats"in t;if(null==n||!n.encrypted||s){var a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===Wa?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})},t._parseIMSC1=function(e,t){var i=this,r=this.hls;Ya(t,this.initPTS[e.cc],(function(t){i._appendCues(t,e.level),r.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(function(t){r.logger.log("Failed to parse IMSC1: "+t),r.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))},t._parseVTTs=function(e){var t,i=this,r=e.frag,n=e.payload,s=this.initPTS,a=this.unparsedVttFrags,o=s.length-1;if(s[r.cc]||-1!==o){var l=this.hls;!function(e,t,i,r,n,s,a){var o,l,h,u=new Ga,d=Y(new Uint8Array(e)).trim().replace(Ha,"\n").split("\n"),c=[],f=t?(o=t.baseTime,void 0===(l=t.timescale)&&(l=1),cn(o,9e4,1/l)):0,g="00:00.000",p=0,v=0,m=!0;u.oncue=function(e){var s=i[r],a=i.ccOffset,o=(p-f)/9e4;if(null!=s&&s.new&&(void 0!==v?a=i.ccOffset=s.start:function(e,t,i){var r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(s=n)&&s.new;){var s;e.ccOffset+=r.start-n.start,r.new=!1,n=e[(r=n).prevCC]}e.presentationOffset=i}(i,r,o)),o){if(!t)return void(h=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}var l=e.endTime-e.startTime,u=yn(9e4*(e.startTime+a-v),9e4*n)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);var d=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(d)),e.id||(e.id=Ka(e.startTime,e.endTime,d)),e.endTime>0&&c.push(e)},u.onparsingerror=function(e){h=e},u.onflush=function(){h?a(h):s(c)},d.forEach((function(e){if(m){if(Va(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((function(e){Va(e,"LOCAL:")?g=e.slice(6):Va(e,"MPEGTS:")&&(p=parseInt(e.slice(7)))}));try{v=function(e){var t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(_(t)&&_(i)&&_(r)&&_(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*i,(t+=6e4*r)+36e5*n}(g)/1e3}catch(e){h=e}return}""===e&&(m=!1)}u.parse(e+"\n")})),u.flush()}(null!=(t=r.initSegment)&&t.data?be(r.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(function(e){i._appendCues(e,r.level),l.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(function(t){var s="Missing initPTS for VTT MPEGTS"===t.message;s?a.push(e):i._fallbackToIMSC1(r,n),l.logger.log("Failed to parse VTT cue: "+t),s&&o>r.cc||l.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}else a.push(e)},t._fallbackToIMSC1=function(e,t){var i=this,r=this.tracks[e.level];r.textCodec||Ya(t,this.initPTS[e.cc],(function(){r.textCodec=Wa,i._parseIMSC1(e,t)}),(function(){r.textCodec="wvtt"}))},t._appendCues=function(e,t){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach((function(e){return la(r,e)}))}else{var n=this.tracks[t];if(!n)return;var s=n.default?"default":"subtitles"+t;i.trigger(P.CUES_PARSED,{type:"subtitles",cues:e,track:s})}},t.onFragDecrypted=function(e,t){t.frag.type===x&&this.onFragLoaded(P.FRAG_LOADED,t)},t.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},t.onFragParsingUserdata=function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var i=t.frag,r=t.samples;if(i.type!==M||"NONE"!==this.closedCaptionsForLevel(i))for(var n=0;n<r.length;n++){var s=r[n].bytes;if(s){this.cea608Parser1||this.initCea608Parsers();var a=this.extractCea608Data(s);this.cea608Parser1.addData(r[n].pts,a[0]),this.cea608Parser2.addData(r[n].pts,a[1])}}}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,n=t.endOffsetSubtitles,s=t.type,a=this.media;if(a&&!(a.currentTime<r)){if(!s||"video"===s){var o=this.captionsTracks;Object.keys(o).forEach((function(e){return ua(o[e],i,r)}))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==n){var l=this.textTracks;Object.keys(l).forEach((function(e){return ua(l[e],i,n)}))}}},t.extractCea608Data=function(e){for(var t=[[],[]],i=31&e[0],r=2,n=0;n<i;n++){var s=e[r++],a=127&e[r++],o=127&e[r++];if((0!==a||0!==o)&&4&s){var l=3&s;0!==l&&1!==l||(t[l].push(a),t[l].push(o))}}return t},e}();function ro(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function no(e,t){return!!e&&e.kind===ro(t)&&Kn(t,e)}var so=/\s/,ao={newCue:function(e,t,i,r){for(var n,s,a,o,l,h=[],u=self.VTTCue||self.TextTrackCue,d=0;d<r.rows.length;d++)if(a=!0,o=0,l="",!(n=r.rows[d]).isEmpty()){for(var c,f=0;f<n.chars.length;f++)so.test(n.chars[f].uchar)&&a?o++:(l+=n.chars[f].uchar,a=!1);n.cueStartTime=t,t===i&&(i+=1e-4),o>=16?o--:o++;var g=Ua(l.trim()),p=Ka(t,i,g);null!=e&&null!=(c=e.cues)&&c.getCueById(p)||((s=new u(t,i,g)).id=p,s.line=d+1,s.align="left",s.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(s))}return e&&h.length&&(h.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),h.forEach((function(t){return la(e,t)}))),h}},oo=/(\d+)-(\d+)\/(\d+)/,lo=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||ho,this.controller=new self.AbortController,this.stats=new X}var t=e.prototype;return t.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},t.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},t.load=function(e,t,i){var r=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var s=function(e,t){var i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(o({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(e,this.controller.signal),a="arraybuffer"===e.responseType,l=a?"byteLength":"length",h=t.loadPolicy,u=h.maxTimeToFirstByteMs,d=h.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=u&&_(u)?u:d,this.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(n,e,r.response))}),t.timeout),(Rn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(i){var s;r.response=r.loader=i;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(r.requestTimeout),t.timeout=d,r.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(n,e,r.response))}),d-(o-n.loading.start)),!i.ok){var l=i.status,h=i.statusText;throw new uo(h||"fetch, bad network response",l,i)}n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var i=function(e){var t=oo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(_(i))return i}var r=e.get("Content-Length");if(r)return parseInt(r)}(i.headers)||n.total;var u=null==(s=r.callbacks)?void 0:s.onProgress;return u&&_(t.highWaterMark)?r.loadProgressively(i,n,e,t.highWaterMark,u):a?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((function(i){var s,a,o=r.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var h=i[l];h&&(n.loaded=n.total=h);var u={url:o.url,data:i,code:o.status},d=null==(s=r.callbacks)?void 0:s.onProgress;d&&!_(t.highWaterMark)&&d(n,e,i,o),null==(a=r.callbacks)||a.onSuccess(u,n,e,o)})).catch((function(t){var i;if(self.clearTimeout(r.requestTimeout),!n.aborted){var s=t&&t.code||0,a=t?t.message:null;null==(i=r.callbacks)||i.onError({code:s,text:a},e,t?t.details:null,n)}}))},t.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},t.loadProgressively=function(e,t,i,r,n){void 0===r&&(r=0);var s=new rr,a=e.body.getReader(),o=function(){return a.read().then((function(a){if(a.done)return s.dataLength&&n(t,i,s.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return t.loaded+=h,h<r||s.dataLength?(s.push(l),s.dataLength>=r&&n(t,i,s.flush().buffer,e)):n(t,i,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},e}();function ho(e,t){return new self.Request(e.url,t)}var uo=function(e){function t(t,i,r){var n;return(n=e.call(this,t)||this).code=void 0,n.details=void 0,n.code=i,n.details=r,n}return h(t,e),t}(p(Error)),co=/^age:\s*[\d.]+\s*$/im,fo=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 X,this.retryDelay=0}var t=e.prototype;return t.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},t.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},t.load=function(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()},t.loadInternal=function(){var e=this,t=this.config,i=this.context;if(t&&i){var r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var s=this.xhrSetup;s?Promise.resolve().then((function(){if(e.loader===r&&!e.stats.aborted)return s(r,i.url)})).catch((function(t){if(e.loader===r&&!e.stats.aborted)return r.open("GET",i.url,!0),s(r,i.url)})).then((function(){e.loader!==r||e.stats.aborted||e.openAndSendXhr(r,i,t)})).catch((function(t){var s;null==(s=e.callbacks)||s.onError({code:r.status,text:t.message},i,r,n)})):this.openAndSendXhr(r,i,t)}},t.openAndSendXhr=function(e,t,i){e.readyState||e.open("GET",t.url,!0);var r=t.headers,n=i.loadPolicy,s=n.maxTimeToFirstByteMs,a=n.maxLoadTimeMs;if(r)for(var o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&_(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()},t.readystatechange=function(){var e=this.context,t=this.loader,i=this.stats;if(e&&t){var r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var s=t.status,a="text"===t.responseType?t.responseText:null;if(s>=200&&s<300){var o=null!=a?a:t.response;if(null!=o){var l,h;i.loading.end=Math.max(self.performance.now(),i.loading.first);var u="arraybuffer"===t.responseType?o.byteLength:o.length;i.loaded=i.total=u,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(i,e,o,t);var c={url:t.responseURL,data:o,code:s};return void(null==(h=this.callbacks)||h.onSuccess(c,i,e,t))}}var f,g=n.loadPolicy.errorRetry;Tt(g,i.retry,!1,{url:e.url,data:void 0,code:s})?this.retry(g):($.error(s+" while loading "+e.url),null==(f=this.callbacks)||f.onError({code:s,text:t.statusText},e,t,i))}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(Tt(e,this.stats.retry,!0))this.retry(e);else{var t;$.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,i=this.stats;this.retryDelay=Et(e,i.retry),i.retry++,$.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?void 0:t.url)+", retrying "+i.retry+"/"+e.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&co.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}(),go=c(c({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:fo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:dt,bufferController:zn,capLevelController:Zn,errorController:Lt,fpsController:Vs,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:mi,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:ao,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:sa,subtitleTrackController:ca,timelineController:io,audioStreamController:Un,audioTrackController:Wn,emeController:Gs,cmcdController:Fs,contentSteeringController:Ns,interstitialsController:na});function po(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(po):Object.keys(e).reduce((function(t,i){return t[i]=po(e[i]),t}),{}):e}var vo=function(e){function t(t,i){var r;return(r=e.call(this,"gap-controller",t.logger)||this).hls=null,r.fragmentTracker=null,r.media=null,r.mediaSource=void 0,r.nudgeRetry=0,r.stallReported=!1,r.stalled=null,r.moved=!1,r.seeking=!1,r.buffered={},r.lastCurrentTime=0,r.ended=0,r.waiting=0,r.onMediaPlaying=function(){r.ended=0,r.waiting=0},r.onMediaWaiting=function(){var e;null!=(e=r.media)&&e.seeking||(r.waiting=self.performance.now(),r.tick())},r.onMediaEnded=function(){var e;r.hls&&(r.ended=(null==(e=r.media)?void 0:e.currentTime)||1,r.hls.trigger(P.MEDIA_ENDED,{stalled:!1}))},r.hls=t,r.fragmentTracker=i,r.registerListeners(),r}h(t,e);var i=t.prototype;return i.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))},i.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))},i.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},i.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var i=this.media=t.media;ta(i,"playing",this.onMediaPlaying),ta(i,"waiting",this.onMediaWaiting),ta(i,"ended",this.onMediaEnded)},i.onMediaDetaching=function(e,t){this.clearInterval();var i=this.media;i&&(ia(i,"playing",this.onMediaPlaying),ia(i,"waiting",this.onMediaWaiting),ia(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},i.onBufferAppended=function(e,t){this.buffered=t.timeRanges},i.tick=function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}},i.poll=function(e,t){var i,r,n=null==(i=this.hls)?void 0:i.config;if(n){var s=this.media,a=this.stalled;if(s){var o=s.seeking,l=this.seeking&&!o,h=!this.seeking&&o,u=s.paused&&!o||s.ended||0===s.playbackRate;if(this.seeking=o,e!==t)return t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.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&&s.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(P.MEDIA_ENDED,{stalled:!1})));if(Wt.getBuffered(s).length){var d=Wt.bufferInfo(s,e,0),c=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){var g=mo(this.hls.inFlightFragments,e),p=d.len>2,v=!c||g||c-e>2&&!f.getPartialFragment(e);if(p||v)return;this.moved=!1}var m=null==(r=this.hls)?void 0:r.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!=m&&m.live?2*m.targetduration:2,S=f.getPartialFragment(e);if(y>0&&(y<=E||S))return void(s.paused||this._trySkipBufferHole(S))}var T=n.detectStallWithCurrentTimeMs,L=self.performance.now(),_=this.waiting;if(null!==a){var b=L-a;if(!o&&(b>=T||_)&&this.hls){var A;if("ended"===(null==(A=this.mediaSource)?void 0:A.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(d),!this.media||!this.hls)return}var I=Wt.bufferInfo(s,e,n.maxBufferHole);this._tryFixBufferStall(I,b)}else this.stalled=_>0&&L-_<T?_:L}else this.nudgeRetry=0}}}},i.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var i=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(i)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(P.STALL_RESOLVED,{})}},i.nudgeOnVideoHole=function(e,t){var i,r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){var n=Wt.bufferedInfo(Wt.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var s=Wt.timeRangesToArray(r),a=Wt.bufferedInfo(s,t,0).bufferedIndex;if(a>-1&&a<s.length-1){var o=Wt.bufferedInfo(s,e,0).bufferedIndex,l=s[a].end,h=s[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=Wt.bufferInfo(this.media,e,0);this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:c.len,bufferInfo:c})}}}}},i._tryFixBufferStall=function(e,t){var i,r,n=this.fragmentTracker,s=this.media,a=null==(i=this.hls)?void 0:i.config;if(s&&n&&a){var o=s.currentTime,l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=n.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))}},i._reportStall=function(e){var t=this.hls,i=this.media,r=this.stallReported,n=this.stalled;if(!r&&null!==n&&i&&t){this.stallReported=!0;var s=new Error("Playback stalling at @"+i.currentTime+" due to low buffer ("+it(e)+")");this.warn(s.message),t.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len,bufferInfo:e,stalled:{start:n}})}},i._trySkipBufferHole=function(e){var t,i=this.fragmentTracker,r=this.media,n=null==(t=this.hls)?void 0:t.config;if(!r||!i||!n)return 0;var s=r.currentTime,a=Wt.bufferInfo(r,s,0),o=s<a.start?a.start:a.nextStart;if(o&&this.hls){var l=a.len<=n.maxBufferHole,h=a.len>0&&a.len<1&&r.readyState<3,u=o-s;if(u>0&&(l||h)){if(u>n.maxBufferHole){var d=!1;if(0===s){var c=i.getAppendedFrag(0,M);c&&o<c.end&&(d=!0)}if(!d){var f=e||i.getAppendedFrag(s,M);if(f){var g;if(null==(g=this.hls.loadLevelObj)||!g.details)return 0;if(mo(this.hls.inFlightFragments,o))return 0;for(var p=!1,v=f.end;v<o;){var m=i.getPartialFragment(v);if(!m){p=!0;break}v+=m.duration}if(p)return 0}}}var y=Math.max(o+.05,s+.1);if(this.warn("skipping hole, adjusting currentTime from "+s+" to "+y),this.moved=!0,r.currentTime=y,null==e||!e.gap){var E=new Error("fragment loaded with buffer holes, seeking from "+s+" to "+y);this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:E,reason:E.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return y}}return 0},i._tryNudgeBuffer=function(e){var t=this.hls,i=this.media,r=this.nudgeRetry,n=null==t?void 0:t.config;if(!i||!n)return 0;var s=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){var a=s+(r+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from "+s+" to "+a);this.warn(o.message),i.currentTime=a,t.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.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 @"+s+" after "+n.nudgeMaxRetry+" nudges");this.error(l.message),t.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}},n(t,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}(Ht);function mo(e,t){var i=yo(e.main);if(i&&i.start<=t)return i;var r=yo(e.audio);return r&&r.start<=t?r:null}function yo(e){if(!e)return null;switch(e.state){case er.IDLE:case er.STOPPED:case er.ENDED:case er.ERROR:return null}return e.frag}function Eo(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function So(e,t,i,r,n){var s=new e(t,i,"");try{s.value=r,n&&(s.type=n)}catch(a){s=new e(t,i,it(n?c({type:n},r):r))}return s}var To=function(){var e=Eo();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),Lo=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 i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.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&&ha(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})},t.onManifestLoading=function(){this.dateRangeCuesAppended={}},t.createTrack=function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t},t.getID3Track=function(e){if(this.media){for(var t=0;t<e.length;t++){var i=e[t];if("metadata"===i.kind&&"id3"===i.label)return oa(i,this.media),i}return this.media.addTextTrack("metadata","id3")}},t.onFragParsingMetadata=function(e,t){if(this.media){var i=this.hls.config,r=i.enableEmsgMetadataCues,n=i.enableID3MetadataCues;if(r||n){var s=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=Eo();if(a)for(var o=0;o<s.length;o++){var l=s[o].type;if((l!==Rr.emsg||r)&&n){var h=_r(s[o].data);if(h){var u=s[o].pts,d=u+s[o].duration;d>To&&(d=To),d-u<=0&&(d=u+.25);for(var c=0;c<h.length;c++){var f=h[c];if(!br(f)){this.updateId3CueEnds(u,l);var g=So(a,u,d,f,l);g&&this.id3Track.addCue(g)}}}}}}}},t.updateId3CueEnds=function(e,t){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var n=r.length;n--;){var s=r[n];s.type===t&&s.startTime<e&&s.endTime===To&&(s.endTime=e)}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,n=t.type,s=this.id3Track,a=this.hls;if(a){var o=a.config,l=o.enableEmsgMetadataCues,h=o.enableID3MetadataCues;s&&(l||h)&&ua(s,i,r,"audio"===n?function(e){return e.type===Rr.audioId3&&h}:"video"===n?function(e){return e.type===Rr.emsg&&l}:function(e){return e.type===Rr.audioId3&&h||e.type===Rr.emsg&&l})}},t.onLevelUpdated=function(e,t){var i=t.details;this.updateDateRangeCues(i,!0)},t.onLevelPtsUpdated=function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var i=this;if(this.media&&e.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var r,n=this.id3Track,s=e.dateRanges,a=Object.keys(s),o=this.dateRangeCuesAppended;if(n&&t)if(null!=(r=n.cues)&&r.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 r=t[e];r.removeEventListener("enter",i.onEventCueEnter),n.removeCue(r)}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=Eo(),f=function(){var e=a[g],t=s[e],r=t.startTime,n=o[e],l=(null==n?void 0:n.cues)||{},h=(null==n?void 0:n.durationKnown)||!1,u=To,d=t.duration;if(t.endDate&&null!==d)u=r+d,h=!0;else if(t.endOnNext&&!h){var f=a.reduce((function(e,i){if(i!==t.id){var r=s[i];if(r.class===t.class&&r.startDate>t.startDate&&(!e||t.startDate<e.startDate))return r}return e}),null);f&&(u=f.startTime,h=!0)}for(var p,v,m=Object.keys(t.attr),y=0;y<m.length;y++){var E=m[y];if("ID"!==(v=E)&&"CLASS"!==v&&"CUE"!==v&&"START-DATE"!==v&&"DURATION"!==v&&"END-DATE"!==v&&"END-ON-NEXT"!==v){var S=l[E];if(S)h&&!n.durationKnown?S.endTime=u:Math.abs(S.startTime-r)>.01&&(S.startTime=r,S.endTime=u);else if(c){var T=t.attr[E];Zt(E)&&(p=T,T=Uint8Array.from(p.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);var L=So(c,r,u,{key:E,data:T},Rr.dateRange);L&&(L.id=e,i.id3Track.addCue(L),l[E]=L,i.hls.config.interstitialsController&&("X-ASSET-LIST"!==E&&"X-ASSET-URL"!==E||L.addEventListener("enter",i.onEventCueEnter)))}}}o[e]={cues:l,dateRange:t,durationKnown:h}},g=0;g<a.length;g++)f()}}},e}(),_o=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e=t.media,i=t.levelDetails;if(e&&i){t.currentTime=e.currentTime;var r=t.computeLatency();if(null!==r){t._latency=r;var n=t.config,s=n.lowLatencyMode,a=n.maxLiveSyncPlaybackRate;if(s&&1!==a&&i.live){var o=t.targetLatency;if(null!==o){var l=r-o;if(l<Math.min(t.maxLatency,o+i.targetduration)&&l>.05&&t.forwardBufferLength>1){var h=Math.min(2,Math.max(1,a)),u=Math.round(2/(1+Math.exp(-.75*l-t.edgeStalled))*20)/20,d=Math.min(h,Math.max(1,u));t.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&t.changeMediaPlaybackRate(e,1)}}}}},this.hls=e,this.config=e.config,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},t.registerListeners=function(){var e=this.hls;e&&(e.on(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 i=t.details;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onError=function(e,t){var i;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(r=this.targetLatency)?void 0:r.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+e.playbackRate+" to "+t),e.playbackRate=t)},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},n(e,[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,i=e.partHoldBack,r=e.targetduration,n=this.config,s=n.liveSyncDuration,a=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,h=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==s?s:a*r);var u=r;return h+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var i=this.levelDetails;if(null===i)return null;var r=i.edge,n=e-t-this.edgeStalled,s=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(s,n),a)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}}])}(),bo=function(e){function t(t,i){var r;return(r=e.call(this,t,"level-controller")||this)._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,r._registerListeners(),r}h(t,e);var i=t.prototype;return i._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)},i._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)},i.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},i.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},i.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},i.onManifestLoading=function(e,t){this.resetLevels()},i.onManifestLoaded=function(e,t){var i=this,r=this.hls.config.preferManagedMediaSource,n=[],s={},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=He(d,r)||void 0),0===(null==(t=c)?void 0:t.indexOf("avc1"))&&(c=e.videoCodec=function(e){for(var t=e.split(","),i=0;i<t.length;i++){var r=t[i].split(".");if(r.length>2){var n=r.shift()+".";n+=parseInt(r.shift()).toString(16),n+=("000"+parseInt(r.shift()).toString(16)).slice(-4),t[i]=n}}return t.join(",")}(c));var f=e.width,g=e.height,p=e.unknownCodecs,v=p?p.length:0;if(p)for(var m=v;m--;){var y=p[m];i.isAudioSupported(y)?(e.audioCodec=d=d?d+","+y:y,v--,Ce.audio[d.substring(0,4)]=2):i.isVideoSupported(y)&&(e.videoCodec=c=c?c+","+y:y,v--,Ce.video[c.substring(0,4)]=2)}if(o||(o=!(!f||!g)),l||(l=!!c),h||(h=!!d),v||d&&!i.isAudioSupported(d)||c&&!i.isVideoSupported(c))i.log('Some or all CODECS not supported "'+u.CODECS+'"');else{var E=u.CODECS,S=u["FRAME-RATE"],T=u["HDCP-LEVEL"],L=u["PATHWAY-ID"],_=u.RESOLUTION,b=u["VIDEO-RANGE"],A=(L||".")+"-"+e.bitrate+"-"+_+"-"+S+"-"+E+"-"+b+"-"+T;if(s[A])if(s[A].uri===e.url||e.attrs["PATHWAY-ID"])s[A].addGroupId("audio",u.AUDIO),s[A].addGroupId("text",u.SUBTITLES);else{var I=a[A]+=1;e.attrs["PATHWAY-ID"]=new Array(I+1).join(".");var R=i.createLevel(e);s[A]=R,n.push(R)}else{var P=i.createLevel(e);s[A]=P,a[A]=1,n.push(P)}}})),this.filterAndSortMediaOptions(n,t,o,l,h)},i.createLevel=function(e){var t=new et(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){var r=new Error('SUPPLEMENTAL-CODECS not supported "'+i.videoCodec+'"');this.log(r.message),t.supportedResult=je(r,[])}return t},i.isAudioSupported=function(e){return Oe(e,"audio",this.hls.config.preferManagedMediaSource)},i.isVideoSupported=function(e){return Oe(e,"video",this.hls.config.preferManagedMediaSource)},i.filterAndSortMediaOptions=function(e,t,i,r,n){var s=this,a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter((function(e){var t,i=e.videoCodec,r=e.videoRange,n=e.width,s=e.height;return(!!i||!(!n||!s))&&!!(t=r)&&Qe.indexOf(t)>-1}))),0!==l.length){t.audioTracks&&Ao(a=t.audioTracks.filter((function(e){return!e.audioCodec||s.isAudioSupported(e.audioCodec)}))),t.subtitles&&Ao(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(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Qe.indexOf(e.videoRange)-Qe.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var r=Ne(e.videoCodec),n=Ne(t.videoCodec);if(r!==n)return n-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var s=Be(e.codecSet),a=Be(t.codecSet);if(s!==a)return a-s}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 v=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);v>p&&p===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}var m=n&&!r,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:n,video:r,altAudio:E&&!m&&a.some((function(e){return!!e.url}))};this.hls.trigger(P.MANIFEST_PARSED,S)}else Promise.resolve().then((function(){if(s.hls){var e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i="one or more CODECS in variant not supported: "+it(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,i){return i.indexOf(e)===t}))),s.warn(i),e+=" ("+i+")");var r=new Error(e);s.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}))},i.onError=function(e,t){!t.fatal&&t.context&&t.context.type===D&&t.context.level===this.level&&this.checkRetry(t)},i.onFragBuffered=function(e,t){var i=t.frag;if(void 0!==i&&i.type===M){var r=i.elementaryStreams;if(!Object.keys(r).some((function(e){return!!r[e]})))return;var n=this._levels[i.level];null!=n&&n.loadError&&(this.log("Resetting level error count of "+n.loadError+" on frag buffered"),n.loadError=0)}},i.onLevelLoaded=function(e,t){var i,r,n=t.level,s=t.details,a=t.levelInfo;if(!a)return this.warn("Invalid level index "+n),void(null!=(r=t.deliveryDirectives)&&r.skip&&(s.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(n,t,o)}else null!=(i=t.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=this.getUrlWithDirectives(t.uri,i),n=this.currentLevelIndex,s=t.attrs["PATHWAY-ID"],a=t.details,o=null==a?void 0:a.age;this.log("Loading level index "+n+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(s?" Pathway "+s:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+r),this.hls.trigger(P.LEVEL_LOADING,{url:r,level:n,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||null})},i.removeLevel=function(e){var t,i=this;if(1!==this._levels.length){var r=this._levels.filter((function(t,r){return r!==e||(i.steering&&i.steering.removeLevel(t),t===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));Yi(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=r.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(P.LEVELS_UPDATED,{levels:r})}},i.onLevelsUpdated=function(e,t){var i=t.levels;this._levels=i},i.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,i=e.maxAutoLevel,r=e.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(P.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))},n(t,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,s=this.currentLevel,a=s?s.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!s||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 "+n+(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==s?void 0:s.details,u);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),i=e.filter((function(e){return-1!==t.indexOf(e)}));if(e.length<1)return void this.warn("pathwayPriority "+e+" should contain at least one pathway from list: "+t);this.steering.pathwayPriority=i}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])}(Gn);function Ao(e){var t={};e.forEach((function(e){var i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}function Io(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ro(){if(!q())return!1;var e=Io();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var Po=function(e){function t(t,i,r){var n;return(n=e.call(this,t,i,r,"stream-controller",M)||this).audioCodecSwap=!1,n.level=-1,n._forceStartLoad=!1,n._hasEnoughToStart=!1,n.altAudio=0,n.audioOnly=!1,n.fragPlaying=null,n.fragLastKbps=0,n.couldBacktrack=!1,n.backtrackFragment=null,n.audioCodecSwitch=!1,n.videoBuffer=null,n.onMediaPlaying=function(){n.tick()},n.onMediaSeeked=function(){var e=n.media,t=e?e.currentTime:null;if(null!==t&&_(t)&&(n.log("Media seeked to "+t.toFixed(3)),n.getBufferedFrag(t))){var i=n.getFwdBufferInfoAtPos(e,t,M,0);null!==i&&0!==i.len?n.tick():n.warn("Main forward buffer length at "+t+' on "seeked" event '+(i?i.len:"empty")+")")}},n.registerListeners(),n}h(t,e);var i=t.prototype;return i.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)},i.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)},i.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},i.startLoad=function(e,t){if(this.levels){var i=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=r.startLevel;-1===n&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i),this.state=er.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=er.STOPPED},i.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},i.doTick=function(){switch(this.state){case er.WAITING_LEVEL:var e=this.levels,t=this.level,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=er.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=er.IDLE;break}break;case er.FRAG_LOADING_WAITING_RETRY:var n,s=self.performance.now(),a=this.retryDate;if(!a||s>=a||null!=(n=this.media)&&n.seeking){var o=this.levels,l=this.level,h=null==o?void 0:o[l];this.resetStartWhenNotLoaded(h||null),this.state=er.IDLE}}this.state===er.IDLE&&this.doTickIdle(),this.onTickEnd()},i.onTickEnd=function(){var t;e.prototype.onTickEnd.call(this),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},i.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,i=this.levels,r=this.media;if(null!==t&&(r||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=i&&i[n]){var s=i[n],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=er.ENDED)}if(this.buffering){e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level "+n+" from level "+this.level),this.level=e.nextLoadLevel=n;var h=s.details;if(!h||this.state===er.WAITING_LEVEL||this.waitForLive(s))return this.level=n,this.state=er.WAITING_LEVEL,void(this.startFragRequested=!1);var u=a.len,d=this.getMaxBufferLength(s.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&&te(f)&&this.fragmentTracker.getState(f)!==Rt){var g,p=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,v=h.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?Q:J,y=(m===J?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m,M)}f=this.getNextFragmentLoopLoading(f,h,a,M,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,s,c))}}}}}},i.loadFragment=function(t,i,r){var n=this.fragmentTracker.getState(t);n===bt||n===It?te(t)?this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,i)):e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i):this.clearTrackerIfNeeded(t)},i.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,M)},i.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},i.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},i.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var s=this.getMainFwdBufferInfo();if(!s||s.len<2*n.targetduration)return}if(!t.paused&&e){var a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;i=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(t.currentTime+i);if(l){var h=this.followingBufferedFrag(l);if(h){this.abortCurrentFrag();var u=h.maxStartPTS?h.maxStartPTS:h.start,d=h.duration,c=Math.max(l.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},i.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case er.KEY_LOADING:case er.FRAG_LOADING:case er.FRAG_LOADING_WAITING_RETRY:case er.PARSING:case er.PARSED:this.state=er.IDLE}this.nextLoadPosition=this.getLoadPosition()},i.flushMainBuffer=function(t,i){e.prototype.flushMainBuffer.call(this,t,i,2===this.altAudio?"video":null)},i.onMediaAttached=function(t,i){e.prototype.onMediaAttached.call(this,t,i);var r=i.media;ta(r,"playing",this.onMediaPlaying),ta(r,"seeked",this.onMediaSeeked)},i.onMediaDetaching=function(t,i){var r=this.media;r&&(ia(r,"playing",this.onMediaPlaying),ia(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,e.prototype.onMediaDetaching.call(this,t,i),i.transferMedia||(this._hasEnoughToStart=!1)},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(P.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},i.onManifestParsed=function(e,t){var i,r,n=!1,s=!1;t.levels.forEach((function(e){var t=e.audioCodec;t&&(n=n||-1!==t.indexOf("mp4a.40.2"),s=s||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=n&&s&&!("function"==typeof(null==(r=Io())||null==(i=r.prototype)?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1},i.onLevelLoading=function(e,t){if(this.levels&&this.state===er.IDLE){var i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=er.WAITING_LEVEL)}},i.onLevelLoaded=function(e,t){var i,r=this.levels,n=this.startFragRequested,s=t.level,a=t.details,o=a.totalduration;if(r){this.log("Level "+s+" 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!==er.FRAG_LOADING&&this.state!==er.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();var u=0;if(a.live||null!=(i=l.details)&&i.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,n||this.setStartPosition(a,u),this.hls.trigger(P.LEVEL_UPDATED,{details:a,level:s}),this.state===er.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=er.IDLE}n&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}else this.warn("Levels were reset while loading level "+s)},i.synchronizeToLiveEdge=function(e){var t=this.config,i=this.media;if(i){var r=this.hls.liveSyncPosition,n=this.getLoadPosition(),s=e.fragmentStart,a=e.edge,o=n>=s-t.maxFragLookUpTolerance&&n<=a;if(null!==r&&i.duration>r&&(n<r||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&i.readyState<4||n<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState&&(this.warn("Playback: "+n.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+r.toFixed(3)),i.currentTime=r))}}},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,n=e.payload,s=this.levels;if(s){var a=s[i.level];if(a){var o=a.details;if(!o)return this.warn("Dropping fragment "+i.sn+" of level "+i.level+" after level details were reset"),void this.fragmentTracker.removeFragment(i);var l=a.videoCodec,h=o.PTSKnown||!o.live,u=null==(t=i.initSegment)?void 0:t.data,d=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Bn(this.hls,M,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,p=new Vt(i.level,i.sn,i.stats.chunkCount,n.byteLength,f,g),v=this.initPTS[i.cc];c.push(n,u,d,l,i,r,o.totalduration,h,p,v)}else this.warn("Level "+i.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i.onAudioTrackSwitching=function(e,t){var i=this,r=this.hls,n=2===this.altAudio;if(ut(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;s&&(this.log("Switching to main audio track, cancel main fragment load"),s.abortRequests(),this.fragmentTracker.removeFragment(s)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n)return this.fragmentTracker.removeAllFragments(),r.once(P.BUFFER_FLUSHED,(function(){var e;null==(e=i.hls)||e.trigger(P.AUDIO_TRACK_SWITCHED,t)})),void r.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(P.AUDIO_TRACK_SWITCHED,t)}},i.onAudioTrackSwitched=function(e,t){var i=ut(t.url,this.hls);if(i){var r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i?2:0,this.tick()},i.onBufferCreated=function(e,t){var i,r,n=t.tracks,s=!1;for(var a in n){var o=n[a];if("main"===o.id){if(r=a,i=o,"video"===a){var l=n[a];l&&(this.videoBuffer=l.buffer)}}else s=!0}s&&i?(this.log("Alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,n=i.type===M;if(n){if(this.fragContextChanged(i))return this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===er.PARSED&&(this.state=er.IDLE));var s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),te(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}var a=this.media;a&&(!this._hasEnoughToStart&&Wt.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())},i.onError=function(e,t){var i;if(t.fatal)this.state=er.ERROR;else switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(M,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==er.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==D||(this.state=er.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},i.onFragLoadEmergencyAborted=function(){this.state=er.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==Q||!this.altAudio){var r=(i===J?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,i,M),this.tick())}},i.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels},i.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},i.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log("could not seek to "+i+", already seeking at "+t);var r=this.timelineOffset;r&&i&&(i+=r);var n=this.getLevelDetails(),s=Wt.getBuffered(e),a=s.length?s.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);o>0&&(o<l||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0))&&(this.log("adjusting start position by "+o+" to match buffer start"),i+=o,this.startPosition=i),t<i&&(this.log("seek to target start position "+i+" from current time "+t+" buffer start "+a),e.currentTime=i)}}},i._getAudioCodec=function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t},i._loadBitrateTestFrag=function(e,t){var i=this;e.bitrateTest=!0,this._doFragLoad(e,t).then((function(e){var r=i.hls,n=null==e?void 0:e.frag;if(n&&!i.fragContextChanged(n)){t.fragmentError=0,i.state=er.IDLE,i.startFragRequested=!1,i.bitrateTest=!1;var s=n.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(P.FRAG_LOADED,e),n.bitrateTest=!1}}))},i._handleTransmuxComplete=function(e){var t,i=this.playlistType,r=this.hls,n=e.remuxResult,s=e.chunkMeta,a=this.getCurrentContext(s);if(a){var o=a.frag,l=a.part,h=a.level,u=n.video,d=n.text,c=n.id3,f=n.initSegment,g=h.details,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=er.PARSING,f){if(null!=f&&f.tracks){var v=o.initSegment||o;this._bufferInitSegment(h,f.tracks,v,s),r.trigger(P.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:f.tracks})}var m=f.initPTS,y=f.timescale;_(m)&&(this.initPTS[o.cc]={baseTime:m,timescale:y},r.trigger(P.INIT_PTS_FOUND,{frag:o,id:i,initPTS:m,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!==n.independent){var L=u.startPTS,b=u.endPTS,A=u.startDTS,I=u.endDTS;if(l)l.elementaryStreams[u.type]={startPTS:L,endPTS:b,startDTS:A,endDTS:I};else if(u.firstKeyFrame&&u.independent&&1===s.id&&!T&&(this.couldBacktrack=!0),u.dropped&&u.independent){var R=this.getMainFwdBufferInfo(),k=(R?R.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:L;if(!S&&k<D-this.config.maxBufferHole&&!T)return void this.backtrack(o);T&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,b,o.start,I,!0)}else S&&L-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,L,b,A,I),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,s,S||T)}else{if(!S&&!T)return void this.backtrack(o);o.gap=!0}}if(p){var w=p.startPTS,C=p.endPTS,M=p.startDTS,O=p.endDTS;l&&(l.elementaryStreams[Q]={startPTS:w,endPTS:C,startDTS:M,endDTS:O}),o.setElementaryStreamInfo(Q,w,C,M,O),this.bufferFragmentData(p,o,l,s)}if(g&&null!=c&&null!=(t=c.samples)&&t.length){var x={id:i,frag:o,details:g,samples:c.samples};r.trigger(P.FRAG_PARSING_METADATA,x)}if(g&&d){var F={id:i,frag:o,details:g,samples:d.samples};r.trigger(P.FRAG_PARSING_USERDATA,F)}}}else this.resetWhenMissingContext(s)},i.logMuxedErr=function(e){this.warn((te(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},i._bufferInitSegment=function(e,t,i,r){var n=this;if(this.state===er.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));var s=t.audio,a=t.video,o=t.audiovideo;if(s){var l=Ve(s.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=s.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"!==s.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+'"'),s.levelCodec=l,s.id=M,this.log("Init audio buffer, container:"+s.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(e.audioCodec||"")+"/"+s.codec+"]"),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=M;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 s=t[e].initSegment;null!=s&&s.byteLength&&n.hls.trigger(P.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}},i.getMainFwdBufferInfo=function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,M)},i.backtrack=function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=er.IDLE},i.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var i=e.currentTime;if(Wt.isBuffered(e,i)?t=this.getAppendedFrag(i):Wt.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;var r=this.fragPlaying,n=t.level;r&&t.sn===r.sn&&r.level===n||(this.fragPlaying=t,this.hls.trigger(P.FRAG_CHANGED,{frag:t}),r&&r.level===n||this.hls.trigger(P.LEVEL_SWITCHED,{level:n}))}}},n(t,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return _(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(_(t)){var i=this.getLevelDetails(),r=this.currentFrag||(i?ft(null,i.fragments,t):null);if(r){var n=r.programDateTime;if(null!==n){var s=n+1e3*(t-r.start);return new Date(s)}}}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}}])}(tr),ko=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 i=this.keyUriToKeyInfo[t].loader;if(i){var r;if(e&&e!==(null==(r=i.context)?void 0:r.frag.type))return;i.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,i,r,n){return void 0===t&&(t=R.KEY_LOAD_ERROR),new Gt({type:I.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})},t.loadClear=function(e,t){var i=this;if(this.emeController&&this.config.emeEnabled)for(var r=e.sn,n=e.cc,s=function(){var e=t[a];if(n<=e.cc&&("initSegment"===r||"initSegment"===e.sn||r<e.sn))return i.emeController.selectKeySystemFormat(e).then((function(t){e.setKeyFormat(t)})),1},a=0;a<t.length&&!s();a++);},t.load=function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(i){return t.loadInternal(e,i)})):this.loadInternal(e)},t.loadInternal=function(e,t){var i,r;t&&e.setKeyFormat(t);var n=e.decryptdata;if(!n){var s=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,R.KEY_LOAD_ERROR,s))}var a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+a+'"')));var o,l=this.keyUriToKeyInfo[a];if(null!=(i=l)&&i.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(null!=(r=l)&&r.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 n.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:l}}))}switch(l=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.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,R.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+n.method+'"')))}},t.loadKeyEME=function(e,t){var i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r=this.emeController.loadKey(i);if(r)return(e.keyLoadPromise=r.then((function(t){return e.mediaKeySessionContext=t,i}))).catch((function(t){throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)},t.loadKeyHTTP=function(e,t){var i=this,r=this.config,n=new(0,r.loader)(r);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((function(s,a){var o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,n){var o=r.frag,l=r.keyInfo,h=r.url;if(!o.decryptdata||l!==i.keyUriToKeyInfo[h])return a(i.createKeyLoadError(o,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,l.loader=null,s({frag:o,keyInfo:l})},onError:function(e,r,n,s){i.resetLoader(r),a(i.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error("HTTP Error "+e.code+" loading key "+e.text),n,c({url:o.url,data:void 0},e)))},onTimeout:function(e,r,n){i.resetLoader(r),a(i.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:function(e,r,n){i.resetLoader(r),a(i.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(o,h,u)}))},t.resetLoader=function(e){var t=e.frag,i=e.keyInfo,r=e.url,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy()},e}();function Do(e){switch(e.type){case w:return O;case C:return x;default:return M}}function wo(e,t){var i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}var Co=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,i=t.pLoader,r=t.loader,n=new(i||r)(t);return this.loaders[e.type]=n,n},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var i=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:k,url:i,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var i=t.id,r=t.level,n=t.pathwayId,s=t.url,a=t.deliveryDirectives,o=t.levelInfo;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:D,url:s,deliveryDirectives:a,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var i=t.id,r=t.groupId,n=t.url,s=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:w,url:n,deliveryDirectives:s,levelOrTrack:a})},t.onSubtitleTrackLoading=function(e,t){var i=t.id,r=t.groupId,n=t.url,s=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:C,url:n,deliveryDirectives:s,levelOrTrack:a})},t.onLevelsUpdated=function(e,t){var i=this.loaders[D];if(i){var r=i.context;r&&!t.levels.some((function(e){return e===r.levelOrTrack}))&&(i.abort(),delete this.loaders[D])}},t.load=function(e){var t,i,r,n=this,s=this.hls.config,a=this.getInternalLoader(e);if(a){var l=this.hls.logger,h=a.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),a.abort()}if(i=e.type===k?s.manifestLoadPolicy.default:o({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(e),_(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===D&&null!==e.level?r=this.hls.levels[e.level].details:e.type===w&&null!==e.id?r=this.hls.audioTracks[e.id].details:e.type===C&&null!==e.id&&(r=this.hls.subtitleTracks[e.id].details),r)){var u=r.partTarget,d=r.targetduration;if(u&&d){var c=1e3*Math.max(3*u,.8*d);i=o({},i,{maxTimeToFirstByteMs:Math.min(c,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,i.maxTimeToFirstByteMs)})}}var f=i.errorRetry||i.timeoutRetry||{},g={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},p={onSuccess:function(e,t,i,r){var s=n.getInternalLoader(i);n.resetInternalLoader(i.type);var a=e.data;0===a.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Ii.isMediaPlaylist(a)||i.type!==k?n.handleTrackOrLevelPlaylist(e,t,i,r||null,s):n.handleMasterPlaylist(e,t,i,r)):n.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),r||null,t)},onError:function(e,t,i,r){n.handleNetworkError(t,i,!1,e,r)},onTimeout:function(e,t,i){n.handleNetworkError(t,i,!0,void 0,e)}};a.load(e,g,p)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,i=t.autoStartLoad,r=t.startPosition,n=e.forceStartLoad;(i||n)&&(this.hls.logger.log((i?"auto":"force")+" startLoad with configured startPosition "+r),this.hls.startLoad(r))}},t.handleMasterPlaylist=function(e,t,i,r){var n=this.hls,s=e.data,a=wo(e,i),o=Ii.parseMasterPlaylist(s,a);if(o.playlistParsingError)this.handleManifestParsingError(e,i,o.playlistParsingError,r,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=Ii.parseMasterPlaylistMedia(s,a,o),p=g.AUDIO,v=void 0===p?[]:p,m=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];v.length&&(v.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"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Jt({}),bitrate:0,url:""}))),n.trigger(P.MANIFEST_LOADED,{levels:h,audioTracks:v,subtitles:m,captions:y,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:u,sessionKeys:d,startTimeOffset:c,variableList:f})}},t.handleTrackOrLevelPlaylist=function(e,t,i,r,n){var s=this.hls,a=i.id,o=i.level,l=i.type,h=wo(e,i),u=_(o)?o:_(a)?a:0,d=Do(i),c=Ii.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===k){var f={attrs:new Jt({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=t.loading.start+Wi(c,0),s.trigger(P.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,e,t,i,r,n)},t.handleManifestParsingError=function(e,t,i,r,n){this.hls.trigger(P.ERROR,{type:I.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===k,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})},t.handleNetworkError=function(e,t,i,r,n){void 0===i&&(i=!1);var s="A network "+(i?"timeout":"error"+(r?" (status "+r.code+")":""))+" occurred while loading "+e.type;e.type===D?s+=": "+e.level+" id: "+e.id:e.type!==w&&e.type!==C||(s+=" id: "+e.id+' group-id: "'+e.groupId+'"');var a=new Error(s);this.hls.logger.warn("[playlist-loader]: "+s);var o=R.UNKNOWN,l=!1,h=this.getInternalLoader(e);switch(e.type){case k:o=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case D:o=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case w:o=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case C:o=i?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);var u={type:I.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:n};if(r){var d=(null==t?void 0:t.url)||e.url;u.response=c({url:d,data:void 0},r)}this.hls.trigger(P.ERROR,u)},t.handlePlaylistLoaded=function(e,t,i,r,n,s){var a=this.hls,o=r.type,l=r.level,h=r.id,u=r.groupId,d=r.deliveryDirectives,c=wo(t,r),f=Do(r),g="number"==typeof r.level&&f===M?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:I.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:p,reason:p.message,response:t,context:r,level:g,parent:f,networkDetails:n,stats:i});e.playlistParsingError=null}switch(e.live&&s&&(s.getCacheAge&&(e.ageHeader=s.getCacheAge()||0),s.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case k:case D:a.trigger(P.LEVEL_LOADED,{details:e,levelInfo:r.levelOrTrack||a.levels[0],level:g||0,id:h||0,stats:i,networkDetails:n,deliveryDirectives:d,withoutMultiVariant:o===k});break;case w:a.trigger(P.AUDIO_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:d});break;case C:a.trigger(P.SUBTITLE_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:d})}}else{var v=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(P.ERROR,{type:I.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:v,reason:v.message,response:t,context:r,level:g,parent:f,networkDetails:n,stats:i})}},e}(),Mo=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 S,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var i=this.logger=W(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=po(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var s=("level"===e?"playlist":e)+"LoadPolicy",a=void 0===t[s],o=[];n.forEach((function(i){var n=e+"Loading"+i,l=t[n];if(void 0!==l&&a){o.push(n);var h=r[s].default;switch(t[s]={default:h},i){case"TimeOut":h.maxLoadTimeMs=l,h.maxTimeToFirstByteMs=l;break;case"MaxRetry":h.errorRetry.maxNumRetry=l,h.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":h.errorRetry.retryDelayMs=l,h.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=l,h.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+s+'": '+it(t[s]))})),c(c({},r),t)}(e.DefaultConfig,t,i);this.userConfig=t,r.progressive&&function(e,t){var i=e.loader;i!==lo&&i!==fo?(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=lo,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(r,i);var n=r.abrController,s=r.bufferController,a=r.capLevelController,o=r.errorController,l=r.fpsController,h=new o(this),u=this.abrController=new n(this),d=new Pt(this),f=r.interstitialsController,g=f?this.interstitialsController=new f(this,e):null,p=this.bufferController=new s(this,d),v=this.capLevelController=new a(this),m=new l(this),y=new Co(this),E=r.contentSteeringController,T=E?new E(this):null,L=this.levelController=new bo(this,T),_=new Lo(this),b=new ko(this.config),A=this.streamController=new Po(this,d,b),I=this.gapController=new vo(this,d);v.setStreamController(A),m.setStreamController(A);var R=[y,L,A];g&&R.splice(1,0,g),T&&R.splice(1,0,T),this.networkControllers=R;var k=[u,p,I,v,m,_,d];this.audioTrackController=this.createController(r.audioTrackController,R);var D=r.audioStreamController;D&&R.push(this.audioStreamController=new D(this,d,b)),this.subtitleTrackController=this.createController(r.subtitleTrackController,R);var w=r.subtitleStreamController;w&&R.push(this.subtititleStreamController=new w(this,d,b)),this.createController(r.timelineController,k),b.emeController=this.emeController=this.createController(r.emeController,k),this.cmcdController=this.createController(r.cmcdController,k),this.latencyController=this.createController(_o,k),this.coreComponents=k,R.push(h);var C=h.onErrorOut;"function"==typeof C&&this.on(P.ERROR,C,h),this.on(P.MANIFEST_LOADED,y.onManifestLoaded,y)}e.isMSESupported=function(){return Ro()},e.isSupported=function(){return function(){if(!Ro())return!1;var e=q();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(Fe(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Fe(t,"audio"))})))}()},e.getMediaSource=function(){return q()};var t=e.prototype;return t.createController=function(e,t){if(e){var i=new e(this);return t&&t.push(i),i}return null},t.on=function(e,t,i){void 0===i&&(i=this),this._emitter.on(e,t,i)},t.once=function(e,t,i){void 0===i&&(i=this),this._emitter.once(e,t,i)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,i,r){void 0===i&&(i=this),this._emitter.off(e,t,i,r)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,i){return this._emitter.emit(e,t,i)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var i=e===P.ERROR;this.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){this.logger.log("destroy"),this.trigger(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:I.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var i="media"in e,r=i?e.media:e,n=i?e:{media:r};this._media=r,this.trigger(P.MEDIA_ATTACHING,n)}},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,i=this._url,r=this._url=L.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+r),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(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 i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);},t.stopLoad=function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);},t.resumeBuffering=function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((function(e){e.resumeBuffering&&e.resumeBuffering()})))},t.pauseBuffering=function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((function(e){e.pauseBuffering&&e.pauseBuffering()})))},t.swapAudioCodec=function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.recoverMediaError=function(){this.logger.log("recoverMediaError");var e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))},t.removeLevel=function(e){this.levelController.removeLevel(e)},t.setAudioOption=function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null},t.setSubtitleOption=function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null},t.getMediaDecodingInfo=function(e,t){return void 0===t&&(t=this.allAudioTracks),ze(e,nt(t),navigator.mediaCapabilities)},n(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={})[M]=this.streamController.inFlightFrag,e);return this.audioStreamController&&(t[O]=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(r){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(i+16*Math.random())%16|0;return i=Math.floor(i/16),("x"==e?t:3&t|8).toString(16)}))}}}()),e}},{key:"levels",get:function(){return this.levelController.levels||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return Xe.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var i=e.length,r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(var n=e;n--;){var s=t[n].attrs["HDCP-LEVEL"];if(s&&s<=r)return n}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 xn}},{key:"Events",get:function(){return P}},{key:"MetadataSchema",get:function(){return Rr}},{key:"ErrorTypes",get:function(){return I}},{key:"ErrorDetails",get:function(){return R}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:go},set:function(t){e.defaultConfig=t}}])}();return Mo.defaultConfig=void 0,Mo},e.exports=r()}(!1)},424:(e,t)=>{"use strict";t.h=n;var i=2147483647;function r(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=n.prototype,t}function n(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return s(e,t,i)}function s(e,t,i){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!n.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var i=0|u(e,t),s=r(i),a=s.write(e,t);a!==i&&(s=s.slice(0,a));return s}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(m(e,ArrayBuffer)||e&&m(e.buffer,ArrayBuffer))return function(e,t,i){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(i||0))throw new RangeError('"length" is outside of buffer bounds');var r;r=void 0===t&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,t):new Uint8Array(e,t,i);return r.__proto__=n.prototype,r}(e,t,i);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var s=e.valueOf&&e.valueOf();if(null!=s&&s!==e)return n.from(s,t,i);var a=function(e){if(n.isBuffer(e)){var t=0|h(e.length),i=r(t);return 0===i.length||e.copy(i,0,0,t),i}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?r(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return n.from(e[Symbol.toPrimitive]("string"),t,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function a(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function o(e){return a(e),r(e<0?0:0|h(e))}function l(e){for(var t=e.length<0?0:0|h(e.length),i=r(t),n=0;n<t;n+=1)i[n]=255&e[n];return i}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function u(e,t){if(n.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||m(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var i=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===i)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return v(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;default:if(s)return r?-1:v(e).length;t=(""+t).toLowerCase(),s=!0}}function d(e,t,i,r){i=Number(i)||0;const n=e.length-i;r?(r=Number(r))>n&&(r=n):r=n;const s=t.length;let a;for(r>s/2&&(r=s/2),a=0;a<r;++a){const r=parseInt(t.substr(2*a,2),16);if(y(r))return a;e[i+a]=r}return a}function c(e,t,i,r){return p(v(t,e.length-i),e,i,r)}function f(e,t,i,r){return p(function(e){const t=[];for(let i=0;i<e.length;++i)t.push(255&e.charCodeAt(i));return t}(t),e,i,r)}function g(e,t,i,r){return p(function(e,t){let i,r,n;const s=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)i=e.charCodeAt(a),r=i>>8,n=i%256,s.push(n),s.push(r);return s}(t,e.length-i),e,i,r)}function p(e,t,i,r){let n;for(n=0;n<r&&!(n+i>=t.length||n>=e.length);++n)t[n+i]=e[n];return n}function v(e,t){var i;t=t||1/0;for(var r=e.length,n=null,s=[],a=0;a<r;++a){if((i=e.charCodeAt(a))>55295&&i<57344){if(!n){if(i>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&s.push(239,191,189);continue}n=i;continue}if(i<56320){(t-=3)>-1&&s.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(t-=3)>-1&&s.push(239,191,189);if(n=null,i<128){if((t-=1)<0)break;s.push(i)}else if(i<2048){if((t-=2)<0)break;s.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;s.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return s}function m(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&n[Symbol.species]===n&&Object.defineProperty(n,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),n.from=function(e,t,i){return s(e,t,i)},n.prototype.__proto__=Uint8Array.prototype,n.__proto__=Uint8Array,n.alloc=function(e,t,i){return function(e,t,i){return a(e),e<=0?r(e):void 0!==t?"string"==typeof i?r(e).fill(t,i):r(e).fill(t):r(e)}(e,t,i)},n.allocUnsafe=function(e){return o(e)},n.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==n.prototype},n.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}},n.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return n.alloc(0);var i;if(void 0===t)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=n.allocUnsafe(t),s=0;for(i=0;i<e.length;++i){var a=e[i];if(m(a,Uint8Array)&&(a=n.from(a)),!n.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(r,s),s+=a.length}return r},n.byteLength=u,n.prototype._isBuffer=!0,n.prototype.copy=function(e,t,i,r){if(!n.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var s=r-i;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,i,r);else if(this===e&&i<t&&t<r)for(var a=s-1;a>=0;--a)e[a+t]=this[a+i];else Uint8Array.prototype.set.call(e,this.subarray(i,r),t);return s},n.prototype.write=function(e,t,i,r){if(void 0===t)r="utf8",i=this.length,t=0;else if(void 0===i&&"string"==typeof t)r=t,i=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(i)?(i>>>=0,void 0===r&&(r="utf8")):(r=i,i=void 0)}const n=this.length-t;if((void 0===i||i>n)&&(i=n),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!1;for(;;)switch(r){case"hex":return d(this,e,t,i);case"utf8":case"utf-8":return c(this,e,t,i);case"ascii":case"latin1":case"binary":return f(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,i);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}}},832:function(e,t,i){var r;!function(n){"use strict";function s(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function a(e,t,i,r,n,a){return s((o=s(s(t,e),s(r,a)))<<(l=n)|o>>>32-l,i);var o,l}function o(e,t,i,r,n,s,o){return a(t&i|~t&r,e,t,n,s,o)}function l(e,t,i,r,n,s,o){return a(t&r|i&~r,e,t,n,s,o)}function h(e,t,i,r,n,s,o){return a(t^i^r,e,t,n,s,o)}function u(e,t,i,r,n,s,o){return a(i^(t|~r),e,t,n,s,o)}function d(e,t){var i,r,n,a,d;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var c=1732584193,f=-271733879,g=-1732584194,p=271733878;for(i=0;i<e.length;i+=16)r=c,n=f,a=g,d=p,c=o(c,f,g,p,e[i],7,-680876936),p=o(p,c,f,g,e[i+1],12,-389564586),g=o(g,p,c,f,e[i+2],17,606105819),f=o(f,g,p,c,e[i+3],22,-1044525330),c=o(c,f,g,p,e[i+4],7,-176418897),p=o(p,c,f,g,e[i+5],12,1200080426),g=o(g,p,c,f,e[i+6],17,-1473231341),f=o(f,g,p,c,e[i+7],22,-45705983),c=o(c,f,g,p,e[i+8],7,1770035416),p=o(p,c,f,g,e[i+9],12,-1958414417),g=o(g,p,c,f,e[i+10],17,-42063),f=o(f,g,p,c,e[i+11],22,-1990404162),c=o(c,f,g,p,e[i+12],7,1804603682),p=o(p,c,f,g,e[i+13],12,-40341101),g=o(g,p,c,f,e[i+14],17,-1502002290),c=l(c,f=o(f,g,p,c,e[i+15],22,1236535329),g,p,e[i+1],5,-165796510),p=l(p,c,f,g,e[i+6],9,-1069501632),g=l(g,p,c,f,e[i+11],14,643717713),f=l(f,g,p,c,e[i],20,-373897302),c=l(c,f,g,p,e[i+5],5,-701558691),p=l(p,c,f,g,e[i+10],9,38016083),g=l(g,p,c,f,e[i+15],14,-660478335),f=l(f,g,p,c,e[i+4],20,-405537848),c=l(c,f,g,p,e[i+9],5,568446438),p=l(p,c,f,g,e[i+14],9,-1019803690),g=l(g,p,c,f,e[i+3],14,-187363961),f=l(f,g,p,c,e[i+8],20,1163531501),c=l(c,f,g,p,e[i+13],5,-1444681467),p=l(p,c,f,g,e[i+2],9,-51403784),g=l(g,p,c,f,e[i+7],14,1735328473),c=h(c,f=l(f,g,p,c,e[i+12],20,-1926607734),g,p,e[i+5],4,-378558),p=h(p,c,f,g,e[i+8],11,-2022574463),g=h(g,p,c,f,e[i+11],16,1839030562),f=h(f,g,p,c,e[i+14],23,-35309556),c=h(c,f,g,p,e[i+1],4,-1530992060),p=h(p,c,f,g,e[i+4],11,1272893353),g=h(g,p,c,f,e[i+7],16,-155497632),f=h(f,g,p,c,e[i+10],23,-1094730640),c=h(c,f,g,p,e[i+13],4,681279174),p=h(p,c,f,g,e[i],11,-358537222),g=h(g,p,c,f,e[i+3],16,-722521979),f=h(f,g,p,c,e[i+6],23,76029189),c=h(c,f,g,p,e[i+9],4,-640364487),p=h(p,c,f,g,e[i+12],11,-421815835),g=h(g,p,c,f,e[i+15],16,530742520),c=u(c,f=h(f,g,p,c,e[i+2],23,-995338651),g,p,e[i],6,-198630844),p=u(p,c,f,g,e[i+7],10,1126891415),g=u(g,p,c,f,e[i+14],15,-1416354905),f=u(f,g,p,c,e[i+5],21,-57434055),c=u(c,f,g,p,e[i+12],6,1700485571),p=u(p,c,f,g,e[i+3],10,-1894986606),g=u(g,p,c,f,e[i+10],15,-1051523),f=u(f,g,p,c,e[i+1],21,-2054922799),c=u(c,f,g,p,e[i+8],6,1873313359),p=u(p,c,f,g,e[i+15],10,-30611744),g=u(g,p,c,f,e[i+6],15,-1560198380),f=u(f,g,p,c,e[i+13],21,1309151649),c=u(c,f,g,p,e[i+4],6,-145523070),p=u(p,c,f,g,e[i+11],10,-1120210379),g=u(g,p,c,f,e[i+2],15,718787259),f=u(f,g,p,c,e[i+9],21,-343485551),c=s(c,r),f=s(f,n),g=s(g,a),p=s(p,d);return[c,f,g,p]}function c(e){var t,i="",r=32*e.length;for(t=0;t<r;t+=8)i+=String.fromCharCode(e[t>>5]>>>t%32&255);return i}function f(e){var t,i=[];for(i[(e.length>>2)-1]=void 0,t=0;t<i.length;t+=1)i[t]=0;var r=8*e.length;for(t=0;t<r;t+=8)i[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return i}function g(e){var t,i,r="0123456789abcdef",n="";for(i=0;i<e.length;i+=1)t=e.charCodeAt(i),n+=r.charAt(t>>>4&15)+r.charAt(15&t);return n}function p(e){return unescape(encodeURIComponent(e))}function v(e){return function(e){return c(d(f(e),8*e.length))}(p(e))}function m(e,t){return function(e,t){var i,r,n=f(e),s=[],a=[];for(s[15]=a[15]=void 0,n.length>16&&(n=d(n,8*e.length)),i=0;i<16;i+=1)s[i]=909522486^n[i],a[i]=1549556828^n[i];return r=d(s.concat(f(t)),512+8*t.length),c(d(a.concat(r),640))}(p(e),p(t))}function y(e,t,i){return t?i?m(t,e):g(m(t,e)):i?v(e):g(v(e))}void 0===(r=function(){return y}.call(t,i,t,e))||(e.exports=r)}()},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var i={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(r())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return i.isAndroid()||i.isAndroidWebView()?t.ANDROID_WEB:i.isIOS()||i.isIpad()||i.isIOSWebView()?t.IOS_WEB:i.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(r())},isPC:function(){return!s(n("os "))&&!s(n("android[/ ]"))},isIOS:function(){return s(n("os "))},isIpad:function(){return r().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return s(n("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(r())},isMobile:function(){return i.isAndroid()||i.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(r())},isFirefox:function(){return/firefox/i.test(r())},isChrome:function(){return/chrome/i.test(r())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=r();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=r();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return i.isAndroidWebView()||i.isIOSWebView()},device:t,getBrowser:function(){return i.isX5()?"X5":i.isAndroidWebView()?"Android-WebView":i.isIOSWebView()?"iOS-WebView":i.isChrome()?"Chrome":i.isFirefox()?"Firefox":i.isIpadSafari()?"iPad-Safari":i.isIOSSafari()?"iPhone-Safari":i.isSafari()?"Mac-Safari":"Unknown"}};function r(){return navigator.userAgent.toLowerCase()}function n(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(r())||[,0])[1]||void 0}function s(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=i}},t={};function i(r){var n=t[r];if(void 0!==n)return n.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,i),s.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var r={};return(()=>{"use strict";i.d(r,{default:()=>Fi});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 n=i(415),s=i.n(n),a=i(424),o=i(558),l=i.n(o);const h="__PROXY_IDENTIFIER__";const u=64e3;function d(){return!0}function c(e){return new URL(location.href).searchParams.get(e)}function f(e,t,i){const r=new URL(e);return r.searchParams.append(t,i),r.href}function g(){return Date.parse(new Date)/1e3}function p(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function v(e){return new Promise((t=>setTimeout(t,e)))}function m(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function y(e){const t=a.h.from(e),i=new a.h(e.byteLength);return t.copy(i),i}function E(){return location.protocol.startsWith("https")}function S(e,t,i){if(e.size<=t)return;const r=[...e.keys()];do{const t=r.shift();i&&i(e.get(t)),e.delete(t)}while(e.size>t)}function T(e,t){if(e.size<=t)return;const i=[...e.values()];do{e.delete(i.shift())}while(e.size>t)}function L(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function _(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const i=Number(t[0]),r=t[1]?Number(t[1]):-1;return{rangeStart:i,rangeEnd:r>=0?r+1:void 0}}function b(e){return e.split("?")[0]}function A(){let e=new Date,t=e.getHours(),i=e.getMinutes(),r=e.getSeconds(),n=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}.${n}`}function I(e){return e&&"function"==typeof e}function R(e,t,i,r,n,s){e.sendPartialBuffer(i,r,{from:n,incompletes:s})&&(r.length<i.attachments?function(e,t,i){e.addStreamListener(i,t.remotePeerId,((e,i,r,n,s)=>{r?t.sendMsgPieceAbort(n,i,!0):t.uploading&&t.send(n),s&&(t.uploading=!1)}))}(t,e,!!i.reverse):e.uploading=!1)}const P=e=>0===p(0,1)?[null,e]:[e,null];function k(e,t,i){return 1===e.length?t.length>=1&&i.length>=1?t[0].weight>i[0].weight?[t[0],e[0]]:[e[0],i[0]]:t.length>=1?[t[0],e[0]]:i.length>=1?[e[0],i[0]]:P(e[0]):[t.length>=1?t[0]:null,i.length>=1?i[0]:null]}function D(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}class w{constructor(e,t){this.target=t,this.type=e}}class C extends w{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class M extends w{constructor(e=1e3,t="",i){super("close",i),this.code=e,this.reason=t,this.wasClean=!0}}const O=()=>{if("undefined"!=typeof WebSocket)return WebSocket},x={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,i={}){this._listeners={error:[],message:[],open:[],close:[]},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._messageQueue=[],this._closeCalled=!1,this._connectLock=!1,this._shouldReconnect=!0,this._retryCount=-1,this._binaryType="blob",this._url=e,this._protocols=t,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect(),this._handleOpen=this._handleOpen.bind(this),this._handleClose=this._handleClose.bind(this),this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this)}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return 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=x.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&this._messageQueue.push(e)}}addEventListener(e,t){this._listeners[e]&&this._listeners[e].push(t)}dispatchEvent(e){const t=this._listeners[e.type];if(t)for(const i of t)this._callEventListener(e,i);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=x.reconnectionDelayGrowFactor,minReconnectionDelay:t=x.minReconnectionDelay,maxReconnectionDelay:i=x.maxReconnectionDelay}=this._options;let r=0;return this._retryCount>0&&(r=t*Math.pow(e,this._retryCount-1),r>i&&(r=i)),r}_wait(){return new Promise((e=>{setTimeout(e,this._getNextDelay())}))}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:e=x.maxRetries,connectionTimeout:t=x.connectionTimeout,WebSocket:i=O()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(r=i)||!r||2!==r.CLOSING)throw Error("No valid WebSocket class provided");var r;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new i(e,this._protocols):new i(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout((()=>this._handleTimeout()),t))})).catch((e=>{this._connectLock=!1,this._handleError(new C(Error(e.message),this))}))}}_handleTimeout(){this._handleError(new C(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new M(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=x.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 N={debug:3,info:4,warn:5,error:6};class B{constructor(e,t,i,r){this.wsAddr=`${e}?app=${t}&id=${i}&v=${r}`,this.destroyed=!1;try{this._ws=this._init()}catch(e){console.error(e)}}_init(){const e={maxRetries:3,minReconnectionDelay:p(5e3,15e3),maxReconnectionDelay:6e5,maxEnqueuedMessages:200};return new F(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const i=N[e];this._ws.send(JSON.stringify({records:[{level:i,text:`${A()}: ${t}`}]}))}sendBatch(e){const t=[];for(let i of e)t.push({level:N[i.levelKey],text:i.message});this._ws.send(JSON.stringify({records:t}))}destroy(){this._ws&&(this._ws.close(1e3),this._ws=null,this.destroyed=!0)}}const U=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}},G=(e,t,i)=>{((e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)})(e,{value:t,duration:i,startTime:Date.now()})},H={debug:0,info:1,warn:2,error:3,none:4};const V=class{constructor(e){this.logLevel=e,this.onlineDebug=!1,this.logCache=[];try{console.debug=console.log}catch(e){console.debug=console.info}"debug"!==e&&"info"!==e||(this.logLevel="error"),U("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:`${A()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,i,r,n=5e3){this.reportUrl&&(e&&this.logCache.unshift({levelKey:"info",message:e}),this.reporter=new B(this.reportUrl,t,i,r),this.reporter._ws.addEventListener("open",(()=>{this.reportUrl=void 0,this.reporter.sendBatch(this.logCache),setTimeout((()=>{this.reporter.destroy(),this.reporter=null}),n)}),{once:!0}))}_hookLogFunc(e){for(let t in H){const i=this[t];this[t]=r=>{e(t,r),i(r)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in H)H[e]<H[this.logLevel]?this[e]=d:this[e]=console[e]}get isDebugLevel(){return H[this.logLevel]<=2||this.onlineDebug}};let K;const W="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(K||(K=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),$=65536;function q(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class j extends(s()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||j.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},j.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=m(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void W((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{e.debug=!0,this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var i;!t.address||t.address.endsWith(".local")?(i="Ignoring unsupported ICE candidate.",console.warn(i)):(e.debug=!0,this.destroy(e))}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,W((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,W((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=$),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>$}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=q(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=q(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((i=>{const r=[];i.forEach((e=>{r.push(t(e))})),e(null,r)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((i=>{if(this.destroyed)return;const r=[];i.result().forEach((e=>{const i={};e.names().forEach((t=>{i[t]=e.stat(t)})),i.id=e.id,i.type=e.type,i.timestamp=e.timestamp,r.push(t(i))})),e(null,r)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,i)=>{if(this.destroyed)return;t&&(i=[]);const r={},n={},s={};let a=!1;i.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(r[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}));const o=e=>{a=!0;let t=n[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let i=r[e.remoteCandidateId];i&&(i.ip||i.address)?(this.remoteAddress=i.ip||i.address,this.remotePort=Number(i.port)):i&&i.ipAddress?(this.remoteAddress=i.ipAddress,this.remotePort=Number(i.portNumber)):"string"==typeof e.googRemoteAddress&&(i=e.googRemoteAddress.split(":"),this.remoteAddress=i[0],this.remotePort=Number(i[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(i.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(s).length&&!Object.keys(n).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>$||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()}}j.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},j.channelConfig={};const Y=j;class z{constructor(e,t,i,r,n=0,s=void 0){this.sn=e,this.segId=t,this.data=i,this.fromPeerId=r,this.level=n||0,this.ext=s}static fromSegment(e){const t=new z(e.sn,e.segId,e.data,e.fromPeerId,e.level,e.ext);return t.from=e.from,t}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var X=i(365),Q=i.n(X);class J extends(s()){static get defaultPacketSize(){return u}static get VERSION(){return"8"}constructor(e,t,i,r,n,s={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=n,this.isInitiator=r,this.options=s,this.intermediator=s.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,i),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=u,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.useBackupSignal=!1,this.gotPeersTS=0,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.incomingSignal=[],this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,i){this.remotePeerId=i,this.channelId=this.isInitiator?`${t}-${i}`:`${i}-${t}`,i&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(e.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=g(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:t,sentSignal:i,signalName:r}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${i} signalName ${r}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:i,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,i,r){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${r} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:i,seg_id:r}))))}addStreamListener(e,t,i){this.streamListeners.push({handler:i,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_initPeerChannel(){const t=new Y({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let i=!0;(this.connected||this.notFatalClosed)&&(i=!1);let r=t.message;t.debug&&(r=`${r} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,i,r)})),t.on("signal",(t=>{t.candidate&&!t.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(t),this.sentSignal=!0,this.emit(e.DC_SIGNAL,t))}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.intermediator?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,this.incomingSignal=[],clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:i}=this;if("string"==typeof t){let r=JSON.parse(t);if(!r)return void i.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(r);let n,s=r.event;switch(n=s!==e.DC_PLAYLIST&&s!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${s}`,i.debug(`datachannel receive ${n} from ${this.remotePeerId}`),s){case e.DC_HAVE:if(this.emit(r.event,r),!r.sn)return;this.config.live||(r.sn<this.startSN&&(this.startSN=r.sn),r.sn>this.endSN&&(this.endSN=r.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=g(),this.timeReceivePiece=performance.now(),this.pieceMsg=r,this._prepareForBinary(r.attachments,r.seg_id,r.sn,r.size),this.emit(r.event,r);break;case e.DC_PIECE_CANCEL:i.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(r.event,r),this.sendMsgPieceAbort("transfer canceled",r.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(r.event,r);break;case e.DC_REQUEST:this._handleRequestMsg(r);break;case e.DC_PIECE_ACK:this._handlePieceAck(r.seg_id,r.size,r.miss);break;case e.DC_STATS:this._handleStats(r);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(r);break;case e.DC_METADATA:this._handleMetadata(r);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,r)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:i.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:i.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(r.event,r.fatal||!1);break;default:this.emit(r.event,r)}}else{if(!t)return void i.error("datachannel on data is undefined!");if(!this.downloading){const r=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return i.warn(r),void this.emit(e.DC_ERROR,!1,r)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,i)=>{this.connected&&"disconnected"===t&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(e.DC_DISCONNECT))}))}sendJson(t){if(!this.remotePeerId)return!1;t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const i=JSON.stringify(t);return i.length>u?(this.logger.error("string to send is too large"),!1):this.send(i,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();t?("string"!=typeof t&&(this.bytesUploaded+=t.byteLength),this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,void this.emit(e.DC_ERROR,!1,t.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){const i=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,i)}return!1}sendMsgHave(t,i,r={}){const n=r.reverse||void 0;delete r.reverse,this.sendJson({event:n?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:i,...r})}sendPieceNotFound(t,i,r={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:i||void 0,sn:t,...r})}sendPeers(t){this.sendJson({event:e.DC_PEERS,peers:t})}sendPeersRequest(){this.sendJson({event:e.DC_GET_PEERS})}sendMsgStats(t,i={}){const r={event:e.DC_STATS,total_conns:t,...i};this.sendJson(r)}sendMsgPlaylist(t,i,r){const n=this.playlistMap.get(t);if(n&&n.seq>=r)return;const s={event:e.DC_PLAYLIST,url:t,data:i,seq:r};this.playlistMap.set(t,{data:i,seq:r}),this.sendJson(s)}sendMsgSignal(t,i,r){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:i,data:r})}sendMsgSignalReject(t,i,r,n=!1){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:i,reason:r,fatal:n})}sendMetaData(t,i,r,n,s=!1){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!Q().isMobile(),mobile_net:s,channel:this.channel,version:"2.14.3",sequential:i,peers:r,region:n})}sendPartialBuffer(e,t,i={}){if(!this.sendMsgPiece(e,i))return!1;for(let e=0;e<t.length;e++)this.send(t[e]);return!0}sendMsgPiece(e,t={}){if(!this.uploading)return this.logger.info("not uploading, cancel send buffer"),!1;this.datasToSend=[],this.bytesUploaded=0,e.ext||(e.ext={}),e.ext.from&&t.from&&t.from.length<2500&&(t.from=`${e.ext.from}-${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const i={...e,ext:t};return this.sendJson(i)}sendBuffer(t,i,r,n={}){const s=n.reverse||void 0;if(delete n.reverse,!r)return void this.logger.error("sendBuffer payload is undefined!");let a=r.byteLength,o=0,l=0;a%this.packetSize==0?l=a/this.packetSize:(l=Math.floor(a/this.packetSize)+1,o=a%this.packetSize);let h={event:e.DC_PIECE,attachments:l,seg_id:i,sn:t,level:n.level,size:a,reverse:s};if(delete n.level,!this.sendMsgPiece(h,n))return;const u=function(e,t,i,r){let n=[];if(r){let s;for(let r=0;r<i-1;r++)s=e.slice(r*t,(r+1)*t),n.push(s);s=e.slice(e.byteLength-r,e.byteLength),n.push(s)}else{let r;for(let s=0;s<i;s++)r=e.slice(s*t,(s+1)*t),n.push(r)}return n}(r,this.packetSize,l,o);this._sendBufferArray(u,s),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}requestDataById(t,i,r=!1,n={}){const s={event:e.DC_REQUEST,seg_id:t,sn:i,...n,urgent:r};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${t} in queue`),r?this.sendReqQueue.unshift(s):this.sendReqQueue.push(s)):this._realRequestData(s)}requestDataBySN(t,i=!1,r={}){const n={event:e.DC_REQUEST,sn:t,...r,urgent:i};this.downloading?(this.logger.info(`add req ${t} in queue`),i?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}_sendBufferArray(e,t=!1){const i=t?e.reverse():e;for(let e=0;e<i.length;e++)this.send(i[e])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0,this._loadedBytes=0}shouldWaitForRemain(e){return 0!==this.bufArrSize&&(0!==this.timeReceivePiece&&this.currentLoadSpeed()>=this.minRequiredSpeed(e))}close(t){t||(this.notFatalClosed=!0),this.emit(e.DC_CLOSE,t)}receiveSignal(e,t){if("answer"===e.type){if(this.gotAnswer||this.gotOffer)return;this.gotAnswer=!0}else if("offer"===e.type){if(this.gotOffer||this.gotAnswer)return;this.gotOffer=!0}this.gotSignal=!0,t&&this.incomingSignal.push(t),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:i}=t;i(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(t=!0){this.logger.info(`destroy datachannel ${this.channelId}`),clearTimeout(this.chokeTimer),clearTimeout(this.connTimeout),this._notifyDownloadListenersAbort("upstream peer is closed");let i={event:e.DC_CLOSE,fatal:t};this.sendJson(i),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:i,reverse:r}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let n=r?this.remainAttachments+1:i-this.remainAttachments;const s=0===this.remainAttachments;if(this.emit(e.DC_PIECE_DATA,this.bufSN,this.segId,t,n,s,this.pieceMsg),this.streamListeners.length>0)for(let e of this.streamListeners){const{handler:i}=e;i(this.bufSN,this.segId,!1,t,s)}if(s){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:e.DC_PIECE_ACK,seg_id:this.segId,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(r)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:i,seq:r}=e;this.playlistMap.set(t,{data:i,seq:r})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const i=this.playlistMap.get(e);return i.seq<=t||i.seq>t+2?null:i}_handleMetadata(t){const{logger:i}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,i.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const r=t.channel;if(this.channel!==r){const t=`peer channel ${r} not matched!`;return i.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){i.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:r}=this.config;if(r&&t.token!==r)return void this.emit(e.DC_ERROR,!0,`super peer token ${t.token} not matched!`)}t.region&&(this.region=t.region);switch(t.platform){case e.DC_PLAT_ANDROID:this.platform=e.DC_PLAT_ANDROID;break;case e.DC_PLAT_IOS:this.platform=e.DC_PLAT_IOS;break;case e.DC_PLAT_WEB:this.platform=e.DC_PLAT_WEB}if(this.mobile=t.mobile||!1,this.mobileNet=t.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===e.DC_PLAT_WEB||!1,this.sequential=t.sequential,i.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,i.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(e.DC_METADATA,t),t.field&&!this.config.live&&t.sequential){const{field:e}=t;if(Array.isArray(e))this._handleField(e);else for(let t in e)this._handleField(e[t])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=g();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPos=e.pos)}_handleRequestMsg(t){if(this.dataExchangeTs=g(),this.uploading)return this.logger.warn(`${this.remotePeerId} is uploading when receive request`),void this.sendPieceNotFound(t.sn,t.seg_id,{level:t.level});this.uploading=!0,this.emit(e.DC_REQUEST,t)}_handlePieceAck(t,i,r){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(i/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),r>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${r}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:i})}_prepareForBinary(e,t,i,r){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=i,this.expectedSize=r}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let i=a.h.concat(this.bufArr);const r=i.byteLength;if(r===this.expectedSize){let t=i.buffer;const r=new z(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,r,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${r}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,i=performance.now()-this.timeSendRequest;if((e||!(i<1e3))&&(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>=3&&!this.choked)){this.choked=!0;const e=30*this.miss;e<=150?(t.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,t.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*e)):t.warn(`datachannel ${this.channelId} is choked permanently`)}}get bufArrSize(){return this.downloading?this.pieceMsg.attachments-this.remainAttachments:0}loadtimeout(){const{logger:e,pieceMsg:t}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded`),this.checkIfNeedChoke(),!0}sendMsgPieceAbort(t,i,r=!1){const n=this.datasToSend.length;if(!r&&!this.uploading&&0===n)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(i,this.bytesUploaded,0),this.bytesUploaded=0;const s={event:e.DC_PIECE_ABORT,reason:`${t}, remains ${n}`};return this.sendJson(s)}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 Z=J,ee={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 te={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class ie extends(s()){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 ee)if(self[t]){e=ee[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,i=()=>{this.curTsUri&&function(e,t,i,r=2e3,n=!1){const s=new XMLHttpRequest;let a=e;return n&&(a=f(e,h,!0)),t=t||"bytes=0-0",new Promise(((n,o)=>{s.open("GET",a,!0),s.responseType="arraybuffer",s.timeout=r,s.onreadystatechange=e=>{if(4===s.readyState){const e=s.status;206===e||200===e&&t?n(s.response):o(`status ${e} url ${a} range ${t}`)}},s.onerror=e=>{o("request error")},s.ontimeout=e=>{o("timeout")},s.setRequestHeader("Range",t),i&&i(s,e),s.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((r=>{e.httpRangeSupported=!1,t.warn(r),this.rangeRequestTimer=setTimeout(i,6e4)})).finally((()=>{t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(i,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 V(e.logLevel);return e.logger=this.logger=t,t}getExtraForStats(){return{}}getExtraForPeersRequest(){const e={};return e.num_want=this._getNumWant(),e}_getNumWant(){const{tracker:e}=this;if(!e.scheduler)return;const t=e.scheduler.peersNum;return t>0&&e.maxConnsActive-t>0?e.maxConnsActive-t:void 0}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return I(t)?(i,r)=>`${e}-${t(i,r)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,i=`wss://${self.atob(function(e){let t="c2lnbmFsY2xvdWQuc3dhcm1jbG91ZC5vcmc=";switch(e){case"hk":t="c2lnbmFsLnN3YXJtY2xvdWQub3Jn";break;case"us":t="b3BlbnNpZ25hbC5zd2FybWNsb3VkLm9yZw==";break;case"cn":t="Z3ouc3dhcm1jbG91ZC5uZXQ="}return t}(t.trackerZone))}`;t.signalConfig&&(t.wsSignalerAddr=t.signalConfig);const{wsSignalerAddr:r}=t;if(r){let n;"object"==typeof r?(r.main||(r.main=i),n=r.main):"string"==typeof r&&(n=r,t.wsSignalerAddr={main:n}),n===i&&(n=void 0),n&&!t.wsSignalerAddr.backup&&(e=l().parseURL(n).netLoc.substring(2))}else t.wsSignalerAddr={main:i,byDefault:!0};return e}get commonBrowserInfo(){const e=Q().getPlatform(),t=Q().getNetType()||"wifi";this.netType=t;const{main:i,backup:r,byDefault:n}=this.config.wsSignalerAddr||{};return{signal:i,custom_signal:!n||void 0,signal2:r,device:e,netType:t,player:this.playerName}}get isMobileNet(){return"wifi"!==this.netType&&"ethernet"!==this.netType}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",i=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,i)};e?self.removeEventListener(t,i):self.addEventListener(t,i)}destroy(){clearTimeout(this.rangeRequestTimer),this.disableP2P(!0),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return ie.version}static isSupported(){const e=m();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,i){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${i}`);let r=4;return t<=2?r=1.5:t<=3?r=2:t<=4?r=2.5:t<=5?r=3:t<=6&&(r=3.5),r}emitEvent(e,...t){this.emit(e,...t);const i=te[e];i&&I(this.config[i])&&this.config[i](...t)}}ie.version="2.14.3",ie.protocolVersion=Z.VERSION;const re=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 se(e,t){let i;if(e&&("string"==typeof e?(i=document.querySelector(e),ae(i)||(i=function(e){const t=document.getElementById(e);if(ae(t))return t;if(!t)return null;const i=t.getElementsByTagName("*");for(let e=0;e<i.length;e++)if(ae(i[e]))return i[e];return null}(e))):e instanceof HTMLMediaElement&&(i=e)),!i){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?i=e[0]:(t&&(i=e.find((e=>e.src===t))),i||(i=e.find((e=>e.currentTime>0))))}return i}function ae(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function oe(e,t,i,r=0,n=0){const s=u;let a=r,o=n||i-1;const l=Math.floor(i/s),h=i%s>0?l+1:l;if(e>=0&&(a+=(e+1)*s),t>=0&&t<h){o-=i%s+(h-t-1)*s}return{rangeStart:a,rangeEnd:o+1}}function le(e,t){return`${e}-${t}`}function he(e,t,i,r){let n=i.split("?")[0];return n.startsWith("http")&&(n=n.split("://")[1]),r?`${n}|${r}`:`${n}`}function ue(e,t){return"number"!=typeof t&&(t=Number(t)),`${t}-${e}`}let de={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,i){},getPeerId:function(e){},getPeersInfo:function(e){}};const ce={...de,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},fe=1e3;function ge(e){const t=new Promise(((t,i)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>i(e.error)})),i=(r=fe,n="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(n)}),r))));var r,n;return Promise.race([t,i])}const pe={};async function ve(e,t,i=!0){const r=pe[e]||{};r.promise||(r.promise=new Promise((e=>r.resolve=e)),pe[e]=r,ye(e,t,r.resolve,i));const n=await r.promise;return delete r.promise,n}const me={};async function ye(e,t,i,r){if(!me[e]){const r=indexedDB.open(e);return r.onupgradeneeded=()=>{const e=r.result;t.forEach((t=>{e.createObjectStore(t)}))},void i(me[e]=await ge(r))}if(r)try{t.forEach((t=>{me[e].transaction(t)})),i(me[e])}catch(n){console.error(`Could not open a transaction on "${e}" due to ${n.name} (${n.message}). Trying to reopen the connection...`),delete me[e],ye(e,t,i,r)}else i(me[e])}let Ee;function Se(){return Ee||(Ee=createStore("keyval-store","keyval")),Ee}function Te(e,t=Se()){return t("readonly",(t=>ge(t.get(e))))}function Le(e,t,i=Se()){return i("readwrite",(i=>(i.put(t,e),ge(i.transaction))))}function _e(e,t=Se()){return t("readwrite",(t=>(t.delete(e),ge(t.transaction))))}function be(e=Se()){return e("readwrite",(e=>(e.clear(),ge(e.transaction))))}function Ae(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},ge(e.transaction)}const Ie="size";class Re extends(s()){constructor(e,t){super(),this.name="SegmentStore",this.logger=t.logger,this.logger.info(`use ${this.name}`),this.engine=e,this.channel=e.channel;const i=e.browserInfo.device;this.isPC=i===Q().device.PC_WEB||i===Q().device.PC_NATIVE,this.maxBufSize=this.isPC?t.diskCacheLimit.pc:t.diskCacheLimit.mobile,this.overflowed=!1,this.countErrors=0,this.isCleared=!0,this.destroyed=!1}async setupStore(){if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate(),t=Math.floor(e.quota-e.usage);t<this.maxBufSize&&(this.maxBufSize=t-104857600)}return new Promise((async(e,t)=>{if(this.isPC&&this.maxBufSize<419430400||!this.isPC&&this.maxBufSize<104857600)return void t("disk storage not enough");const i=this.stores;let r;try{r=function(e,t){let i=ve(e,t);return t.map((r=>(n,s)=>i.then((a=>{try{const e=a.transaction(r,n).objectStore(r);return s(e)}catch(a){i=ve(e,t),i.then((e=>s(e.transaction(r,n).objectStore(r))))}}))))}(this.channel,i)}catch(e){return void t(e)}this._createStores(r),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return Le(Ie,0,this.metaStore)}currBufSize(){return new Promise((async(t,i)=>{try{const r=await Te(Ie,this.metaStore);if(isNaN(r))return this.engine.emit(e.BM_FATAL_ERROR),void i("size is NaN");t(r)}catch(e){i(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:i}=this;if(L(t.data))return new Promise((r=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),this.countErrors=0,r()})).catch((e=>{this._handleFataError(),e&&(i.warn(`putSeg ${e}`),("QuotaExceededError"===e.name||e.inner&&"QuotaExceededError"===e.inner.name)&&this.currBufSize().then((e=>{this._trimDisk(e,!0)})).catch((e=>{this.logger.error(`trimDisk ${e}`)}))),r()}))}));i.error(`putSeg ${t.segId} is not buffer`)}_handleFataError(){this.countErrors++,this.countErrors>=3&&(this.engine.emit(e.BM_FATAL_ERROR),this.countErrors=0)}_decreaseBufSize(e){this.currBufSize().then((t=>{t&&Le(Ie,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(e){this.destroyed||this.currBufSize().then((t=>{Le(Ie,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){be(this.segmentsStore),e?this._initMetaStore():be(this.metaStore),this.overflowed=!1}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const Pe=Re;const ke=class extends Pe{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 Te(e,this.id2SnStore)}catch(e){return Promise.resolve(!1)}return new Promise((i=>{void 0!==t?Te(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?i(!0):i(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),i(!1)})):i(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let i;try{i=await Te(e,this.id2SnStore)}catch(e){return null}return new Promise((r=>{void 0!==i?Te(i,this.segmentsStore).then((i=>{if(this.countErrors=0,i&&i.length>0){const n=i.find((t=>t.segId===e));if(!n)return void r(null);if(!L(n.data))return t.error(`getSegById ${n.sn} is not buffer`),void r(null);r(z.fromSegment(n))}else r(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),r(null)})):r(null)}))}getSegIdBySN(e){return new Promise((t=>{Te(e,this.segmentsStore).then((e=>{e&&e.length>0?t(e[0].segId):t(null)})).catch((e=>{this.logger.warn(`getSegIdBySN ${e}`),t(null)}))}))}_addSeg(e){const{segId:t,sn:i,size:r}=e;return Le(t,i,this.id2SnStore),new Promise(((n,s)=>{Te(i,this.segmentsStore).then((a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(this._segmentToCache(e)),Le(i,a,this.segmentsStore).then((()=>{this._increaseBufSize(r),n(e)})).catch((e=>{s(e)}))):n(e):Le(i,[this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(r),n(e)})).catch((e=>{s(e)}))})).catch((e=>{s(e)}))}))}async _trimDisk(t,i=!1){if(this.isCleared||this.destroyed)return;let r=this.maxBufSize;const{logger:n}=this;i&&(r=t-104857600,r<0&&(r=0)),t<r||(n.warn(`_trimDisk currentSize ${t} upBound ${r}`),function(e=Se()){return e("readonly",(e=>{if(e.getAllKeys)return ge(e.getAllKeys());const t=[];return Ae(e,(e=>t.push(e.key))).then((()=>t))}))}(this.segmentsStore).then((async i=>{const s=i.sort(((e,t)=>e-t));let a=0;do{if(a++>10){n.warn("too much loops in SegmentStore");break}const i=s.shift();if(void 0===i){n.warn("lastSN not found");continue}if(i>=this.loadingSN){n.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const r=s[0],o=await Te(i,this.segmentsStore);if(!o){n.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),_e(i,this.segmentsStore).then((()=>{this._decreaseBufSize(parseInt(l))})),o.forEach((t=>{_e(t.segId,this.id2SnStore),n.info(`pop seg ${t.segId} size ${t.data.byteLength}`),this.emit(e.BM_LOST,{sn:i,segId:t.segId,next:r,level:t.level})})),t-=l,n.info(`pop sn ${i} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=r)})))}_segmentToCache(e){return{data:e.data,level:e.level,segId:e.segId,sn:e.sn}}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}be(this.id2SnStore).catch((e=>{}))}};class De extends(s()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const i=e.browserInfo.device;if(this.maxBufSize=i===Q().device.PC_WEB||i===Q().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)),L(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 we=De;const Ce=class extends we{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,i)=>{const r=this.id2Sn.get(e);this._segPool.has(r)?t(this._segPool.get(r).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((i,r)=>{if(!this._segPool.has(t))return void i(null);i(this._segPool.get(t).find((t=>t.segId===e)))}))}getSegIdBySN(e){return new Promise(((t,i)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}_addSeg(t){const{logger:i}=this,{segId:r,sn:n,size:s}=t;if(this.id2Sn.set(r,n),this._segPool.has(n)){this._segPool.get(n).push(t)}else this._segPool.set(n,[t]);this._currBufSize+=parseInt(s);const a=this._segPool.size;if(this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t),this._currBufSize<this.maxBufSize||a<=5)return;let o=Array.from(this._segPool.keys());this.isLive||(o=o.sort(((e,t)=>e-t)));let l=0;do{if(l++>10){i.error("too much loops in SegmentCache");break}const t=o.shift();if(void 0===t){i.error("lastSN not found");continue}const r=o[0],n=this._segPool.get(t);if(!n){i.error("lastSeg not found");continue}let s=0;n.forEach((e=>{s+=e.size})),this._currBufSize-=parseInt(s),this._segPool.delete(t),n.forEach((i=>{this.id2Sn.delete(i.segId),this.emit(e.BM_LOST,{sn:t,segId:i.segId,next:r,level:i.level})})),i.info(`pop sn ${t} size ${s} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>5)}clear(){super.clear(),this.id2Sn.clear()}};var Me=i(832),Oe=i.n(Me);function xe(e,t){for(const i in t)Object.defineProperty(e,i,{value:t[i],enumerable:!0,configurable:!0});return e}const Fe=function(e,t,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof t&&(i=t,t=void 0),null!=t&&(i.code=t);try{return xe(e,i)}catch(t){i.message=e.message,i.stack=e.stack;const r=function(){};return r.prototype=Object.create(Object.getPrototypeOf(e)),xe(new r,i)}};class Ne{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 Be="SW_GEOIP_KEY",Ue=2592e5,Ge=432e5,He="TRACKER_EXPT",Ve="IPAPI_ERROR",Ke="uY2R",We="LmNv",$e="uYnll",qe="bQ==",je="Z3o",Ye="aGsuc3d",ze="hcm1j",Xe="bG91ZC",Qe="5uZXQ=",Je=Symbol("httpDownloaded"),Ze=Symbol("p2pDownloaded"),et=Symbol("p2pUploaded");class tt extends(s()){constructor(e,t,i,r,n){let s;super(),this.config=e.config;let a=this.config.announceLocation;switch(this.config.trackerZone&&(a=this.config.trackerZone),a){case"hk":s=Ye+ze+Xe+Qe;break;case"us":s="dXMuaGR0dmNsb3VkLmNvbQ==";break;case"cn":s=je+Ke+$e+We+qe;break;default:s="ZXUuaGR0dmNsb3VkLmNvbQ=="}this.engine=e,this.key=t||void 0,this.baseUrl=r||`https://${self.atob(s)}/v1`,this.channelId=self.btoa(i),this.timestamp=g(),this.health=new Ne;const o=l().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,""),function(e,t){function i(e,t,i,r,n){return h(i-219,n)}var r,n,s=e();function a(e,t,i,r,n){return h(n- -994,e)}function o(e,t,i,r,n){return h(r-233,t)}function l(e,t,i,r,n){return h(n-305,i)}for(;;)try{if(156690===-parseInt(o(0,246,0,247))/1*(-parseInt(o(0,243,0,248))/2)+-parseInt(o(0,238,0,245))/3+parseInt(a(-1e3,0,0,0,-989))/4*(-parseInt(i(0,0,225,0,216))/5)+-parseInt((r=-180,n=-173,h(n- -181,r)))/6*(parseInt(l(0,0,324,0,324))/7)+-parseInt(a(-991,0,0,0,-990))/8*(parseInt(l(0,0,313,0,307))/9)+-parseInt(l(0,0,310,0,305))/10+-parseInt(a(-968,0,0,0,-974))/11*(-parseInt(i(0,0,226,0,216))/12))break;s.push(s.shift())}catch(e){s.push(s.shift())}}(d);function h(e,t){var i=d();return(h=function(e,t){return i[e-=0]})(e,t)}const u=function(e,t,i,r,n,s){let a=location.hostname;a===h(-922- -923,-915)&&s&&(a=s+"."+a);return 13,Oe()(a+"2.14.3"+i+r+n,e).substr(0,8)}(this.timestamp,0,this.announce,this.channelId,n.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=!(!n.bundle||!window.electron&&!navigator.userAgent.toLowerCase().includes("electron")),this.announceInfo={...n,channel:this.channelId,ts:this.timestamp,version:"2.14.3",v:u,announce:this.announce,k:st(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[Je]=0,this[Ze]=0,this[et]=0,this.speed=0,this.offline=!1,this.errsBufStalled=0,this.mediaRequests=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,i)=>{if((e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return!(!e.duration||!e.startTime)&&Date.now()-e.startTime<e.duration}catch(e){return!1}})(Be)){const i=U(Be);e.info("found local geo data"),t(i)}else fetch(self.atob("aHR0cHM6Ly9wcm8uaXAtYXBpLmNvbS9qc29uP2ZpZWxkcz0yMTgxODI2JmtleT1YT3BpYW5zUmdZeEdUaG8=")).then((e=>e.json())).then((e=>{if("success"!==e.status){const t=new Error(`preflight status ${e.status}`);throw Fe(t,Ve)}{const i=e.mobile?Ge:Ue;G(Be,e,i),t(e)}})).catch((e=>{i(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(Fe(new Error("request timeout"),Ve))}),600)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(t.code!==He){const t=U(Be);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:i,isp:r,as:n,mobile:s,countryCode:a,continentCode:o}=e;s&&(this.announceInfo.netType="cellular");const l=n.split(" ")[0].substr(2);this.announceInfo={...this.announceInfo,lat:t,lon:i,isp:r,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,i)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>{if(!e.ok){const t=e.status>=500&&e.status<600;throw 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 i=e.data;if(i.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:i}=e.data;throw Fe(new Error(i),He,{retry:t>=5e3})}if(i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),i.min_conns||(i.min_conns=8),(!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval&&i.peers){if(this.peerId=this.id=i.id,i.report_interval<20&&(i.report_interval=20),this.btStats(i.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,!this.announceInfo.asn&&i.asn){const{country:e,asn:t,mobile:r,isp:n,lat:s,lon:a}=i;this.announceInfo={...this.announceInfo,country:e,asn:t},G(Be,{countryCode:e,as:`AS${t}`,mobile:r,isp:n,lat:s,lon:a,status:"success"},r?Ge:Ue)}t(i)}else this.engine&&(this.engine.p2pEnabled=!1)})).catch((t=>{e.error(`btAnnounce error ${t}`);const r=t.code||He,n=!t.code||t.retry;i(Fe(t,r,{retry:n}))}))}))}btStats(e=10){this.heartbeater=setInterval((()=>{this.postStats()}),1e3*e)}postStatsWithBeacon(){if(this.offline)return;this.offline=!0;let e={off:!0};this.statsRequesting||(e={...e,...this._makeStatsBody()}),this.statsURL&&navigator.sendBeacon&&navigator.sendBeacon(this.statsURL,JSON.stringify(e))}postStats(){const{logger:t}=this.engine;this.statsRequesting=!0,fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.statsRequesting=!1,this.reportFails=0,e.text()))).then((i=>{let r;if(r=i?JSON.parse(i):{ret:0,data:{}},-1===r.ret)clearInterval(this.heartbeater),t.error(`${r.data.msg} code ${r.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:i=0,failConns:r=0,rebuffers:n=0,requests:s=0,errsInternalExpt:a=0}=this.lastStats||{};this[Je]>=e&&(this[Je]-=e),this[Ze]>=t&&(this[Ze]-=t),this[et]>=i&&(this[et]-=i),this.failConns>=r&&(this.failConns-=r),this.errsBufStalled>=n&&(this.errsBufStalled-=n),this.mediaRequests>=s&&(this.mediaRequests-=s),this.errsInternalExpt>=a&&(this.errsInternalExpt-=a),this.exptMsg&&(this.exptMsg=void 0)}})).catch((e=>{t.error(`btStats error ${e}`),this.statsRequesting=!1,this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e,t=!1){const{logger:i}=this.engine,{asn:r,country:n}=this.announceInfo;let s={exclusions:e,asn:r,country:n,ratio:this.health.healthRatio,urgent:t||void 0},a={};return this.engine.getExtraForPeersRequest&&(a=this.engine.getExtraForPeersRequest()),s=Object.assign({},s,a),new Promise(((e,t)=>{this.reportFails>=3?t(new Error("reportFails >= 3")):fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(s)}).then((e=>e.json())).then((i=>{-1===i.ret?t(i.data.msg):e(i.data)})).catch((e=>{i.error(`btGetPeers error ${e}`),t(e)})).finally((()=>{this.health.resetTraffic()}))}))}increFailConns(){this.failConns++}increRebuffers(){this.engine.emitEvent("bufferStalled"),this.errsBufStalled++}increMediaRequests(){this.mediaRequests++,this.engine.emit(e.MEDIA_REBUFFER,this.errsBufStalled>=2)}reportFlow(e){const t=Math.round(e/1024);this.engine.emitEvent("httpDownloaded",t),this[Je]+=t,this.totalHTTPDownloaded+=t,this.health.recordHttp(t),this._emitStats()}reportDCTraffic(e,t){const i=Math.round(e/1024);this[Ze]+=i,this.totalP2PDownloaded+=i,this.health.recordP2p(i),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",i,this.speed),this._emitStats()}reportUploaded(e=0){const t=Math.round(e/1024);this.engine.emitEvent("p2pUploaded",t),this.totalP2PUploaded+=t,this.health.recordShare(t),this[et]+=t,this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),this.removeAllListeners(),clearInterval(this.heartbeater)}_emitStats(){const{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:i}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:i,p2pDownloadSpeed:this.speed});const{getStats:r}=this.config;I(r)&&r(t,i,e,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let i={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,rebuffers:this.errsBufStalled||void 0,requests:this.mediaRequests||void 0,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[Je])||0,p2p:Math.round(this[Ze])||0,share:Math.round(this[et])||0,asn:e,country:t},r={};this.engine.getExtraForStats&&(r=this.engine.getExtraForStats()),i=Object.assign({},i,r),this.lastStats=JSON.parse(JSON.stringify(i)),Object.keys(i).forEach((e=>{0===i[e]&&delete i[e]}));const{logger:n}=this.engine;return n.isDebugLevel&&n.info(`report ${JSON.stringify(i)}`),this.exptMsg&&(i.exptMsg="2.14.3 "+this.exptMsg),i}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":st(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const it=tt;function rt(e,t){const i=nt();return(rt=function(e,t){return i[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 st(e){if(!e)return;const t=rt(-822- -830,-826);let i="".split("").reverse().join("");const r=t.length;for(let n=0;n<e.length;n++){const s=e.charCodeAt(n)^t.charCodeAt(n%r);i+=String.fromCharCode(s)}return self.btoa(i)}!function(e,t){const i=e();function r(e,t,i,r,n){return rt(e-92,n)}function n(e,t,i,r,n){return rt(n-930,i)}for(;;)try{if(377468===parseInt(n(0,0,944,0,939))/1*(parseInt(n(0,0,936,0,930))/2)+parseInt(n(0,0,929,0,935))/3+parseInt(n(0,0,939,0,941))/4+-parseInt((s=-995,a=-995,rt(s- -999,a)))/5+parseInt(r(94,0,0,0,91))/6+-parseInt(r(93,0,0,0,92))/7+-parseInt(r(102,0,0,0,107))/8)break;i.push(i.shift())}catch(e){i.push(i.shift())}var s,a}(nt);class at extends(s()){constructor(e,t){super(),this.logger=e,t.startsWith("wss")?this.addr=t.replace("wss","https"):t.startsWith("ws")&&(this.addr=t.replace("ws","http")),this.connected=!1,this.retryCount=0,this.closed=!1,this.msgQueue=[],this.posting=!1,this.pollingTs=0}start(){this.closed=!1,this._hello((()=>{this._longPolling()}))}_hello(e){fetch(this.addr+"&hello",{method:"POST"}).then((e=>{if(!e.ok)throw new Error("hello response was not ok");return e.json()})).then((t=>{this.connected=!0,e(),this.onopen&&this.onopen(t.ver)})).catch((e=>{this.closed=!0,this.onerror&&this.onerror(e)}))}send(e){this.msgQueue.push(e),this.posting||this._realSend([...this.msgQueue])}_realSend(e){0!==e.length&&(this.posting=!0,this.msgQueue=[],fetch(this.addr,{method:"POST",body:JSON.stringify(e)}).then((()=>{this.posting=!1,this.msgQueue.length>0&&this._realSend([...this.msgQueue])})).catch((e=>{this.logger.error(e),this.posting=!1})))}close(){this.connected&&(this.closed=!0,this.connected=!1,this.abortController&&(this.abortController.abort(),this.abortController=null),this.onclose&&this.onclose())}destroy(){this.close(),this.removeAllListeners()}_longPolling(){if(this.closed)return;this.pollingTs=g(),this.abortController=new AbortController;const e=this.abortController.signal;fetch(this.addr,{signal:e}).then((e=>{if(!e.ok)throw new Error("polling response was not ok");return e.text()})).then((async e=>{e&&this.onmessage&&this.onmessage(JSON.parse(e)),this.retryCount=0;const t=g()-this.pollingTs;JSON.stringify(e)===JSON.stringify(this.lastData)&&t<10&&(this.logger.warn(`wait ${10-t}s for next polling`),await v(1e3*(10-t))),this.lastData=e,this._longPolling()})).catch((e=>{this.connected&&(this.retryCount<=3?(this.retryCount++,this._longPolling()):(this.connected=!1,this.onerror&&this.onerror(e)))}))}}const ot=class{constructor(e,t,i,r="main"){this.logger=e,this.config=t,this.wsAddr=i,this.serverVersion=0,this.pingInterval=95e3,this.name=r,this.normalClosed=!1,this.lastSendTs=performance.now(),this.pollingClient=new at(e,i);try{this._ws=this._init()}catch(t){e.error(t),this._startPolling()}}get batchSupported(){return this.serverVersion>=50}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:p(15e3,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20,connectionTimeout:7e3};let t=new 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 i=JSON.stringify(e);t.push(i)},t.addEventListener("message",(e=>{let t=e.data;const i=JSON.parse(t),r=i.action;if("pong"!==r){if("ver"!==r)return"close"===r?(this.logger.warn(`server close signal ${this.name} reason ${i.reason}`),void this.close()):void(this.onmessage&&this.onmessage(i,this.name));this.serverVersion=i.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),e.code>=5e3||e.code<4e3?(this.onclose&&this.onclose(),this._stopPing()):this.close()})),t.addEventListener("error",(e=>{this._stopPing(),this.onerror&&this.onerror(e),this._startPolling()})),t}forcePolling(){this.pollingClient.connected||(this.close(),this.pollingClient=new at(this.logger,this.wsAddr),this._startPolling())}_startPolling(){this.pollingClient.connected||(this.logger.info(`${this.name} start polling`),this.pollingClient.start(),this._setupPolling(this.pollingClient))}sendDebug(e,t,i){this._send({action:"debug",details:t,ping:i||void 0,to:e})}sendSignal(e,t){const i={action:"signal",to:e,data:t};this._send(i)}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let i of t)this.sendSignal(e,i)}sendReject(e,t,i){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const r={action:"reject",to:e,reason:t,fatal:i};this._send(r)}_send(e){this.pollingClient.connected?this.pollingClient.send(e):this._ws&&this._ws.send(e)}_startPing(e){this.connected&&(this.pingTimer=setTimeout((()=>{const e=95e3-(performance.now()-this.lastSendTs);if(e>=0)return this._startPing(e);const t={action:"ping"};this._ws&&this._ws.push(JSON.stringify(t)),this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),15e3),this._startPing(this.pingInterval)}),e))}_stopPing(){clearTimeout(this.pingTimer),clearTimeout(this.pongTimer)}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3)})(),this.pollingClient.close(),this.normalClosed=!0}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.pollingClient.destroy()}get connected(){return!!this.pollingClient.connected||this._connected}get _connected(){return!!this._ws&&this._ws.readyState===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)}}},lt=class{constructor(e,t,i,r){this.logger=e,this.config=t,this.mainAddr=i,this.backupAddr=r,this.mainWS=this._init(i),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(r,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let i=new ot(this.logger,this.config,e,t);return i.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},i.onmessage=e=>{this.onmessage&&this.onmessage(e,i.name)},i.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},i.onerror=e=>{this.onerror&&this.onerror(e)},i}sendSignalBatch(e,t,i){if(i){const r=this._getWSByName(i);r&&r.sendSignalBatch(e,t)}else this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected&&this.backupWS.sendSignalBatch(e,t)}sendSignal(e,t,i){this.sendSignalBatch(e,[t],i)}sendReject(e,t,i,r){if(r){const n=this._getWSByName(r);if(n)return void n.sendReject(e,t,i)}this.mainConnected?this.mainWS.sendReject(e,t,i):this.backupConnected?this.backupWS.sendReject(e,t,i):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,i){this.mainConnected&&this.mainWS.sendDebug(e,t,i)}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close(),this.normalClosed=!0}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(e){this.mainWS&&"backup"!==e&&this.mainWS.reconnect(),this.backupWS&&"main"!==e&&this.backupWS.reconnect()}forcePolling(e){this.mainWS&&"backup"!==e&&this.mainWS.forcePolling(),this.backupWS&&"main"!==e&&this.backupWS.forcePolling()}destroy(){this.close(),clearTimeout(this.backupTimer),this.mainWS=null,this.backupWS=null,this.destroyed=!0}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}};const ht=function(e,t,i=40){var r=null,n=!1,s=i;return function(i=!1){if(i)return clearTimeout(r),void(n=!1);n||(n=!0,r=setTimeout((function(){e.call(t,s),n=!1,r=null}),1e3*s),s*=1.1)}};class ut{constructor(e,t,i=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=i,this.pool=[],t.ICEPreflight&&this.reset(),this.trickle=!1}reset(){this.destroy();for(let e=0;e<this.poolSize;e++)this.pool.push(this._createPeer())}_createPeer(){return new Z(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 dt=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,i=0,r="";for(const n of e){if("="===n)break;const e=this.CHARSET.indexOf(n);for(t=t<<this.BITS_PER_BASE64_CHAR|e,i+=this.BITS_PER_BASE64_CHAR;i>=this.BITS_PER_BYTE;){i-=this.BITS_PER_BYTE;r+=(t>>i&(1<<this.BITS_PER_BYTE)-1).toString(16).padStart(2,"0").toUpperCase()}}let n="";for(let e=0;e<r.length;e++)n+=r[e],e%2==1&&e!==r.length-1&&(n+=":");return n}},ct="typ host",ft="generation 0",gt="network-cost",pt="rport",vt="0.0.0.0",mt={V:"v=",O:"o=",S:"s=",C:"c=",A:"a=",M:"m=",T:"t="},yt={U:"ice-ufrag:",P:"ice-pwd:",F:"fingerprint:",C:"candidate:",S:"sctp-port:",M:"max-message-size:"},Et={1:"sha-1",2:"sha-224",3:"sha-256",4:"sha-384",5:"sha-512",6:"md5",7:"md2",8:"token"},St={P:`${ct} ${ft} ${gt} 999`,W:`${pt} 0 ${ft} ${gt} 999`,H:ct,S:"typ srflx",R:pt,A:"raddr",V:vt,F:"ufrag",G:`${pt} 0 ${ft}`,N:gt,E:"network-id",C:"tcptype active",Q:`${ft}`,U:"udp",T:"tcp"},Tt={P:"application",U:"UDP/DTLS/SCTP",S:"DTLS/SCTP",D:"webrtc-datachannel"},Lt={4:"IP4",6:"IP6"},_t={0:vt},bt=e=>(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in St&&(e=St[e]),e))).join(" "));function At(e,t){let i=e.split("~"),r=[];i=i.map((e=>{let t=e.slice(0,1),i=e.slice(1);if(t in mt&&(t=mt[t]),"a="===t){let e=i.slice(0,1);const t=i.slice(1);e in yt&&(e=yt[e],i=e+t)}return t+i})),r.push("v=0"),r.push("s=-"),r.push("t=0 0"),r.push("a=msid-semantic: WMS");let n=0;i.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),i=[];i.push("-");const n=t.shift();if(n&&i.push(n),0===t.length)i.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&i.push(e),0===t.length)i.push("IN IP4 127.0.0.1");else{i.push("IN");const e=t.shift();e&&i.push(e);const r=t.shift();r&&i.push(r)}}r.splice(1,0,`o=${i.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(It,(e=>Tt[e]))}(e),r.push(e),r.push("a=setup:"+(t?"actpass":"active")),r.push(`a=mid:${n}`),void n++;if(e.startsWith("a=candidate:"))return e=bt(e),void r.push(e);if(e.startsWith("a=fingerprint:")){let[t,i]=e.slice(14).split(" ");return t in Et&&(t=Et[t]),i=dt.decode(i),void r.push(`a=fingerprint:${t} ${i}`)}if(e.startsWith("c=")){let[t,i]=e.slice(2).split(" ");return t in Lt&&(t=Lt[t]),i in _t&&(i=_t[i]),void r.push(`c=IN ${t} ${i}`)}"I"!==e?"Z"!==e?"B"!==e?r.push(e):r.push("a=sendrecv"):r.push("a=ice-options:ice2,trickle"):r.push("a=ice-options:trickle")}}));const s=r.length-1;return r.splice(s,0,`a=group:BUNDLE ${Array.from(Array(n).keys()).join(" ")}`),r.join("\r\n")}const It=new RegExp(Object.keys(Tt).join("|"),"g");class Rt extends(s()){constructor(e,t,i,r){super(),this.engine=e,this.logger=e.logger,this.config=r,this.connected=!1,this.scheduler=i,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set;const n=Q().isMobile();this.peerPool=new ut(e,r,15),this.signalerWs=null,this.fetcher=t,this.peers=[],this.requestPeersQueue=[],this.minConns=5,this.stuns=[],this.requestMorePeers=ht(this._requestMorePeers,this,p(35,45)),this.maxConns=n?15:22,this.maxConnsActive=n?10:13,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.requestPeersWaitCount=0,this.gotSignalFails={main:0,backup:0,limit:5},this.fuseRate=-1,this.overloaded=!1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:t,config:i,fetcher:r}=this,{btAnnounce:n,btAnnouncePreflight:s}=r,{wsSignalerAddr:a,wifiOnly:o,geoIpPreflight:l}=i;(l?s:n).call(r).then((e=>{const{scheduler:i}=this;if(!i)return;t.peerId=this.peerId=e.id,this.minConns=e.min_conns,i.minConns=this.minConns;const n=e.peers;i.notifyPeersLoaded(n.length),n.length>this.gotSignalFails.limit&&(this.gotSignalFails.limit=n.length),t.netType=r.announceInfo.netType,(e.wifi_only||o)&&t.isMobileNet&&(i.downloadOnly=!0,this.logger.info("downloadOnly mode"));const s=a.main;let l=a.backup;function h(e,t){var i=u();return(h=function(e,t){return i[e-=0]})(e,t)}function u(){var e=["IHmzPt4745802".split("").reverse().join(""),"fqbpvJ65672".split("").reverse().join(""),"peerId","evitcAsnnoCxam".split("").reverse().join(""),"0r^EeI@*KS".split("").reverse().join(""),"yGChQi82100203".split("").reverse().join(""),"dIlennahc".split("").reverse().join(""),"qrZmAF0973735".split("").reverse().join(""),"qNTzkD6562665".split("").reverse().join(""),"timestamp","HaovMZ5303011".split("").reverse().join(""),"blnwIB1433257".split("").reverse().join(""),"39zAjEpC","substring"];return(u=function(){return e})()}var d,c;e.signal&&!e.signal2&&(l=void 0),this.signalerWs=this._initSignalerWs(e.signal||s,e.signal2||l,e.token,e.token2),0===n.length?this.requestMorePeers():this.peers=this._filterPeers(n),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 B(e.log_url,this.fetcher.key||location.hostname,this.peerId,"2.14.3"),this.logger.setUploader(this.logUploader))),t.onTrackerResume&&t.onTrackerResume(e),e.fuse_rate&&(this.fuseRate=e.fuse_rate),e.overload&&(this.overloaded=!0,this.logger.warn("server overloaded, degrade signaling")),this.logger.info(`announce request response ${JSON.stringify(e,null,2)}`),function(e,t){function i(e,t,i,r,n){return h(t- -94,n)}var r=e();function n(e,t,i,r,n){return h(t-586,i)}function s(e,t,i,r,n){return h(r-742,n)}for(;;)try{if(595581===-parseInt(i(0,-83,0,0,-88))/1+-parseInt(n(0,587,588))/2+parseInt(n(0,599,592))/3*(-parseInt(n(0,588,591))/4)+parseInt(i(0,-86,0,0,-83))/5+-parseInt(s(0,0,0,751,751))/6+-parseInt(s(0,0,0,754,760))/7+parseInt(h(403-397,399))/8)break;r.push(r.shift())}catch(e){r.push(r.shift())}}(u),e.v!==Oe()(r.channelId+this.peerId+r.timestamp+(d=701,c=702,h(d-696,c)),"2.14.3").substring(0,8)&&(this.maxConnsActive=1)})).catch((i=>{if(this.scheduler&&("TRACKER_EXPT"===i.code&&t.emitEvent(e.EXCEPTION,i),this.scheduler.notifyPeersLoaded(0),i.retry)){const e=p(15e3,4e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.postStatsWithBeacon(),this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.peerPool.destroy(),this.peerPool=null,this.failedDCMap.clear(),this.notFoundDCSet.clear(),this.logUploader&&(this.logUploader.destroy(),this.logUploader=null),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer),clearTimeout(this.requestPeersTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}isPeerConnectedOrFailed(e){return!e||(this.DCMap.has(e)||this.failedDCMap.has(e)||e===this.peerId)}_filterPeers(e){const t=[];return e.filter((e=>!this.isPeerConnectedOrFailed(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator})})),t}_tryConnectToAllPeers(){const{logger:e}=this;if(0!==this.peers.length)for(this._checkDCMap(),e.info(`try connect to ${this.peers.length} peers, map size ${this.DCMap.size} limit ${this.maxConnsActive} peersNum ${this.scheduler.peersNum}`);this.peers.length>0&&!(this.DCMap.size>=this.maxConnsActive);){let t=this.peers.shift();if(this.isPeerConnectedOrFailed(t.id))continue;const i=t.intermediator;this.signalerWs.connected||i&&this.DCMap.has(i)?(e.debug(`create DataChannel ${t.id} intermediator ${i}`),this._createDatachannel(t.id,!0,i)):e.info(`skip peer ${t.id} without intermediator`)}else e.info("no peers after filter")}_handleSendSignal(e,t){const i=e.remotePeerId;if(e.intermediator){const r=this.DCMap.get(e.intermediator);if(r){let n=!0;for(let e of t)r.sendMsgSignal(i,this.peerId,e)||(n=!1);if(n)return;this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,this.signalerWs.sendSignalBatch(i,t,e.signalName)}_setupDC(t){t.on(e.DC_SIGNAL,(e=>{this._handleSendSignal(t,[e])})).on(e.DC_SIGNAL_BATCH,(e=>{this._handleSendSignal(t,e)})).on(e.DC_PEER_SIGNAL,(e=>{const i=e.to_peer_id||e.to,r=e.from_peer_id||e.from,n=e.action;if(i&&r&&n)if(i!==this.peerId){this.logger.info(`relay signal for ${r}`);const s=this.DCMap.get(i);if(s){if("signal"!==n)return void s.sendMsgSignalReject(i,r,e.reason,e.fatal);if(s.sendMsgSignal(i,r,e.data))return}t.sendMsgSignal(r,i)}else"signal"===n?this._handleSignalMsg(r,e,t.remotePeerId):this._handSignalRejected(r,e)})).on(e.DC_GET_PEERS,(()=>{const e=g(),i=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?15:22)&&!e.super));if(i&&i.length>0){const r=[];i.forEach((i=>{if(i.remotePeerId===t.remotePeerId||i.remotePeerId===this.peerId)return;if(!this.config.live&&(i.currentPos-t.currentPos>600||i.currentPos<t.currentPos))return;e-i.timeJoin>50&&r.push({id:i.remotePeerId,...i.region})})),this.logger.info(`send ${r.length} peers to ${t.remotePeerId}`),t.sendPeers(r)}})).on(e.DC_PEERS,(e=>{const i=e.peers;this.logger.info(`receive ${i.length} peers from ${t.remotePeerId}`),i&&i.length>0&&(i.forEach((e=>{e.intermediator=t.remotePeerId,e.region||(e.region={})})),this.requestPeersQueue.push(...i)),this.requestPeersWaitCount--,this.requestPeersWaitCount<=0&&this._handleRequestedPeers()})).once(e.DC_ERROR,((e,i)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${i}`),this.scheduler&&(this.scheduler.deletePeer(t),this._destroyAndDeletePeer(t.remotePeerId,e),this.fetcher&&(t.connected||e&&this.fetcher.increFailConns(),e&&this.failedDCMap.set(t.remotePeerId,`DC_FAILED ${i}`),this._doSignalFusing(this.scheduler.peersNum),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:i,data:r})=>{const{logger:n,signalerWs:s,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,n.warn("gotSignalFails many, forcePolling"),s.forcePolling(u))),i&&e&&h&&(this.failedDCMap.set(o,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!e&&h&&!l&&this._tryBackupSignal(t,o,r))return t._startTimer(),void n.warn(`${o} conn timeout, try backup signal`);this._destroyAndDeletePeer(o,!1),this._doPeersRequest()})).once(e.DC_CLOSE,(e=>{this.logger.info(`datachannel ${t.channelId} closed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(t.remotePeerId,e),e&&this.failedDCMap.set(t.remotePeerId,"DC_CLOSE"),this._doPeersRequest()})).once(e.DC_OPEN,(()=>{t.isInitiator&&this.scheduler.handshakePeer(t)})).once(e.DC_METADATA,(e=>{const{scheduler:i}=this;t.isInitiator||i.handshakePeer(t),i.handleMetaData(t,e);const r=this.DCMap.size>=this.maxConnsActive;this.requestMorePeers(r),t.intermediator&&this.peersIncrement++,this._doSignalFusing(i.peersNum)}))}_doPeersRequest(){const e=this.scheduler.peersNum;!this.signalerWs.connected||this.overloaded&&e>this.minConns?this._requestPeersFromPeers(e):this.requestMorePeers(),this._tryConnectToAllPeers()}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e<=this.minConns&&this.signalerWs.normalClosed&&(this.logger.warn(`low conns ${e}, reconnect signaler`),this.signalerWs.reconnect())}_initSignalerWs(t,i,r,n){const s=(e,t)=>{let i=`${e}?id=${this.peerId}&p=web&v=2.14.3`;return this.config.signalCompact&&(i=`${i}&c=1`),t&&(i=`${i}&token=${t}`),i};let a,o=s(t,r);if(i&&i!==t){let e=s(i,n);a=new lt(this.logger,this.config,o,e)}else a=new ot(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this.engine.emitEvent("serverConnected",!0),this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let i=e.action;const r=e.from_peer_id||e.from;if(r)switch(i){case"signal":this._handleSignalMsg(r,e,null,t);break;case"reject":this._handSignalRejected(r,e);break;default:this.logger.warn(`Signal websocket unknown action ${i}`)}else this.logger.warn("fromPeerId is missed")},a.onclose=()=>{this.connected=!1,this.engine.emitEvent("serverConnected",!1)},a.onerror=t=>{t.message&&this.logger.warn(`signal err: ${t.message}`),t.message&&this.engine.emitEvent(e.EXCEPTION,Fe(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const i=`signaling ${e} rejected`;this.logger.warn(`${i}, reason ${t.reason}`);const r=this.DCMap.get(e);r&&!r.connected&&(r.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,i),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,i,r="main"){return!(!(this.signalerWs.backupConnected&&e&&i.length>0&&"main"===r)||e.useBackupSignal)&&(e.useBackupSignal=!0,e.signalName="backup",e.intermediator=void 0,this.signalerWs.sendSignalBatch(t,i,"backup"),!0)}_handleSignalMsg(e,t,i,r){if(!this.scheduler)return;const{logger:n}=this;if(t.data){if(this.failedDCMap.has(e))return void this._sendSignalReject(e,`${e} ${this.failedDCMap.get(e)||"unknown"}`,i,r,!0);this._handleSignal(e,t.data,i,r)}else{const t=this.DCMap.get(e);if(!t)return;if(this._tryBackupSignal(t,e,t.signalMsgs,r))return void this.logger.warn(`${e} not found from main, try backup signal`);if(t.useBackupSignal)return;this._destroyAndDeletePeer(e),n.info(`signaling ${e} not found`);const{scheduler:s}=this;s.waitForPeer&&(s.waitingPeers--,0===s.waitingPeers&&s.notifyPeersLoaded(0)),this.requestMorePeers(),this._tryConnectToAllPeers(),i||this.notFoundDCSet.add(e)}}_handleSignal(e,t,i,r){let n=t;"string"==typeof n?n=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:bt(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),i="O"===e[0];return{type:i?"offer":"answer",sdp:At(t,i)}})(n):t=void 0;const s=n.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"===s&&o.isInitiator){if(!(this.peerId>e))return void a.warn(`${e} signal type wrong ${s}, ignored`);a.warn(`${e} signal type wrong ${s}, convert to non initiator`),this._destroyAndDeletePeer(e,!1),o=this._createDatachannel(e,!1,i)}}else{if("answer"===s){const t=`${e} type wrong ${s}`;return a.warn(t),this._sendSignalReject(e,t,i,r),void this._destroyAndDeletePeer(e,!1)}if(a.debug(`receive node ${e} connection request`),this.DCMap.size>=this.maxConns){const t=`reach limit ${this.maxConns}`;return a.warn(t),void this._sendSignalReject(e,t,i,r)}o=this._createDatachannel(e,!1,i)}o&&(r&&(o.signalName=r),o.receiveSignal(n,t))}_createDatachannel(e,t,i){if(!this.fetcher)return;let r;if(t&&this.peerPool.available)r=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${r.signalMsgs.length}`),r.intermediator=i,r.assignPeerId(this.peerId,e);else{let n=this.config.trickleICE;this.overloaded&&(n=!1),r=new Z(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:i,trickle:!i&&n})}return this.DCMap.set(e,r),this._setupDC(r),r}_sendSignalReject(e,t,i,r,n){if(i){const r=this.DCMap.get(i);if(r&&r.sendMsgSignalReject(e,this.peerId,t,n))return}this.signalerWs.sendReject(e,t,n,r)}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this,i=this.scheduler.peersNum;i>=this.maxConnsActive||(t.info(`requestMorePeers after delay ${e}, peersIncrement ${this.peersIncrement}`),i<3||i<this.minConns&&this.peersIncrement<=3&&!this.gotPeersFromTracker?this._requestPeersFromServer(i):this._requestPeersFromPeers(i)||this._requestPeersFromServer(i),this.peersIncrement=0)}_requestPeersFromServer(e){const{logger:t}=this;this.failedDCMap.size>50&&(this.failedDCMap=new Map([...this.failedDCMap].slice(-50))),this.notFoundDCSet.size>20&&(this.notFoundDCSet=new Set([...this.notFoundDCSet].slice(-20))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCMap.keys(),...this.notFoundDCSet.keys()],0===e).then((e=>{e&&e.peers&&(t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=this._filterPeers(e.peers),this._tryConnectToAllPeers())})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0}_requestPeersFromPeers(e){return!!this.requestPeersTimer||(e>=this.maxConnsActive||(this.requestPeersWaitCount=this.scheduler.requestPeers(),0!==this.requestPeersWaitCount&&(this.gotPeersFromTracker=!1,this.requestPeersTimer=setTimeout((()=>{this.logger.warn("requestPeersTimer timeout"),this._handleRequestedPeers()}),1e4),!0)))}_handleRequestedPeers(){if(clearTimeout(this.requestPeersTimer),this.requestPeersTimer=void 0,this.fetcher){if(this.requestPeersQueue.length>0){const e=function(e,t){const i=[],r=new Set;for(let t of e)r.has(t.id)||(r.add(t.id),i.push(t));const{asn:n,country:s}=t;if(!n||!s||i.length<2)return i;const a=i.filter((e=>!e.asn&&!e.country)),o=i.filter((e=>e.country===s&&e.asn!==n)),l=i.filter((e=>e.asn===n&&e.country===s)),h=i.filter((e=>!a.includes(e)&&!l.includes(e)&&!o.includes(e)));return l.concat(o).concat(a).concat(h)}(this.requestPeersQueue,this.fetcher.announceInfo);this.peers=this._filterPeers(e),this.requestPeersQueue=[]}this._tryConnectToAllPeers()}}_destroyAndDeletePeer(e,t=!0){const i=this.DCMap.get(e);return!!i&&(i.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=g();for(let t of this.DCMap.values()){const i=e-t.timeJoin;e-t.timeJoin>30&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${i} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}}const Pt=Rt;class kt extends re{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},ce,e),t){this.HLSEvents=t.constructor.Events;const e=t.constructor.version;this.hlsjsVersion=e,this.config.isHlsV0=e&&"0"===e.split(".")[0]}this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t}=this.config,i=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(i=this.makeChannelId(e,t));return{channelIdMaker:i,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo}}}setupElectron(){this.browserInfo.device===X.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e=super.getExtraForStats();return!this.config.live&&this.media&&(e.pos=Math.round(this.media.currentTime)),this.multiBitrate&&this.currentLevel!==this.lastLevel&&(e.level=this.currentLevel+"",this.lastLevel=this.currentLevel),e}getExtraForPeersRequest(){const e=super.getExtraForPeersRequest();return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){super.destroy()}async initSegmentManager(e){const{logger:i,config:r}=this;if(self.indexedDB&&r.useDiskCache&&!r.live){const e=new ke(this,r);try{await e.setupStore(),this.bufMgr=e}catch(e){i.warn(e),this.bufMgr=new Ce(this,r)}}else this.bufMgr=new Ce(this,r);if(this.bufMgr.maxBufSize<=0)throw new Error("bufMgr state is invalid");"SegmentStore"===this.bufMgr.name&&(this.removeAllListeners(t.BM_FATAL_ERROR),this.once(t.BM_FATAL_ERROR,(()=>{const t="SegmentStoreFatalError";i.warn(`${t}, switch to SegmentCache`),this.bufMgr.destroy(),this.bufMgr=new Ce(this,r),e&&e(this.bufMgr),i.report(JSON.stringify(this.browserInfo),t,this.peerId,"2.14.3",5e4)})))}generateTag(){let e=(0,X.getBrowser)();return e.includes("iPhone")&&"HlsSwP2pEngine"===this.engineName&&(e=`${e}_p`),this.playerName&&(e=`${e}_${this.playerName}`),e}async _init(e,t,i){const{logger:r,config:n}=this;if(!re.isSupported())throw new Error("webrtc is not supported");await this.initSegmentManager((e=>{if(this.tracker){const{scheduler:t}=this.tracker;t.bufferManager=e,t.bitset.clear()}})),i.live||this.media&&(i.pos=Math.round(this.media.currentTime)),i.tag=void 0===n.tag?this.generateTag():n.tag;let s=new it(this,n.token,encodeURIComponent(e),n.announce||"",i);this.fetcher=s,this.tracker=new Pt(this,s,t,n),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?he:le)}_onHlsError(e,i){if(!i||!this.hlsjs)return;const{logger:r,tracker:n}=this;if(!r)return;const s=`${i.type} details ${i.details} reason ${i.reason}`;if(i.fatal?r.error(s):r.warn(s),"networkError"===i.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:a}=this.browserInfo,o=`${a||""} hlsjs ${this.hlsjsVersion} ${location.href}`,l=this.hlsjs.constructor.ErrorDetails;switch(i.details){case l.BUFFER_STALLED_ERROR:if("HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),n&&n.scheduler){const e=n.scheduler;r.warn(`buffered: ${1e3*e.getBufferedDuration()} fragLoading ${e.fragLoading} isCritical ${e.isCritical()}`)}break;case l.INTERNAL_EXCEPTION:if(i.event&&"demuxerWorker"!==i.event){i.error||(i.error={});const e=`${i.error.message} event ${i.event} ${o}`;this.fetcher&&i.fatal&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=e),r.error(`INTERNAL_EXCEPTION event ${i.event} err ${i.error.message}`),this.emitEvent(t.EXCEPTION,Fe(i.error,"HLSJS_EXPT")),r.report(e,i.event,this.peerId,"2.14.3")}break;default:if(i.fatal||i.details===l.FRAG_PARSING_ERROR){const e=`${i.type} ${i.details} ${i.err||""} ${o}`;r.report(e,i.details,this.peerId,"2.14.3"),"mediaError"===i.type&&this.tracker&&this.tracker.scheduler&&this.tracker.scheduler.clearCache()}}}}class Dt{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 wt{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[wt.ElementaryStreamTypes.AUDIO]:!1,[wt.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=o.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url}set url(e){this._url=e}get byteRange(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;let e=[];if(this.rawByteRange){const t=this.rawByteRange.split("@",2);if(1===t.length){const t=this.lastByteRangeEndOffset;e[0]=t||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get decryptdata(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}get endProgramDateTime(){if(!Number.isFinite(this.programDateTime))return null;let e=Number.isFinite(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}addElementaryStream(e){this._elementaryStreams[e]=!0}hasElementaryStream(e){return!0===this._elementaryStreams[e]}createInitializationVector(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let i=e;return e&&e.method&&e.uri&&!e.iv&&(i=new Dt,i.method=e.method,i.baseuri=e.baseuri,i.reluri=e.reluri,i.iv=this.createInitializationVector(t)),i}}class Ct{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 Mt=/^(\d+)x(\d+)$/,Ot=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class xt{constructor(e){"string"==typeof e&&(e=xt.parseAttrList(e));for(let t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}enumeratedString(e){return this[e]}decimalResolution(e){const t=Mt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,i={};for(Ot.lastIndex=0;null!==(t=Ot.exec(e));){let e=t[2],r='"';0===e.indexOf(r)&&e.lastIndexOf(r)===e.length-1&&(e=e.slice(1,-1)),i[t[1]]=e}return i}}const Ft=xt,Nt={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 Bt=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Ut=/#EXT-X-MEDIA:(.*)/g,Gt=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?/,Vt=/\.(mp4|m4s|m4v|m4a)$/i;class Kt{static findGroup(e,t){if(!e)return null;let i=null;for(let r=0;r<e.length;r++){const n=e[r];n.id===t&&(i=n)}return i}static convertAVC1ToAVCOTI(e){let t,i=e.split(".");return i.length>2?(t=i.shift()+".",t+=parseInt(i.shift()).toString(16),t+=("000"+parseInt(i.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let i,r=[];function n(e,t){["video","audio"].forEach((i=>{const r=e.filter((e=>function(e,t){const i=Nt[t];return!!i&&!0===i[e.slice(0,4)]}(e,i)));if(r.length){const n=r.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${i}Codec`]=n.length>0?n[0]:r[0],e=e.filter((e=>-1===r.indexOf(e)))}})),t.unknownCodecs=e}for(Bt.lastIndex=0;null!=(i=Bt.exec(e));){const e={},s=e.attrs=new Ft(i[1]);e.url=Kt.resolve(i[2],t);const a=s.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=s.decimalInteger("AVERAGE-BANDWIDTH")||s.decimalInteger("BANDWIDTH"),e.name=s.NAME,n([].concat((s.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=Kt.convertAVC1ToAVCOTI(e.videoCodec)),r.push(e)}return r}static parseMasterPlaylistMedia(e,t,i,r=[]){let n,s=[],a=0;for(Ut.lastIndex=0;null!==(n=Ut.exec(e));){const e={},o=new Ft(n[1]);if(o.TYPE===i){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=i,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=Kt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),r.length){const t=Kt.findGroup(r,e.groupId);e.audioCodec=t?t.codec:r[0].codec}e.id=a++,s.push(e)}}return s}static parseLevelPlaylist(e,t){let i,r,n=0,s=0,a=new Ct(t),o=new Dt,l=0,h=null,u=new wt,d=null;for(Gt.lastIndex=0;null!==(i=Gt.exec(e));){const e=i[1];if(e){u.duration=parseFloat(e);const t=(" "+i[2]).slice(1);u.title=t||null,u.tagList.push(t?["INF",e,t]:["INF",e])}else if(i[3]){if(Number.isFinite(u.duration)){const e=n++;u.start=s,u.levelkey=o,u.sn=e,u.cc=l,u.baseurl=t,u.relurl=(" "+i[3]).slice(1),Wt(u,h),a.fragments.push(u),h=u,s+=u.duration,u=new wt}}else if(i[4]){if(u.rawByteRange=(" "+i[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(u.lastByteRangeEndOffset=e)}}else if(i[5])u.rawProgramDateTime=(" "+i[5]).slice(1),u.tagList.push(["PROGRAM-DATE-TIME",u.rawProgramDateTime]),null===d&&(d=a.fragments.length);else{for(i=i[0].match(Ht),r=1;r<i.length&&void 0===i[r];r++);const e=(" "+i[r+1]).slice(1),s=(" "+i[r+2]).slice(1);switch(i[r]){case"#":u.tagList.push(s?[e,s]:[e]);break;case"PLAYLIST-TYPE":a.type=e.toUpperCase();break;case"MEDIA-SEQUENCE":n=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 Dt,g&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(f)>=0&&(o.method=f,o.baseuri=t,o.reluri=g,o.key=null,o.iv=p));break;case"START":let r=new Ft(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(r)&&(a.startTimeOffset=r);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 wt,u.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${i}`)}}}return u=h,u&&!u.relurl&&(a.fragments.pop(),s-=u.duration),a.totalduration=s,a.averagetargetduration=s/a.fragments.length,a.endSN=n-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>Vt.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),u=new wt,u.relurl=a.fragments[0].relurl,u.baseurl=t,u.level=id,u.sn="initSegment",a.initSegment=u,a.needSidxRanges=!0),d&&function(e,t){let i=e[t];for(let r=t-1;r>=0;r--){const t=e[r];t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(a.fragments,d),a}}function Wt(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 $t={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},qt=(e,t,i,r,n=!1)=>{const[s,a,o]=jt(e,t,i,r);return n&&s.length>=1?P(s[0]):s.length>=2?[s[0],s[1]]:k(s,a,o)},jt=(e,t,i,r)=>{const n=[],{COMPLETE:s,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=$t;return[s,a,o].forEach((s=>{n.push(Yt(e,s,t,i,r))})),n},Yt=(e,t,i,r,n)=>e.filter((e=>e.bitset.hasWithId(i,r,n,t)));class zt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const i=Number(e);if(i<0)continue;const r=new Map;if(t[e])for(let i of t[e])r.set(i,{state:$t.COMPLETE,segId:void 0,size:void 0});this.levelMap.set(i,r)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,i,r=$t.ANY){if(t<0)return!1;const n=this._createOrGetSet(t).get(e);return!!n&&((!i||!n.segId||n.segId===i)&&(r===$t.ANY||n.state===r))}has(e,t,i=$t.ANY){return this.hasWithId(e,t,void 0,i)}hasCompleteOr(e,t,i=$t.COMPLETE){const r=this._createOrGetSet(t).get(e);return!!r&&(r.state===$t.COMPLETE||r.state===i)}getObj(e,t){let i=this._createOrGetSet(t).get(e);return i||(i={}),i}getSegId(e,t){return this.getObj(e,t).segId}getSize(e,t){return this.getObj(e,t).size}getState(e,t){return this.getObj(e,t).state}delete(e,t){return this._createOrGetSet(t).delete(e)}add(e,t,i,r,n){if("number"!=typeof(s=e)||s%1!=0)return;var s;this._createOrGetSet(t).set(e,{state:r,segId:i,size:n}),this.isLive&&this._trimBitset(e)}array(e){const t=this._createOrGetSet(e);return this._keysForStateComplete(t)}allArray(){let e={};return this.levelMap.forEach(((t,i)=>{e[i]=this._keysForStateComplete(t)})),e}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetSet(e).size}_createOrGetSet(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}_trimBitset(e){const t=e-20;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[i,r]of e)r.state===$t.COMPLETE&&t.push(i);return t}}class Xt{constructor(){this.levelMap=new Map}totalLevels(){return this.levelMap.size}has(e,t){return this._createOrGetMap(t).has(e)}delete(e,t){return this._createOrGetMap(t).delete(e)}decre(e,t){const i=this._createOrGetMap(t);if(i.has(e)){let t=i.get(e);1===t?i.delete(e):i.set(e,t-1)}}incre(e,t){const i=this._createOrGetMap(t);if(i.has(e)){let t=i.get(e);i.set(e,t+1)}else i.set(e,1)}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetMap(e).size}_createOrGetMap(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}}const Qt=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))}},Jt=Symbol("shareOnly");class Zt extends(s()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Qt,this.fragLoading=!1,this._setupEngine&&this._setupEngine(),this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[Jt]=!1,this.downloadOnly=!1,this.loadedPeerNum=0,this.minConns=5}get isMobileNet(){return this.engine.isMobileNet}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const e=this.getStatsForPeer();let t=this.peersNum;const i=g();this.getPeers().forEach((r=>{t>this.minConns+1&&(i-r.dataExchangeTs>120||i-r.gotStatsTs>=83)?(this.logger.warn(`close dead peer ${r.remotePeerId} level ${r.currentLevel}`),r.close(!1),t--):r.connected&&r.sendMsgStats(t,e)}))}),4e4)}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}requestPeers(){const e=g();let t=0;for(let i of this.getPeers())i.mobileNet||i.super||(e-i.gotPeersTS<60?this.logger.warn(`${i.remotePeerId} just got peers, ignored`):(i.sendPeersRequest(),i.gotPeersTS=e,t++));return t}chokePeerRequest(t){const i={event:e.DC_CHOKE};t?t.sendJson(i):this._broadcastToPeers(i)}unchokePeerRequest(t){const i={event:e.DC_UNCHOKE};t?t.sendJson(i):this._broadcastToPeers(i)}stopRequestFromPeers(){for(let e of this.getPeers())e.choked=!0}resumeRequestFromPeers(){for(let e of this.getPeers())e.choked=!1}setShareOnly(){this[Jt]=!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[Jt]&&(e.choked=!0);const i=this.peerManager.getPeerIds();this._peersStats(i);const{asn:r,country:n}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${n||""} asn ${r||""}, now has ${i.length} peers`)}hasPeer(e){return this.peerManager.hasPeer(e)}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const{logger:e}=this,t=this.getIdlePeer().length;if(e.info(`peers: ${this.peersNum} idle peers: ${t}`),t<this.peersNum){const t=this.peerManager.getPeers(),i=t.filter((e=>e.downloading));e.warn(`downloading: ${i.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of i)e.warn(`${t.remotePeerId} loading ${t.segId} remains ${t.remainAttachments} total ${t.pieceMsg.attachments}`)}return t>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(t){this.bufMgr=t,t.on(e.BM_LOST,(({sn:e,segId:t,next:i,level:r})=>{this._broadcastLost(e,t,r),this.onBufferManagerLost(e,t,i,r)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,i,r,n){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:i||void 0,level:r},n)}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),clearTimeout(this.checkTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(t){const{logger:i}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),i.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{i.warn(`peer ${t.remotePeerId} download aborted, reason ${e.reason}`),this._handlePieceAborted(t.remotePeerId),this.config.live&&this.checkPeers&&this.checkPeers()})).on(e.DC_DISCONNECT,(()=>{this.peersNum>=this.minConns&&(this.logger.warn(`close disconnected peer ${t.remotePeerId}`),t.close(!1))}))}_broadcastToPeers(e,t){for(let i of this.getPeers())t&&i===t||i.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;I(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(i=this.loadedPeerNum)?3:.5*i+1.67);var i;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const i=this.requestingMap.get(e);if(i)return void i.removeStreamListener(t);const r=this.segmentBuilderMap.get(e);r&&r.removeStreamListener(t)}setTargetPeersFromGroup(e,t,i,r){if(e.hasReversePeer){if((i=t.concat(i)).length>0)return this.targetPeers.forwardPeer=i[0],!0}else if(e.hasForwardPeer&&(r=t.concat(r)).length>0)return this.targetPeers.reversePeer=r[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=k(t,i,r),this.targetPeers.some((e=>!!e)))}}const ei=Zt;class ti extends(s()){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 ii=0,ri=1,ni=2,si=3;class ai extends(s()){constructor(){super(),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.timeout=0,this.withCredentials=!1,this.status=0,this.readyState=this.UNSENT,this.headers=new Map,this.responseHeaders=null,this.on("load",(e=>{this.onload&&this.onload(e)})),this.on("abort",(e=>{this.onabort&&this.onabort(e)})),this.on("error",(e=>{this.onerror&&this.onerror(e)})),this.on("loadstart",(e=>{this.onloadstart&&this.onloadstart(e)})),this.on("progress",(e=>{this.onprogress&&this.onprogress(e)})),this.on("timeout",(e=>{this.ontimeout&&this.ontimeout(e)})),this.on("loadend",(e=>{this.onloadend&&this.onloadend(e)})),this.on("readystatechange",(()=>{this.onreadystatechange&&this.onreadystatechange()}))}setRequestHeader(e,t){this.headers.set(e,t)}addEventListener(e,t){this.addListener(e,t)}removeEventListener(e,t){this.removeListener(e,t)}overrideMimeType(){}getAllResponseHeaders(){if(!this.responseHeaders)return null;let e="";return this.responseHeaders.forEach(((t,i)=>{e+=`${i}: ${t}\n`})),e}getResponseHeader(e){return this.responseHeaders?this.responseHeaders.get(e):null}open(){this.readyState=this.OPENED,this.emit("loadstart")}abort(){this.readyState=this.DONE,this.status=0,this.emit("loadend")}send(){}_emitEvent(e){this.emit(e,{type:e,target:this})}}const oi=/(\d+)-(\d+)\/(\d+)/;function li(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class hi{constructor(e){this.fetchSetup=e.fetchSetup||ui,this.xhrSetup=e.xhrSetup,this.controller=new self.AbortController,this.stats=D(),this.packetSize=u,this.fakeXhr=new ai}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.xhrSetup=this.fakeXhr=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.callbacks&&this.callbacks.onUpdate&&this.callbacks.onUpdate(void 0,!1,!0),this.controller.abort())}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;r.trequest=r.loading.start;let n=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal);const s="arraybuffer"===e.responseType,a=s?"byteLength":"length",{maxTimeToFirstByteMs:o=8e3,maxLoadTimeMs:l=2e4}=t.loadPolicy||{},h=i.onUpdate,u=i.onBodyStart;this.context=e,this.config=t,this.callbacks=i,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),n=function(e,t){e.withCredentials&&(t.credentials="include");for(let[i,r]of e.headers)t.headers.set(i,r);return t}(this.fakeXhr,n)),this.request=this.fetchSetup(e,n),clearTimeout(this.requestTimeout),t.timeout=o&&Number.isFinite(o)?o:l,this.requestTimeout=setTimeout((()=>{this.abortInternal(),this.fakeXhr._emitEvent("timeout"),this.fakeXhr._emitEvent("loadend"),i.onTimeout&&i.onTimeout(r,e,this.response)}),this.fakeXhr.timeout||t.timeout);const d="then"in(c=this.request)&&c.then instanceof Function?this.request.then(self.fetch):self.fetch(this.request);var c;const{fakeXhr:f}=this;f.readyState=f.OPENED,f.emit("readystatechange"),f._emitEvent("loadstart"),d.then((n=>{this.response=this.loader=n;const a=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),l-(a-r.loading.start)),!n.ok){const{status:e,statusText:t}=n;throw new di(t||"fetch, bad network response",e,n)}r.tfirst=r.loading.first=a,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=oi.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Number.isFinite(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(n.headers)||r.total;let o=0;try{const e=n.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=n.headers,d.emit("readystatechange"),h&&"0"!==r.total?(u&&u(r.total,o),this.loadProgressively(n,r,e,h)):(d.emit("progress",new ProgressEvent("progress",{lengthComputable:!1})),s?n.arrayBuffer():"json"===e.responseType?n.json():n.text())})).then((t=>{const{response:n}=this;clearTimeout(this.requestTimeout),r.tload=r.loading.end=Math.max(performance.now(),r.loading.first);const s=t[a];s&&(r.loaded=r.total=s);const o={url:n.url,data:t,code:n.status};i.onProgress&&i.onProgress(r,e,t,n),i.onSuccess&&i.onSuccess(o,r,e,n)})).catch((t=>{if(clearTimeout(this.requestTimeout),r.aborted)return;const n=t&&t.code||0,s=t?t.message:null;i.onError&&i.onError({code:n,text:s},e,t?t.details:null,r)}))}loadProgressively(e,t,i,r){const n=e.body.getReader();let s=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>n.read().then((({value:i,done:n})=>{const{fakeXhr:c}=this;if(c.readyState!==c.LOADING&&(c.readyState=c.LOADING,c.emit("readystatechange")),i&&(s+=i.length),n){if(l.byteLength>0)if(s<=this.packetSize){const e=(0,a.h)(s);l.copy(e,0,o*this.packetSize,l.byteLength),r(e,!0)}else{const e=function(e,t){const i=e.byteLength-t,r=[];let n=t,s=Math.floor(i/u),o=i%u;for(let t=0;t<s;t++){const t=(0,a.h)(u);e.copy(t,0,n,n+u),r.push(t),n+=u}if(o>0){const t=(0,a.h)(o);e.copy(t,0,n,n+o),r.push(t)}return r}(l,o*this.packetSize);for(let t=0;t<e.length;t++)r(e[t],t===e.length-1)}const t=l.buffer,{fakeXhr:i}=this,{status:n,statusText:h,url:d}=e;return i.readyState=i.DONE,i.responseText=n,i.status=h,i.responseURL=d,i.responseType="arraybuffer",i.response=t,i.emit("readystatechange"),i._emitEvent("load"),i._emitEvent("loadend"),Promise.resolve(t)}if(t.loaded+=i.length,c.emit("progress",new ProgressEvent("progress",{lengthComputable:!0,loaded:t.loaded,total:t.total})),this.callbacks.onLoaded&&this.callbacks.onLoaded({total:t.total,loaded:t.loaded,first:!h},this.context),h=!0,l=a.h.concat([l,i]),s>=this.packetSize){s-=this.packetSize;const e=(0,a.h)(this.packetSize);l.copy(e,0,o*this.packetSize,(o+1)*this.packetSize),o++,r(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function ui(e,t){return new self.Request(e.url,t)}class di extends Error{constructor(e,t,i){super(e),this.code=t,this.details=i}}class ci extends(s()){constructor(e,t,i=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=i,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=2e3,this.proxied=!1,this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.forwardBufList=[],this.reverseBufList=[],this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.rangeRequesting=!1,this.waitingRemain=!1,this.httpLoaded=0,this.p2pLoaded=0,this.deadline=0,this.forwardCanceled=!1,this.reverseCanceled=!1,this.firstReceived=!1,this.alreadyOutput=!1,this.pieceMsg={}}get isDownloading(){return this.timeReceivePiece>0}get isAlmostDeadline(){return this.rangeRequesting||this.alreadyOutput}hasPeer(e){return!!e&&(e===this.forwardPeer||e===this.reversePeer)}get streamListeners(){return[...this.reverseStreamListeners,...this.forwardStreamListeners].length}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg,i=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let r of i){const{handler:i}=r;i(e,t,!0,"aborted by synthesizer")}this._resetStreamListeners()}_resetStreamListeners(){this.reverseStreamListeners.length=0,this.forwardStreamListeners.length=0}_notifyStreamListenersRemain(){if(this.forwardStreamListeners.length>0){for(let e=this.forwardOffset+1;e<this.bufArr.length;e++)this._notifyStreamListeners(!1,this.bufArr[e],e);this.forwardStreamListeners=[]}if(this.reverseStreamListeners.length>0){for(let e=this.reverseOffset-1;e>=0;e--)this._notifyStreamListeners(!0,this.bufArr[e],e);this.reverseStreamListeners=[]}}addStreamListener(e,t,i){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:i,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:i}=this.pieceMsg,r=r=>r.filter((r=>r.peerId!==e||(r.handler(t,i,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=r(this.forwardStreamListeners),this.reverseStreamListeners=r(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let i=performance.now();e<=0?setTimeout((()=>{this._handleTimeout(!1,!1)}),0):(this.firstPieceTimer=setTimeout((()=>{if(this.firstReceived)return;const e=()=>{this.logger.warn(`switch to http, firstReceived ${this.firstReceived}`),this._handleTimeout(!1)};if(this.timeReceivePiece>0){const t=(this.timeReceivePiece-i)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=i+e,this._startTimer(e,t))}setExtra(e={}){e.url&&(this.url=e.url),e.rangeStart&&(this.rangeStart=e.rangeStart),e.rangeEnd&&(this.rangeEnd=e.rangeEnd),e.httpLoadTime&&(this.httpLoadTime=e.httpLoadTime),e.proxied&&(this.proxied=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup),e.headers&&(this.headers=e.headers),e.segId&&!this.pieceMsg.seg_id&&(this.pieceMsg.seg_id=e.segId)}get hasForwardPeer(){return!!this.forwardPeer}get hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}get isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}get isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1,t),!0))}setReversePeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0,t),!0))}setPeer(e,t,i){return t?this.setReversePeer(e,i):this.setForwardPeer(e,i)}deletePeer(e){const t=e===this.reversePeer;this._detachPeer(e),t?this.reversePeer=null:this.forwardPeer=null,(this.isEmpty||this.deadline>0)&&this._handleTimeout(!1,!1)}terminate(){this._handleTimeout(!1,!1)}get hasPartialBuffer(){return this.hasForwardBuffer||this.hasReverseBuffer}get hasForwardBuffer(){return this.forwardOffset>=0}get hasReverseBuffer(){return this.pieceMsg&&this.reverseOffset<this.pieceMsg.attachments}get isForwardBufferFull(){return this.pieceMsg&&this.forwardOffset>=this.pieceMsg.attachments-1}get isReverseBufferFull(){return this.reverseOffset<=0}_cancelP2p(e=!1){const{seg_id:t,sn:i,level:r}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(i,r,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(i,r,t),this.reverseCanceled=!0)}detachPeers(){this._detachPeer(this.forwardPeer),this._detachPeer(this.reversePeer)}destroy(){clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._notifyStreamListenersAbort(),this._cancelP2p(),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.httpLoader&&(this.logger.warn("abort syn httpLoader"),this.httpLoader.abort())}_detachPeer(t){if(!t)return;const i=t===this.reversePeer?this.reverseEvents:this.forwardEvents;i&&i&&t.off(e.DC_PIECE_DATA,i.onPieceData).off(e.DC_PIECE,i.onPiece).off(e.DC_PIECE_NOT_FOUND,i.onPieceNotFound).off(e.DC_PIECE_ABORT,i.onPieceAbort)}_receivePacket(t,i,r,n=!0){const{seg_id:s,sn:o,level:l,size:h,attachments:u}=this.pieceMsg,d=i-1;if(this.bufArr[d]?(this.logger.warn(`syn bufArr ${s} already has ${d} size ${r.byteLength}`),this.bufArr[d]=r):(n?this.p2pLoaded+=r.byteLength:this.httpLoaded+=r.byteLength,this.emit(e.SYN_PROGRESS,{total:h,loaded:this.p2pLoaded+this.httpLoaded,first:!this.firstReceived,segId:s,sn:o}),this.firstReceived=!0,this.bufArr[d]=r,t?this.reverseOffset=d:this.forwardOffset=d,this._notifyStreamListeners(t,r,d)),this.forwardOffset!==this.reverseOffset-1)return!0;this.rangeRequesting||(this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0)),clearTimeout(this.timer),this._notifyStreamListenersRemain();const c=performance.now()-this.timeStart,f=h/c;let g=a.h.concat(this.bufArr);const p=g.byteLength;if(p===h){let t=g.buffer;const i=new z(o,s,t,this.getFromPeerId(),l,this.pieceMsg.ext);this.alreadyOutput=!0,this.emit(e.SYN_OUTPUT,i,{speed:f,time:c,p2p:this.p2pLoaded,http:this.httpLoaded})}else{this.logger.error(`${s} 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,ii),this._disconnectPeers()}}_disconnectPeers(){[this.forwardPeer,this.reversePeer].forEach((t=>{t&&t.emit(e.DC_ERROR,!0)}))}_checkPieceSize(e){const{size:t,seg_id:i,sn:r}=this.pieceMsg;return!e||!t||e===t||(this.logger.warn(`checkPieceSize ${i||r} size not match ${t} ${e}`),!1)}_setupPeer(t,i,r){const{logger:n}=this;0===this.timeStart&&(this.timeStart=performance.now()),r&&!this.pieceMsg.size&&(this.pieceMsg.size=r);const s=(i,r,s,a,o,l)=>{if(this.destroyed)return;if(!this._validateMsg(i,l.level,r))return void n.error(`onPieceData ${r||i} size ${s.byteLength} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(a<this.pieceMsg.attachments&&s.byteLength!==u)return n.error(`${r} dataSn ${a} size is ${s.byteLength}`),this.emit(e.SYN_ERROR,this.pieceMsg,ii),void this._disconnectPeers();const{reverse:h}=l;this._receivePacket(h,a,s)&&!this.waitingRemain&&!this.rangeRequesting&&this.deadline>0&&this._shouldSwitch()&&(n.warn("should switch to http"),clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._handleTimeout(!1,!1))},a=e=>{if(this.destroyed)return;const{attachments:i,size:r,sn:s,level:a,seg_id:o,ext:l}=e;return r<=999||!this._validateMsg(s,a,o)?(n.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),t.cancelDownload(s,a,o),void this.deletePeer(t)):this._checkPieceSize(r)?void(0===this.bufArr.length&&(this.pieceMsg={...this.pieceMsg,seg_id:o,size:r,attachments:i,ext:l},this.reverseOffset=i,this.bufArr=new Array(i),this.timeReceivePiece=performance.now())):(t.cancelDownload(s,a,o),void this.deletePeer(t))},o=e=>{this.destroyed||this.deletePeer(t)},l=()=>{this.destroyed||this.deletePeer(t)},h={onPieceData:s,onPiece:a,onPieceNotFound:o,onPieceAbort:l};i?this.reverseEvents=h:this.forwardEvents=h,t.on(e.DC_PIECE_DATA,s).once(e.DC_PIECE,a).once(e.DC_PIECE_NOT_FOUND,o).once(e.DC_PIECE_ABORT,l)}_shouldSwitch(){const e=u,t=this.pieceMsg.size-e*this.loadedPackets;return this.coordinator.shouldSwitchToHttp(t,this.deadline,this.p2pSpeed,e,this.httpLoadTime)}_startTimer(e,t=!0){this.timer=setTimeout(this._handleTimeout.bind(this,t),e)}get loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(t=!1,i=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:r,size:n,attachments:s}=this.pieceMsg;if(!n||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${r} url ${this.url}`),void this.emit(e.SYN_ERROR,this.pieceMsg,ii);if(t&&this.timeReceivePiece>0&&s){this.logger.warn(`syn ${this.loadedPackets} of ${s} packets loaded`);const e=this.httpLoadTime>3e3?3e3:this.httpLoadTime;if(this.shouldWaitForRemain(e))return this.waitingRemain=!0,this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}if(i){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const i=e.currentLoadSpeed(),r=t.currentLoadSpeed();return i===r?e.timeSendRequest-t.timeSendRequest:i-r})).shift();e&&e.loadtimeout()}if((this.rangeSupported||!this.hasPartialBuffer)&&this.url)return this._cancelP2p(!0),this._loadRemainBufferByHttp();this._notifyStreamListenersAbort(),this.emit(e.SYN_ERROR,this.pieceMsg,si)}shouldWaitForRemain(e){return!this.isEmpty&&this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed,i=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${i}`),t>=i}minRequiredSpeed(e){let t=0;return[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(t+=e.loadedBytes())})),(this.pieceMsg.size-t)/e}get p2pSpeed(){let e=0;return[this.forwardPeer,this.reversePeer].forEach((t=>{t&&(e+=t.currentLoadSpeed())})),e}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull&&e!==t?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}getStreamInfo(e){const t=e?this.reverseBufList:this.forwardBufList;let i,r;return t.length<this.pieceMsg.attachments?(i=this.isFull?"WaitPartialDouble":"WaitPartialSingle",r=1):(i=this.isFull?"SynFullDouble":"SynFullSingle",r=0),{from:i,incompletes:r,bufferList:t}}_loadRemainBufferByHttp(){if(this.rangeRequesting)return;const{size:t,seg_id:i}=this.pieceMsg,{logger:r}=this,n=this.rangeEnd>0?this.rangeEnd-1:0;let s=this.forwardOffset;const a=performance.now();this.rangeRequesting=!0;let o=oe(s,this.reverseOffset,t,this.rangeStart,n);const l=o.rangeEnd-o.rangeStart;r.info(`listeners ${this.streamListeners} continue download ${i} from ${this.url} range: ${o.rangeStart}-${o.rangeEnd}`),this.hasPartialBuffer||(o={});const u=new hi({xhrSetup:this.xhrSetup});this.httpLoader=u;let d={url:this.proxied?f(this.url,h,!0):this.url,...o};let c,g=s+1;const p={onUpdate:(t,i,n)=>{if(!this.destroyed){if(n)return r.warn("httpLoader aborted"),void this.emit(e.SYN_ERROR,this.pieceMsg,ri);if(i){const e=c/(performance.now()-a);this.coordinator.addHttpSpeed(e),this.httpLoader=void 0}this.bufArr[g]||this._receivePacket(!1,g+1,t,!1),g++}},onBodyStart:(t,n)=>{if(0===n&&r.warn(`range request fileSize ${n}`),this.destroyed)return;const{size:s}=this.pieceMsg;if(c=t,t!==s||0!==n&&n!==s){let i=!1;n>0&&n!==s?(r.error(`onBodyStart fileSize ${n} != ${s}`),i=!0):t!==l&&(r.error(`onBodyStart size ${t} != expectedSize ${l}`),i=!0),i&&this.emit(e.SYN_ERROR,this.pieceMsg,ri)}else r.warn(`syn range request ${i} resp whole ts`),g=0},onError:t=>{this.destroyed||(r.error(`httpLoader error ${t.text}`),this.emit(e.SYN_ERROR,this.pieceMsg,ri))},onTimeout:()=>{this.destroyed||(r.warn("httpLoader timeout"),this.emit(e.SYN_ERROR,this.pieceMsg,ni))}};u.load(d,{timeout:15e3},p)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class fi extends ci{constructor(e,i,r,n,s,a=!1,o){super(e,i,a,o),this.pieceMsg={event:t.DC_PIECE,sn:r,level:n,seg_id:s},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,i){const{sn:r,seg_id:n,attachments:s}=this.pieceMsg,a=e&&0===i||!e&&i===s-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;e?this.reverseBufList.push(t):this.forwardBufList.push(t),a&&(this.forwardBufList.push([...this.reverseBufList].reverse()),this.reverseBufList.push([...this.forwardBufList].reverse()));for(let e of o){const{handler:i}=e;i(r,n,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,i){return(!this.pieceMsg.seg_id||i===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}}class gi{constructor(){this.meanHttpSpeed=0,this.loaderHttpSpeed=0}addHttpSpeed(e){this.meanHttpSpeed=this._cal(this.meanHttpSpeed,e)}addLoaderHttpSpeed(e,t){t&&e&&(this.loaderHttpSpeed=this._cal(this.loaderHttpSpeed,t/e))}getMeanTimeToLoaded(e){return this.loaderHttpSpeed?e/this.loaderHttpSpeed:500}shouldSwitchToHttp(e,t,i,r,n){if(this.meanHttpSpeed<=0)return!1;if(i>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*n>=e)return!1;return((n+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-i)*i<r}_cal(e,t){return.4*e+.6*t}}class pi extends ei{constructor(e,t){super(e,t),this.prefetchOnly=t.prefetchOnly,this.bitset=new zt(t.live||!1),this.bitCounts=new Xt,this.requestingMap=new ti,this.segmentBuilderMap=new ti,this.allowP2pLimit=t.httpLoadTime+1.5,this.playlistInfo=new Map,this.gotPlaylist=!1,this.targetPeers={},this.sequential=!0,this.coordinator=new gi,this.loadingSegId="",this.loadingSN=0,this.currPlaySN=0,this.currLostSN=-1,this.nextLostSN=-1,this.config.live?this.maxPrefetchCount=10:(this.maxPrefetchCount=150,this.startCheckPeersTimer())}handshakePeer(e){this._setupDC(e);const{asn:t,country:i}=this.engine.fetcher.announceInfo;e.sendMetaData(this.bitset.allArray(),!0,this.peersNum,{asn:t,country:i},this.isMobileNet)}_receiveDCHave(e,t,i,r){this.bitset.has(e,t)||this.bitCounts.incre(e,t)}_setupDC(e){super._setupDC(e),e.on(t.DC_HAVE,(t=>{if(e.bitset&&t.sn>=0){const{sn:i,level:r,complete:n,seg_id:s,size:a}=t,o=n?$t.COMPLETE:$t.PARTIAL_FORWARD;e.bitset.add(i,r,s,o,a),this._receiveDCHave(i,r,s,e),e.isAvailableUrgently&&this._handleDCHave(e,i,r,s,a,o)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:i,level:r,seg_id:n,size:s}=t;e.bitset.hasCompleteOr(i,r,$t.PARTIAL_REVERSE)||e.bitset.add(i,r,n,$t.PARTIAL_REVERSE,s),this._receiveDCHave(i,r,n,e),e.isAvailableUrgently&&this._handleDCHave(e,i,r,n,s,$t.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:i,level:r}=t;e.bitset.has(i,r)&&(e.bitset.delete(i,r),this.bitCounts.decre(i,r))})).on(t.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=7||this.requestingMap.has(ue(e.sn,e.level))&&this.notifyAllPeers(e.sn,e.level,e.seg_id,e.size,e.reverse?$t.PARTIAL_REVERSE:$t.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:i,level:r}=t,n=ue(i,r);this.removeStreamListener(n,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:i,level:r}=t;e.bitset.delete(i,r),this.bitCounts.decre(i,r),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:i}=this,{sn:r,level:n,reverse:s}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(r));const o=()=>{this.bitset.delete(r,n),e.sendPieceNotFound(r,a,{level:n}),this._broadcastLost(r,a,n,e)},l=await this.bufMgr.getSegById(a),h=ue(r,n),u=this.requestingMap.get(h);let d=!1;u&&u.isDownloading&&(d=!0);const c=this.segmentBuilderMap.get(h);if(l)if(i.info(`found seg ${a} from bufMgr`),l.level===n){let t="SegmentStore"===this.bufMgr.name?"Disk":"Cache";l.ext&&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:s})}else o();else if(!s&&c)i.info(`peer request ${r} wait from builder, sent ${c.bufferList.length}`),R(e,c,c.pieceMsg,c.bufferList,c.source,1);else if(d){i.info(`syn had ${u.loadedPackets} packets, wait remain from upstream ${u.getFromPeerId()}`);const t={...u.pieceMsg,reverse:s},{from:r,incompletes:n,bufferList:a}=u.getStreamInfo(s);R(e,u,t,a,r,n)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new zt(this.config.live,t.field);for(let e in t.field){const i=Number(e);if(i<0)continue;t.field[i].forEach((e=>{this.bitset.has(e,i)||this.bitCounts.incre(e,i)}))}this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e)}}peersHas(e,t){return this.bitCounts.has(e,t)}deletePeer(e){if(this.peerManager.hasPeer(e.remotePeerId)&&e.bitset){const t=e.bitset.allArray();for(let e in t){const i=Number(e),r=t[i];r&&r.forEach((e=>{this.bitCounts.decre(e,i)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,i,r){const{logger:n,config:s}=this;let a=1e3*(r-s.httpLoadTime);this.allowP2pLimit=s.httpLoadTime+1.5,n.info(`bufferedDuration ${1e3*r} remainLoadTime ${a} allowP2pLimit ${1e3*this.allowP2pLimit}`);const o=ue(e,t),l=this.requestingMap.get(o);if(l){const s=l.segId;if(s&&s!==i)return n.warn(`syn segId ${s} not match ${i}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,i,r);if(!l.shouldWaitForRemain(a)){if(n.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const r=this.peerManager.getPeersOrderByWeight();let[s,o,h]=jt(r,e,t,i);return!!this.setTargetPeersFromGroup(l,s,o,h)||(l.hasReversePeer||l.hasPartialBuffer||a>1e3*(this.allowP2pLimit+1))&&this.httpRangeSupported}return n.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t,i,r)}_searchAvailablePeers(e,t,i,r){if(r<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const n=this.peerManager.getPeersOrderByWeight(),[s,a]=qt(n,e,t,i);return this.targetPeers={forwardPeer:s,reversePeer:a},[s,a].some((e=>!!e))}reportTraffic(e,t,i){const{fetcher:r}=this.engine;r&&(e>0&&r.reportFlow(e),t>0&&r.reportDCTraffic(t,i))}notifyAllPeers(e,t,i,r,n=$t.COMPLETE){if(!i)return void this.logger.error("segId is required");if(this.downloadOnly)return;const{live:s}=this.config;if(this.bitset.has(e,t,n))return;const a=((e,t,i)=>`${e}-${t}-${i}`)(e,t,n);let o;n!==$t.PARTIAL_REVERSE&&(o=n===$t.COMPLETE);const l=this.requestingMap.get(ue(e,t));for(let h of this.getPeers())l&&l.hasPeer(h)||h.notifySet.has(a)||h.bitset.hasCompleteOr(e,t,n)||h.uploading||(h.sendMsgHave(e,i,{level:t,reverse:n===$t.PARTIAL_REVERSE,complete:o,size:r}),h.notifySet.add(a),s&&T(h.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:i}=this;if(!this.hasPeers)return;const r=t.live;if(this.fragLoading)return void e.info("loading urgently, skip prefetch");const{currentLevel:n}=i;if(0===this.bitCounts.size(n))return;if(!r&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;let s=this.peerManager.getPeersOrderByWeight();if(0===s.length)return;let a=0,{prefetchNum:o,endSN:l,startSN:h}=t;if(!r){const t=this.requestingMap.size,i=this.requestingMap.activePeers;if(i>=o)return void e.warn(`requestingMap size ${t} activePeers ${i}`);o-=i}if(this.getBufferedDuration()<this.allowP2pLimit){if(!r)return;o=1}let u=0,d=this.loadingSN+1;if(this.prefetchOnly&&(d+=2),!r)if(this.loadingSN>=l&&!this.bufMgr.overflowed)d=h;else{const e=Math.min(...s.filter((e=>e.endSN>=d)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;d<e&&(d=e)}for(;a<o&&u<this.maxPrefetchCount&&(r||!(d>l))&&!(r&&d>this.loadingSN+2);){if(this.bitset.has(d,n)){d++;continue}const t=ue(d,n),i=this.requestingMap.get(t);if(this.bitCounts.has(d,n)){if(i){for(let e of s)if(e.bitset.has(d,n)){const{state:t,segId:r,size:s}=e.bitset.getObj(d,n);if(this._trySetPeerForSyn(i,e,r,d,n,s,t))break}}else{let i=[null,null];if(r)i=qt(s,d,n,void 0,!0);else for(let e of s)if(e.bitset.has(d,n)){const t=e.bitset.getState(d,n);let r;r=t===$t.COMPLETE?0===p(0,1):t===$t.PARTIAL_REVERSE,i[r?1:0]=e;break}if(i.some((e=>!!e))){const r=new fi(this.coordinator,this.logger,d,n,void 0,this.httpRangeSupported);this._setupSynthesizer(r),this.requestingMap.set(t,r),i.forEach(((t,i)=>{if(t&&a<o){const s=1===i,o=t.bitset.getSize(d,n);r.setPeer(t,s,o)&&(a++,t.requestDataBySN(d,!1,{level:n,reverse:s}),e.info(`request prefetch ${d} level ${n} from peer ${t.remotePeerId} downloadNum ${t.downloadNum} reverse ${s}`))}}))}}s=this.peerManager.getPeersOrderByWeight()}if(u++,d++,0===s.length)break}this.loadedPeerNum=a}onBufferManagerLost(e,t,i,r){this.currLostSN=e,i&&(this.nextLostSN=i),this.bitset.delete(e,r),this.bitCounts.delete(e,r)}onBufferManagerSegAdded(e){const{sn:t,segId:i,level:r,size:n}=e;this.notifyAllPeers(t,r,i,n),this.updateLoaded(t,r,i)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[i,r]of this.requestingMap.internalMap){const n=i.split("-"),s=Number(n[1]),a=Number(n[0]);r.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),r.deletePeer(t),this.bitCounts.decre(s,a),t.bitset.delete(s,a))}}updateLoaded(e,t,i){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,i,$t.COMPLETE),this.bitCounts.delete(e,t))}broadcastPlaylist(e,t){if(!this.config.live)return;const i=function(e){const t=e.split("\n");let i=0,r=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){i=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&r++;return i+r-1}(t);if(!this.isMobileNet)for(let r of this.getPeers())r.sendMsgPlaylist(e,t,i);this.playlistInfo.set(e,{seq:i,data:t})}async getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t,data:i}=this.playlistInfo.get(e),r=()=>{for(let i of this.getPeers()){const r=i.getLatestPlaylist(e,t);if(r)return this.playlistInfo.set(e,r),this.gotPlaylist=!0,r}return null};let n=r();return!n&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await v(240),this.gotPlaylist=!1,n=r()),n}getBufferedDuration(){const{config:e}=this;let{media:t,currentSrc:i}=this.engine;if(!t||t.src!==i&&0===t.currentTime){if(this.logger.info("try get video element"),t=se(this.config.mediaElem,i),!t)return 4;this.engine.media=t}let r=function(e){let t=0,i=e.currentTime,r=e.buffered;for(let e=r.length-1;e>=0;e--)if(i>=r.start(e)&&i<=r.end(e)){t=r.end(e)-i;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return r}destroy(){super.destroy(),this.requestingMap.clear(),this.segmentBuilderMap.clear(),this.engine.removeAllListeners(t.MEDIA_REBUFFER)}clearCache(){"SegmentStore"===this.bufMgr.name?this.engine.emit(t.BM_FATAL_ERROR):this.bufMgr.clear(),this.bitset.clear()}_handleSynOutput(e,t,i,r){this.logger.info(`syn output ${e} http ${t} p2p ${i} time ${r}`)}_handleSynError(e,t,i,r){const{logger:n,config:s}=this;n.warn(`SYN_ERROR ${t}-${i} code ${r}`),r!==ii&&e.hasPartialBuffer&&i>this.loadingSN?n.warn(`syn abort ${i} with partial buffer`):this.requestingMap.delete(ue(i,t)),s.live&&this.checkPeers()}_notifySynthesizer(e,t,i,r,n,s,a=!0){const o=this.requestingMap.get(ue(i,r));o&&this._trySetPeerForSyn(o,e,t,i,r,n,s,a)}_trySetPeerForSyn(e,t,i,r,n,s,a,o=!1){const{logger:l}=this,h=e.segId;if(i&&h&&i!==h)return l.warn(`notifySynthesizer segId ${i} not match ${h}`),!1;if(e.isFull)return!0;if(e.isAlmostDeadline)return!0;if(e.isEmpty){if(e.hasForwardBuffer&&c()){if(e.setReversePeer(t,s))return u(!0,o),!0}else if(e.hasReverseBuffer&&d()&&e.setForwardPeer(t,s))return u(!1,o),!0}else if(!e.hasForwardPeer&&d()){if(e.setForwardPeer(t,s))return u(!1,o),!0}else if(!e.hasReversePeer&&c()&&e.setReversePeer(t,s))return u(!0,o),!0;function u(e,s){s?t.requestDataById(i,r,!0,{level:n,reverse:e}):t.requestDataBySN(r,!1,{level:n,reverse:e})}function d(){return a===$t.PARTIAL_FORWARD||a===$t.COMPLETE}function c(){return a===$t.PARTIAL_REVERSE||a===$t.COMPLETE}return!1}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:i}=this.config;t||i||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,i={level:e};if(t&&!this.config.live){const{currentTime:e}=t;i.pos=Math.round(e)}return i}checkSynthesizer(e,t){const i=ue(e,t),r=this.requestingMap.get(i);r&&(0===r.streamListeners?(this.logger.info(`destroy syn ${i} without listeners`),this.requestingMap.delete(i)):this.logger.info(`keep syn ${i} with listeners`))}setupSynForLoad(e,t,i,r,n){const{forwardPeer:s,reversePeer:a}=this.targetPeers,o=ue(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(r):(l=new fi(this.coordinator,this.logger,e,t,i,this.httpRangeSupported,r),this._setupSynthesizer(l),this.requestingMap.set(o,l)),l.prefetchTimeout&&n<1e3*this.allowP2pLimit&&!s&&!a)return l.setTimeout(0);n>700&&(s&&l.setForwardPeer(s)&&s.requestDataById(i,e,!0,{level:t}),a&&l.setReversePeer(a)&&a.requestDataById(i,e,!0,{level:t,reverse:!0})),l.setTimeout(l.isEmpty?0:n,!0)}}class vi{constructor(t,i,r,n){this.bufferList=[],this.streamListeners=[],this.finished=!1,this.packetSize=u,this.attachments=n%this.packetSize==0?n/this.packetSize:Math.floor(n/this.packetSize)+1,this.pieceMsg={event:e.DC_PIECE,attachments:this.attachments,seg_id:r,sn:t,level:i,size:n,reverse:!1},this.sink=(0,a.h)(0),this.source="HttpStream"}receiveBytes(e,t){e.byteLength&&(this.sink=a.h.concat([this.sink,e]),this.bufferList.push(e),t&&(this.finished=!0),this._notifyStreamListeners(e))}getCompleteBuffer(){return this.sink.buffer}destroy(){this.finished||this._notifyStreamListenersAbort()}addStreamListener(e,t,i){this.streamListeners.push({handler:i,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:i}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((r=>r.peerId!==e||(r.handler(t,i,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let i of this.streamListeners){const{handler:r}=i;r(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:i}=this.pieceMsg;for(let r of this.streamListeners){const{handler:n}=r;n(t,i,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const mi=/^age:\s*[\d.]+\s*$/im;function yi(e,t,i,r){if(!e)return!1;const n=r?.code,s=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(n)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,s):s}const Ei=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?.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return n(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),n(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:s}=i.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&Number.isFinite(n)?n:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,s="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){const n=s||t.response;if(null!=n){i.loading.end=Math.max(self.performance.now(),i.loading.first);const s="arraybuffer"===t.responseType?n.byteLength:n.length;if(i.loaded=i.total=s,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(i,e,n,t),!this.callbacks)return;const o={url:t.responseURL,data:n,code:r};return void this.callbacks.onSuccess(o,i,e,t)}}const a=n.loadPolicy.errorRetry;yi(a,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(a):this.callbacks.onError({code:r,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(yi(e,this.stats.retry,!0))this.retry(e);else{const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=function(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}(e,i.retry),i.retry++,this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&mi.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 Si=class extends pi{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=I(t.segmentBypass)?t.segmentBypass:()=>!1,!0===this.config.httpStreamEnabled?this.streamEnabled=li():this.streamEnabled=!1}async handleGetMediaData(e,i){const{logger:r,engine:n,config:s}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return r.warn(`cannot get frag ${a}`),i.postMessage({action:t.SW_GET_MEDIA});n.currentLevelIndex=l.level;const{sn:h,level:u}=l,d=this.config.segmentId(String(u),h,a,o);if(n.segmentLoadCount++,this.segmentBypass(a,l.tagList))return r.info(`bypass frag ${a}`),i.postMessage({action:t.SW_GET_MEDIA});if(n.segmentLoadCount<s.startFromSegmentOffset)return this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout,!1);const c=d===this.loadingSegId;if(c&&(r.warn(`duplicate request ${d}`),this.prefetchOnly))return i.postMessage({action:t.SW_GET_MEDIA});this.loadingSN=h,n.bufMgr&&(n.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,r.info(`bufMgr found seg sn ${h} segId ${d} size ${l.loaded}`),n.emit(t.FRAG_LOADED,{url:a,sn:h,level:u,segId:d,loaded:l.loaded,duration:l.duration,byP2p:!0,fromPeerId:f.fromPeerId}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:f.data}});if(this.fragLoading=!0,this.prefetchOnly)return r.info(`prefetchOnly, skip p2p load ${d}`),this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout);let g=this.getBufferedDuration();g>this.fragloadTimeout&&(g=this.fragloadTimeout),r.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const v=ue(h,u);if(this.resolveMap.has(h)||c){let e=this.requestingMap.get(v);if(e||c){e&&this.httpRangeSupported&&(r.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let n=setTimeout((()=>{r.info(`notify seg ${h} timeout`),n=-1,i.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{n<0||e&&e.level===u&&(clearTimeout(n),r.info(`notify seg ${e.sn}`),i.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else r.warn(`${h} is requesting, fallback`),i.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,u,d,g)){await this._loadFragByP2p(l,i,h,d,a,u,o,p)||(r.warn(`p2p timeout switch to http load ${d}`),this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,i,r,n,s,a,o=!0){const{sn:l,level:u}=e,d=ue(l,u),c=f(n,h,!0),g={},p=this.streamEnabled&&o?new hi(g):new Ei(g);let v={url:c,responseType:"arraybuffer",..._(s)};const m={timeout:a,loadPolicy:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4}},E={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,i.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,i.postMessage({action:t.SW_GET_MEDIA})},onSuccess:async(s,a)=>{this.fragLoading=!1;const{data:o}=s;let h=a.loading.end-a.loading.start;if(this.logger.info(`HTTP loaded ${r} time ${h} speed ${o.byteLength/h}`),!await this.bufMgr.hasSegOfId(r)){const e=y(o).buffer,t=new z(l,r,e,"",u);await this.bufMgr.putSeg(t),this.reportTraffic(o.byteLength,0,0)}this.segmentBuilderMap.delete(d),e.segId=r,e.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:n,sn:l,level:u,segId:r,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:o}})}};if(this.streamEnabled&&o){let e;E.onBodyStart=t=>{!e&&t>0&&(this.notifyAllPeers(l,u,r,t,$t.PARTIAL_FORWARD),e=new vi(l,u,r,t),this.segmentBuilderMap.has(d)||this.segmentBuilderMap.set(d,e))},E.onUpdate=(t,i,n)=>{if(n)return this.logger.warn(`loadFragByHttp ${r} aborted`),void this.segmentBuilderMap.delete(d);e&&e.receiveBytes(t,i)}}p.load(v,m,E)}async _loadFragByP2p(e,i,r,n,s,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${r} segId ${n} level ${a}`);const u=await this.load(r,n,a,s,o,l);if(u&&u.data){const{data:o,fromPeerId:l,size:d}=u;if(h.info(`p2p loaded segId ${n} level ${a} size ${o.byteLength}`),!await this.bufMgr.hasSegOfId(n)){const e=new z(r,n,o,l,a);h.info(`bufMgr putSeg ${r} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:s,sn:r,level:a,segId:n,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:o,size:d}}),!0}h.warn(`P2P timeout load segId ${n}`);const d=await this.bufMgr.getSegById(n);return!!d&&(this.fragLoading=!1,h.info(`already loaded seg sn ${r} segId ${n}`),i.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:d.data}}),!0)}notifySWMessage(e,i,r){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(i,r);else this.logger.warn(`unknown action ${e}`)}_getFrag(e,t){return t&&(e=`${e}|${t}`),this.fragMap.get(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(){if(!this.engine)return;const{media:e,targetDuration:t}=this.engine;!this.config.live&&e&&t&&(this.currPlaySN=Math.ceil(e.currentTime/t))}load(e,t,i,r,n,s){const{logger:a,config:o}=this;let l={..._(n),proxied:!0,url:r,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,i,t,l,s);const h=new Promise((r=>{const n={resolve:r,sn:e,level:i,segId:t};this.resolveMap.set(e,n)}));return this.targetPeers={},h}isCritical(){return this.resolveMap.has(this.loadingSN)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,i)=>{const{config:r,logger:n}=this,{segId:s,sn:a,data:o,level:l}=t,{speed:h,time:u,http:d,p2p:c}=i;this._handleSynOutput(s,d,c,u);const f=this.resolveMap.has(a);f&&(this.fragLoading=!1);if(r.validateSegment(s,new Uint8Array(o))){this.bitset.has(a,l)||this.reportTraffic(d,c,h);const i=e.getFromPeerId();if(f){n.info(`receive criticalSeg seg_id ${s}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:i})}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t))}else if(n.error(`segment ${s} validate failed`),f){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(ue(a,l)),r.live&&this.checkPeers()})).on(t.SYN_ERROR,((t,i)=>{const{sn:r,level:n}=t;if(this.resolveMap.has(r)){const e=this.resolveMap.get(r);this.resolveMap.delete(r),e.resolve()}this._handleSynError(e,n,r,i)}))}_handleDCHave(e,t,i,r,n,s){this._notifySynthesizer(e,r,t,i,n,s,this.resolveMap.has(t)),this.config.live&&W((()=>{this.checkPeers()}))}},Ti="2.13.0";class Li extends kt{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},i=null){super(e,i),this.swSupported=self.isSecureContext,this.levels=[],this.bypassLevels=[],this.currentLevelIndex=0,this.currentSrc="",this.swVersion="",this.media=se(this.config.mediaElem),this.workerKeepAliveInterval=null,this.fragMap=new Map,this.engineName=Li.name,Li.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),i&&(i.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),i.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:r,signalId:n,browserInfo:s}=this.setup();if(this.onLevelLoaded=e=>{const{config:i}=this,a=e.live;i.live=a,this.segmentLoadCount=0,this.targetDuration=e.averagetargetduration,this.browserInfo={...s,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${r(this.currentSrc)}|${n}[${Z.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsSwP2pEngine"),o.info(`engine version: ${re.version} hls-proxy version: ${this.swVersion}`),o.info(`channel ${this.channel}`),a||(i.startSN=e.startSN,i.endSN=e.endSN,o.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(t.LEVEL_LOADED,this.onLevelLoaded)},0===this.config.httpLoadTime&&(this.config.live?this.on(t.LEVEL_LOADED,(e=>{const{fragments:t,averagetargetduration:i,startSN:r}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,i,r)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,i)=>{this.multiBitrate=e.length>1,this.currentSrc=i,this.off(t.MANIFEST_PARSED,this.onManifestParsed)},this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{this.curTsUri=e;const{config:t}=this;!this.rangeTested&&t.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,t.logger&&t.logger.info(JSON.stringify({engine:this.engineName,...this.browserInfo}))),this.segmentLoadCount>=t.startFromSegmentOffset&&this.resumeTracker()},this.on(t.FRAG_LOADED,this.onFragLoaded),this.swSupported){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:i,data:r}=e.data;if(!i)return;if(i===t.SW_DEBUG){const{level:e,text:t}=r;return void(this.logger&&this.logger[e](`hls-proxy ${this.swVersion}: ${t}`))}const n=e.ports[0];if(n){if(this.logger&&this.logger.info(`engine onmessage action ${i}`),n.postMessage({action:i,pong:!0}),!this.p2pEnabled||!r)return n.postMessage({action:i});if(i===t.SW_GET_PLAYLIST)this.handleGetPlaylist(r,n);else{if(!this.scheduler)return n.postMessage({action:i});this.scheduler.notifySWMessage(i,r,n)}}else this.logger&&this.logger.error(`sender not found in action ${i}`)}}this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}watchRebuffering(e){this.offEventRebuffer=function(e,t){let i=null;const r=()=>{i||(i=setTimeout((()=>{t()}),2500))},n=()=>{null!=i&&(clearTimeout(i),i=null)};return e.addEventListener("waiting",r),e.addEventListener("playing",n),()=>{e.removeEventListener("waiting",r),e.removeEventListener("playing",n)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,i,r=!1){const{config:n,logger:s}=this,{url:a,redirectedUrl:o,text:l,ver:u}=e;return this.swVersion=u,-1===function(e,t){for(var i=e.split("."),r=t.split("."),n=0;n<Math.max(i.length,r.length);n++){var s=parseInt(i[n]||0),a=parseInt(r[n]||0);if(s<a)return-1;if(s>a)return 1}return 0}(u,Ti)?(console.warn(`hls-proxy.js version should >= ${Ti}`),i.postMessage({action:t.SW_GET_PLAYLIST})):this.bypassLevels.indexOf(b(a))>=0?(console.warn("bypass audio track"),s&&s.warn("bypass audio track"),i.postMessage({action:t.SW_GET_PLAYLIST})):(i.postMessage({action:t.SW_GET_PLAYLIST,data:{active:!0,debug:s&&s.isDebugLevel,text:l,redirectedUrl:o}}),this._parsePlaylist(l,b(a),o,r),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!n.live&&t()){const i=new URL(e.scope);this.pathname=i.pathname+h;const r=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;s&&(s.error(t),s.report(t,"SWKeepAlive",this.peerId,"2.14.3"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,i)=>{fetch(`${e}/keepalive/`).then((e=>{if(e.ok)return e.text();throw new Error("keepalive failed")})).then((e=>{if(""!==e.trim())throw new Error("not valid keepalive response");t()})).catch((e=>{i(e)}))}))).catch((e=>{r(e)})):r("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,i,r,n=!1){const s=i;r&&(i=r);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let r=0;const o=Kt.parseLevelPlaylist(e,i);this.levels.length>0?(r=this.levels.indexOf(b(o.url)),-1===r?(this.restartP2p(),this.currentSrc=s,r=0):this.currentLevelIndex=r):(""!==this.currentSrc&&s!==this.currentSrc&&this.restartP2p(),this.currentSrc=s,this.levels=[b(i)]),this.emit(t.LEVEL_LOADED,o),a.live&&S(this.fragMap,200),o.fragments.forEach((e=>{e.level=r;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const i=e.byteRange;2===i.length&&(t=`${t}|bytes=${i[0]}-${i[1]-1}`),this.fragMap.set(t,e)})),!n&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(b(i),e)}else{const r=Kt.parseMasterPlaylist(e,i);""!==this.currentSrc&&this.restartP2p(),r.length>0&&(r.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=r.map((e=>b(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{Kt.parseMasterPlaylistMedia(e,i,t).forEach((e=>{e.url&&this.bypassLevels.push(b(e.url))}))}))),this.emit(t.MANIFEST_PARSED,r,s)}this._setupSegmentId()}async handleGetPlaylist(e,i){const{config:r,logger:n,scheduler:s}=this,{url:a}=e,o=b(a);if(s&&s.playlistInfo.has(o)){const t=await s.getPlaylistFromPeer(o);if(t&&t.data){const{data:r,seq:s}=t;return n&&n.info(`got playlist from peer seq ${s}`),void this.handlePlaylist({text:r,...e},i,!0)}}try{const{text:r,redirectedUrl:s}=await this._loadPlaylistByHttp(a);if(!function(e){return 0===e.indexOf("#EXTM3U")}(r))return n&&n.warn(`not m3u8: ${r}`),i.postMessage({action:t.SW_GET_PLAYLIST});this.handlePlaylist({text:r,redirectedUrl:s,...e},i)}catch(e){i.postMessage({action:t.SW_GET_PLAYLIST})}}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let e="sw is not supported";return E||(e="https is required when using ServiceWorker",console.warn(e)),Promise.reject(e)}return this.media=se(t.mediaElem),this.media||e&&e.warn("no video element found"),Di.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,i)=>{const{serviceWorker:r}=navigator;r||i(e),r.getRegistration().then((r=>{r?r.unregister().then(t).catch(i):i(e)}))}))}async _init(e,t){const{logger:i,config:r}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.mediaTimer=setInterval((()=>{const e=()=>this.hlsjs&&this.hlsjs.media;if(this.media){const t=e();t&&this.media!==t&&(this.media=t),clearInterval(this.mediaTimer),this.rubufferTimer=setTimeout((()=>{this.watchRebuffering(this.media)}),15e3)}else this.media=e()||se(r.mediaElem)}),3e3);let n=new Si(this,r);n.fragMap=this.fragMap;try{await super._init(e,n,t)}catch(e){return void(i&&i.error(e))}n.server=this.fetcher,this.scheduler=n}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 Pt&&(this.tracker.stopP2P(),this.tracker=null,this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.trackerTried=!1)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(t.MANIFEST_PARSED),this.removeAllListeners(t.LEVEL_LOADED),this.removeAllListeners(t.FRAG_LOADED),clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null}destroy(){this.swSupported&&(navigator.serviceWorker.onmessage=void 0),super.destroy()}async _loadPlaylistByHttp(e){const t=f(e,h,!0),i=await fetch(t);return{text:await i.text(),redirectedUrl:i.redirected?i.url:void 0}}}const _i=Li;function bi(e,t,i="main"){return"main"!==i}function Ai(e,t,i){let r,n,s;const a=performance.now();s=a,n=i?s-i.getMeanTimeToLoaded(t):a-200,r=n-100,e.trequest=r,e.tfirst=n,e.tload=s,e.loading={first:r,start:n,end:s},e.loaded=t,e.total=t}const Ii=class extends pi{constructor(e,t){super(e,t),this.isHlsjs=!0,this.waitingPeers=0,this.waitingSeg={},this.requestedSet=new Set}updatePlaySN(e){this.currPlaySN=e}load(e,t,i){const{logger:r,config:n}=this;this.context=e;const{rangeStart:s,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:u,level:d}=l;this.callbacks=i,this.criticalSeg={sn:u,level:d,segId:h};let c=e.defaultTimeout-1e3*n.httpLoadTime;const f={rangeStart:Number(s),rangeEnd:Number(a),url:o,httpLoadTime:1e3*n.httpLoadTime,xhrSetup:n.xhrSetup,segId:h,headers:Object.keys(e.headers||{}).length>0?e.headers:void 0};this.setupSynForLoad(u,d,h,f,c),this.targetPeers={}}isCritical(){return!(!this.criticalSeg||this.criticalSeg.segId!==this.loadingSegId)}addPeer(e){super.addPeer(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler")}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,i)=>{const{config:r,logger:n}=this,{segId:s,sn:a,data:o,level:l}=t,{speed:h,time:u,http:d,p2p:c}=i;this._handleSynOutput(s,d,c,u);const f=this.criticalSeg&&this.criticalSeg.segId===s;if(r.validateSegment(s,new Uint8Array(o))){this.bitset.has(a,l)||this.reportTraffic(d,c,h);const i=e.getFromPeerId();if(f){n.info(`receive criticalSeg seg_id ${s}`),this.criticalSeg=null;const{frag:e}=this.context;e.fromPeerId=i,e.loadByP2P=!0,this.callbacks.onSuccess({data:o,url:this.context.url},{},this.context),this.callbacks=void 0}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t))}else n.error(`segment ${s} validate failed`),f&&this.callbacks.onTimeout({},this.context,null);this.requestingMap.delete(ue(a,l)),r.live&&this.checkPeers()})).on(t.SYN_ERROR,((t,i)=>{const{sn:r,level:n}=t;this.criticalSeg&&this.criticalSeg.sn===r&&(this.criticalSeg=null,this.callbacks.onTimeout({},this.context,null)),this._handleSynError(e,n,r,i)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:i,segId:r})=>{this.criticalSeg&&this.criticalSeg.segId===r&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:i},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:i,level:r})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,i&&this.checkSynthesizer(e,r)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:i,level:r})=>{this.fragLoading=!1,i||this.checkSynthesizer(e,r)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,i,r,n,s){this._notifySynthesizer(e,r,t,i,n,s,this.criticalSeg&&this.criticalSeg.segId===r),this.config.live&&W((()=>{this.checkPeers()}))}};class Ri extends kt{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=Ri.name,this._onFragLoading=this._onFragLoading.bind(this),this._onFragLoaded=this._onFragLoaded.bind(this),this._onFragChanged=this._onFragChanged.bind(this),this._onHlsError=this._onHlsError.bind(this),this._onLevelUpdated=this._onLevelUpdated.bind(this);const{channelIdMaker:i,signalId:r,browserInfo:n}=this.setup(),s=(t,a)=>{if(!a)return;const{config:o}=this,l=a.details,h=l.live;this._startEngine(this.hlsjs.url,h,n,i,r,l),e.off(this.HLSEvents.LEVEL_LOADED,s)};this._updateHlsEventsHandlers(),e.on(this.HLSEvents.LEVEL_LOADED,s);const a=(e,t)=>{if(!t)return;const{config:i}=this,{fragments:r,averagetargetduration:n,startSN:s}=t.details;i.httpLoadTime=this.determineHttpLoadTime(r,n,s)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,i)=>{this._setupSegmentId();const r=i.levels.length;this.multiBitrate=r>1,e.off(this.HLSEvents.MANIFEST_PARSED,o)};e.on(this.HLSEvents.MANIFEST_PARSED,o),e.on(this.HLSEvents.DESTROYING,(()=>{e.off(this.HLSEvents.LEVEL_LOADED,a),this.destroy()}))}_startEngine(e,t,i,r,n,s={}){const{config:a}=this;a.live=t,this.browserInfo={...i,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${r(e)}|${n}[${Z.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsjsP2pEngine"),this.logger=o,o.info(`channel ${this.channel}`),t||(a.startSN=s.startSN,a.endSN=s.endSN,o.info(`startSN ${s.startSN} endSN ${s.endSN}`)),this._init(this.channel,this.browserInfo)}async _init(e,t){const{logger:i,config:r}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const n=new Ii(this,r);try{await super._init(e,n,t)}catch(e){return void i.error(e)}this.hlsjs.config.fLoader=function(e,t,i,r){const n=r.httpStreamEnabled&&li();return class extends(s()){constructor(s){super(),this.logger=i,this.isHlsV0=r.isHlsV0,this.bufMgr=e.bufMgr,this.httpLoader=n?new hi(s):new Ei(s),this.p2pEnabled=r.p2pEnabled,this.isLive=r.live,this.scheduler=e,this.fetcher=t,this.segmentId=r.segmentId,this.blockTypes=r.p2pBlackList,this.stats=this.httpLoader.stats||D(),this.enableWorker=s.enableWorker,this.segmentBypass=I(r.segmentBypass)?r.segmentBypass:()=>!1,this.prefetchOnly=r.prefetchOnly,this.startFromSegmentOffset=r.startFromSegmentOffset}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,i){const{logger:r,scheduler:n}=this,{url:s,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,s,t)}const c=()=>(a.loadByHTTP=!0,this.httpLoader.load(e,t,i));if(!s||!Number.isInteger(l)||bi(0,this.blockTypes,h)||this.segmentBypass(s,u))return r.info(`HTTP load blockType ${s}`),c();if(this.fetcher.increMediaRequests(),this.isLive&&n.requestedSet.has(d))return r.warn(`HTTP load duplicated ${s}`),c();if(n.engine.segmentLoadCount<this.startFromSegmentOffset)return c();t.maxRetry=2;const f=n.getBufferedDuration(),g=await this.bufMgr.getSegById(d);if(this.p2pEnabled&&g){r.info(`bufMgr found seg sn ${l} segId ${d} level ${o} size ${g.size}`);let t=y(g.data).buffer,s={url:e.url,data:t};return Ai(this.stats,g.size,n.coordinator),a.loaded=g.size,a.loadByP2P=!0,a.fromPeerId=g.fromPeerId,void W((()=>{!this.isHlsV0&&i.onProgress&&i.onProgress(this.stats,e,s.data),i.onSuccess(s,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&n.hasAndSetTargetPeer(l,o,d,f)?this.loadFragByP2p(e,t,i,d,f):(r.info(`fragLoader load ${d} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,i,d))}loadFragByHttp(e,t,i,r){const{logger:s,scheduler:a}=this,{segmentBuilderMap:o}=a,l=e.frag,{sn:h,level:u}=l,d=ue(h,u);if(n){let e;i.onUpdate=(t,i,n)=>{if(n)return s.warn(`loadFragByHttp ${r} aborted`),void o.delete(d);e&&e.receiveBytes(t,i)},i.onBodyStart=t=>{!e&&t>0&&(e=new vi(h,u,r,t),o.has(d)||o.set(d,e),a.notifyAllPeers(h,u,r,t,$t.PARTIAL_FORWARD))}}const c=i.onSuccess;i.onSuccess=async(e,t,i)=>{a.coordinator.addLoaderHttpSpeed(t.tload-t.tfirst,t.loaded);const{data:n}=e;let l=t.tload-t.trequest;if(s.info(`HTTP loaded ${r} time ${l} speed ${t.total/l}`),!await this.bufMgr.hasSegOfId(r)){const e=y(n).buffer,t=new z(h,r,e,this.fetcher.peerId,u);await this.bufMgr.putSeg(t)}o.delete(d),this.fetcher.reportFlow(t.total),c(e,t,i)};const f=i.onProgress;f&&(i.onProgress=(e,t,i)=>{l.loaded=e.total,f(e,t,i&&this.enableWorker?y(i).buffer:i)}),e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,i)}loadFragByP2p(t,i,r,n,s){const{logger:a}=this,o=t.frag;let l;l=i.loadPolicy?i.loadPolicy.maxTimeToFirstByteMs:i.timeout,(!l||l>1e3*s)&&(l=1e3*s),t.defaultTimeout=l,this.scheduler.load(t,i,r);const h=r.onSuccess,u=r.onTimeout;r.onTimeout=(e,t)=>{a.warn(`P2P timeout switched to HTTP load ${o.relurl} at ${o.sn}`),r.onSuccess=h,this.loadFragByHttp(t,i,r,n),r.onTimeout=u},r.onSuccess=async(t,i,s)=>{const{data:l}=t;if(Ai(i=this.stats,l.byteLength,e.coordinator),!await this.bufMgr.hasSegOfId(n)){const e=y(l).buffer,t=new z(o.sn,n,e,o.fromPeerId||this.fetcher.peerId,o.level);await this.bufMgr.putSeg(t)}o.loadByP2P||this.fetcher.reportFlow(i.total),o.loaded=i.loaded,a.info(`${o.loadByP2P?"P2P":"HTTP"} loaded segment id ${n}`),!this.isHlsV0&&r.onProgress&&r.onProgress(i,s,l),h(t,i,s)}}}}(n,this.fetcher,i,r),r.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,i){return class extends(s()){constructor(r){super(),this.logger=t,this.xhrLoader=new r.loader(r),this.p2pEnabled=i.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||D()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,i){const{logger:r}=this,{url:n}=e,s=b(n),a=i.onSuccess;if(i.onSuccess=(e,t,i)=>{this.scheduler&&!i.loadedByPeer&&this.scheduler.broadcastPlaylist(s,e.data),a(e,t,i)},this.scheduler&&this.scheduler.playlistInfo.has(s)){const t=await this.scheduler.getPlaylistFromPeer(s);if(t&&t.data){const{data:s,seq:a}=t;r.info(`got playlist from peer seq ${a}`),Ai(this.stats,s.length);let o={url:n,data:s};return e.loadedByPeer=!0,void W((()=>{i.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,i)}}}(n,i,r))}_onFragLoading(e,i){const r=i.frag;let{sn:n,level:s,segId:a}=r;if(!bi(r.url,this.config.p2pBlackList,r.type)&&Number.isInteger(n)){if(this.logger&&this.logger.info("loading frag "+n),this.bufMgr&&(this.bufMgr.loadingSN=n),!a){let e;r._byteRange&&(e="bytes="+r._byteRange[0]+"-"+r._byteRange[1]);let t=r.url;this._setupSegmentId(),a=r.segId=this.config.segmentId(String(s),r.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:n,segId:a,byHttp:r.loadByHTTP,level:s})}}_onLevelUpdated(e,t){const{details:i}=t,{hlsjs:r,config:n}=this,{targetduration:s,live:a,fragments:o}=i,l=o.length;if(a&&r&&"main"===o[0].type&&!(l<=4)&&(n.isHlsV0||!r.userConfig.liveSyncDuration&&!r.userConfig.liveSyncDurationCount)){const e=l<=9?l-1:l-2;r.config.liveSyncDurationCount!==e&&(r.config.liveSyncDurationCount=e)}}_onFragLoaded(e,i){if(this.segmentLoadCount++,!this.p2pEnabled)return;const{frag:r}=i;this.curTsUri=r.url;const{sn:n,segId:s,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:u,url:d}=r,{config:c,logger:f}=this;this.tracker&&this.tracker.scheduler&&(T(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(s)),bi(r.url,c.p2pBlackList,r.type)||(this.bufMgr&&this.bufMgr.loadingSN>=0&&this.emit(t.FRAG_LOADED,{url:d,sn:n,level:l,segId:s,loaded:a,duration:o,byP2p:!!u,fromPeerId:h}),!this.rangeTested&&c.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,f.info(JSON.stringify({engine:this.engineName,hlsjs:this.hlsjsVersion,...this.browserInfo})))),this.segmentLoadCount>=c.startFromSegmentOffset&&this.resumeTracker()}_onFragChanged(e,i){const{frag:r}=i;if(!bi(r.url,this.config.p2pBlackList,r.type)){this.logger.info("frag changed: "+r.sn);const{sn:e,duration:i}=r;this.emit(t.FRAG_CHANGED,{sn:e,duration:i})}}get currentLevel(){const{currentLevel:e}=this.hlsjs;return e>=0?e:0}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}_updateHlsEventsHandlers(e=!1){const t=this.hlsjs;if(!t)return;const i=e?"off":"on";t[i](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[i](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[i](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[i](this.HLSEvents.ERROR,this._onHlsError),t[i](this.HLSEvents.LEVEL_UPDATED,this._onLevelUpdated)}destroy(){this._updateHlsEventsHandlers(!0),super.destroy()}_setupSW(){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:t}=e.data,i=e.ports[0];if(i)return i.postMessage({action:t,pong:!0}),i.postMessage({action:t,data:{bypass:!0}})}}}const Pi=Ri;class ki{static get Events(){return t}static get TrackerZone(){return re.TrackerZone}static isSupported(){return re.isSupported()&&(ne()||_i.isServiceWorkerSupported())}static isServiceWorkerSupported(){return _i.isServiceWorkerSupported()}static isMSESupported(){return ne()}static getBrowser(){return Q().getBrowser()}static get ServiceWorkerEngine(){return _i}static get HlsjsEngine(){return Pi}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return ki.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:i}={}){const{serviceWorker:r}=navigator;return!r||i?Promise.resolve():r.getRegistration().then((i=>i||Promise.race([r.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,i)=>{const r=e.installing||e.waiting||e.active,n=()=>"activated"===r.state&&(r.removeEventListener("statechange",n),t(e),!0);n()||r.addEventListener("statechange",n)}))}(e))).catch((()=>{Promise.resolve()})),v(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const i=()=>{this._realEngine=new Pi(t,e)},r=()=>{this._realEngine=new _i(e,t)};"1"!==c("_sw")?e.proxyFirst&&t?_i.isServiceWorkerSupported()?r():i():!e.proxyOnly&&ne()&&t?i():r():r()}get realEngine(){return this._realEngine}get engineName(){return this._realEngine.constructor.name}once(e,t){return this._realEngine.once(e,t)}on(e,t){return this._realEngine.on(e,t)}off(e,t){return this._realEngine.off(e,t)}removeListener(e,t){return this._realEngine.removeListener(e,t)}removeAllListeners(e){return this._realEngine.removeAllListeners(e)}set p2pEnabled(e){this._realEngine.p2pEnabled=e}get p2pEnabled(){return this._realEngine.p2pEnabled}enableP2P(){this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}async registerServiceWorker(){return I(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return I(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return re.version}}ki.version=re.version,ki.protocolVersion=Z.VERSION,"object"==typeof self&&(self.P2PEngineHls=ki);const Di=ki;var wi=i(251),Ci=i.n(wi);const Mi={maxBufferLength:12},Oi={maxBufferLength:40};class xi extends(Ci()){static get P2PEvents(){return Di.Events}static get P2pEngine(){return Di}constructor(e={}){let t=e.p2pConfig||{};const i=!1===t.live?Oi:Mi;let r=JSON.parse(JSON.stringify(i));r.maxBufferSize=0,r.enableWorker=!1;for(let t in e)"p2pConfig"!==t&&(r[t]=e[t]);super(r),this._restartEvent=()=>{this.restartP2P()},Di.isSupported()&&(this._p2pEngine=new Di({...t,hlsjsInstance:this}),this._p2pEngine.on(Di.Events.RESTART_P2P,this._restartEvent)),this.on(Ci().Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(Di.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(Di.Events.RESTART_P2P,this._restartEvent))}}xi.engineVersion=Di.version,xi.protocolVersion=Di.protocolVersion,xi.WEBRTC_SUPPORT=Di.isSupported();const Fi=xi})(),r=r.default})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(this,(()=>(()=>{var e={415:e=>{"use strict";var t,i="object"==typeof Reflect?Reflect:null,r=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(i,r){function n(i){e.removeListener(t,s),r(i)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),i([].slice.call(arguments))}p(e,t,s,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&p(e,"error",t,i)}(e,n,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.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?s.defaultMaxListeners:e._maxListeners}function h(e,t,i,r){var n,s,a,h;if(o(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]),void 0===a)a=s[t]=i,++e._eventsCount;else if("function"==typeof a?a=s[t]=r?[i,a]:[a,i]:r?a.unshift(i):a.push(i),(n=l(e))>0&&a.length>n&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,h=u,console&&console.warn&&console.warn(h)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},n=u.bind(r);return n.listener=i,r.wrapFn=n,n}function c(e,t,i){var r=e._events;if(void 0===r)return[];var n=r[t];return void 0===n?[]:"function"==typeof n?i?[n.listener||n]:[n]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(n):g(n,n.length)}function f(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function g(e,t){for(var i=new Array(t),r=0;r<t;++r)i[r]=e[r];return i}function p(e,t,i,r){if("function"==typeof e.on)r.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function n(s){r.once&&e.removeEventListener(t,n),i(s)}))}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),s.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},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(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},s.prototype.getMaxListeners=function(){return l(this)},s.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){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=s[e];if(void 0===l)return!1;if("function"==typeof l)r(l,this,t);else{var h=l.length,u=g(l,h);for(i=0;i<h;++i)r(u[i],this,t)}return!0},s.prototype.addListener=function(e,t){return h(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return h(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,d(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,d(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,r,n,s,a;if(o(t),void 0===(r=this._events))return this;if(void 0===(i=r[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,n=s;break}if(n<0)return this;0===n?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,n),1===i.length&&(r[e]=i[0]),void 0!==r.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,r;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var n,s=Object.keys(i);for(r=0;r<s.length;++r)"removeListener"!==(n=s[r])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},s.prototype.listeners=function(e){return c(this,e,!0)},s.prototype.rawListeners=function(e){return c(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(h.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+s.path;h.path=a.normalizePath(d)}else h.path=o.path,s.params||(h.params=o.params,s.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(h)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(s,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()},251:e=>{!function t(i){var r;r=function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=Array(t);i<t;i++)r[i]=e[i];return r}function r(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,g(r.key),r)}}function n(e,t,i){return t&&r(e.prototype,t),i&&r(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(t,i){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,i){if(t){if("string"==typeof t)return e(t,i);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,i):void 0}}(t))||i){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function a(e,t,i){return(t=g(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},o.apply(null,arguments)}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function h(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,f(e,t)}function u(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(u=function(){return!!e})()}function d(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function c(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?d(Object(i),!0).forEach((function(t){a(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):d(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function f(e,t){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},f(e,t)}function g(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function p(e){var t="function"==typeof Map?new Map:void 0;return p=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return function(e,t,i){if(u())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var n=new(e.bind.apply(e,r));return i&&f(n,i.prototype),n}(e,arguments,l(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),f(i,e)},p(e)}var v,m,y={exports:{}},E=(v||(v=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,r,s,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new n(r,s||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,n=[];if(0===this._eventsCount)return n;for(r in e=this._events)t.call(e,r)&&n.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,s=r.length,a=new Array(s);n<s;n++)a[n]=r[n].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,n,s,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,h,u=this._events[o],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,n),!0;case 5:return u.fn.call(u.context,t,r,n,s),!0;case 6:return u.fn.call(u.context,t,r,n,s,a),!0}for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var c,f=u.length;for(h=0;h<f;h++)switch(u[h].once&&this.removeListener(e,u[h].fn,void 0,!0),d){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,t);break;case 3:u[h].fn.call(u[h].context,t,r);break;case 4:u[h].fn.call(u[h].context,t,r,n);break;default:if(!l)for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u[h].fn.apply(u[h].context,l)}}return!0},o.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,r,n){var s=i?i+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn!==t||n&&!o.once||r&&o.context!==r||a(this,s);else{for(var l=0,h=[],u=o.length;l<u;l++)(o[l].fn!==t||n&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[s]=1===h.length?h[0]:h:a(this,s)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(y)),y.exports),S=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(E),T={exports:{}},L=(m||(m=1,function(e,t){var i,r,n,s,a;i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(h.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+s.path;h.path=a.normalizePath(d)}else h.path=o.path,s.params||(h.params=o.params,s.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(h)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(s,"")).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}(T)),T.exports),_=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},b=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=A},A=Number.MAX_SAFE_INTEGER||9007199254740991,I=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}({}),R=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}({}),k="manifest",D="level",w="audioTrack",C="subtitleTrack",M="main",O="audio",x="subtitle",F=function(){function e(e,t,i){void 0===t&&(t=0),void 0===i&&(i=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}var t=e.prototype;return t.sample=function(e,t){var i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),N=function(){function e(e,t,i,r){void 0===r&&(r=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new F(e),this.fast_=new F(t),this.defaultTTFB_=r,this.ttfb_=new F(e)}var t=e.prototype;return t.update=function(e,t){var i=this.slow_,r=this.fast_,n=this.ttfb_;i.halfLife!==e&&(this.slow_=new F(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new F(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new F(e,n.getEstimate(),n.getTotalWeight()))},t.sample=function(e,t){var i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)},t.sampleTTFB=function(e){var t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},n(e,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),B=function(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="["+e+"]:";this.trace=U,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)},U=function(){},G={trace:U,debug:U,log:U,warn:U,info:U,error:U};function H(){return o({},G)}function V(e,t,i){return t[e]?t[e].bind(t):function(e,t){var i=self.console[e];return i?i.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):U}(e,i)}var K=H();function W(e,t,i){var r=H();if("object"==typeof console&&!0===e||"object"==typeof e){var n=["debug","log","info","warn","error"];n.forEach((function(t){r[t]=V(t,e,i)}));try{r.log('Debug logs enabled for "'+t+'" in hls.js version 1.6.2')}catch(e){return H()}n.forEach((function(t){K[t]=V(t,e)}))}else o(K,r);return r}var $=K;function q(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function j(e,t){var i=Object.keys(e),r=Object.keys(t),n=i.length,s=r.length;return!n||!s||n===s&&!i.some((function(e){return-1===r.indexOf(e)}))}function Y(e,t){if(void 0===t&&(t=!1),"undefined"!=typeof TextDecoder){var i=new TextDecoder("utf-8").decode(e);if(t){var r=i.indexOf("\0");return-1!==r?i.substring(0,r):i}return i.replace(/\0/g,"")}for(var n,s,a,o=e.length,l="",h=0;h<o;){if(0===(n=e[h++])&&t)return l;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:s=e[h++],l+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=e[h++],a=e[h++],l+=String.fromCharCode((15&n)<<12|(63&s)<<6|63&a)}}return l}var z=function(e){for(var t="",i=0;i<e.length;i++){var r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t},X=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}},Q="audio",J="video",Z="audiovideo",ee=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 i,r=e.split("@",2);i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]},t.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[Q]=null,e[J]=null,e[Z]=null},n(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={})[Q]=null,e[J]=null,e[Z]=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 X),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=L.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}])}();function te(e){return"initSegment"!==e.sn}var ie=function(e){function t(t,i){var r;return(r=e.call(this,i)||this)._decryptdata=null,r._programDateTime=null,r._ref=null,r._bitrate=void 0,r.rawProgramDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.playlistOffset=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=t,r}h(t,e);var i=t.prototype;return i.addStart=function(e){this.setStart(this.start+e)},i.setStart=function(e){this.start=e,this._ref&&(this._ref.start=e)},i.setDuration=function(e){this.duration=e,this._ref&&(this._ref.duration=e)},i.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},i.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},i.setElementaryStreamInfo=function(e,t,i,r,n,s){void 0===s&&(s=!1);var a=this.elementaryStreams,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,n)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:s}},n(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],i=this.byteRange[1];if(_(t)&&_(i))return i-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{var t=Object.keys(this.levelkeys);if(1===t.length)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),i=t.length;if(i>1||1===i&&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 te(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(ee),re=function(e){function t(t,i,r,n,s){var a;(a=e.call(this,r)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.duration=t.decimalFloatingPoint("DURATION"),a.gap=t.bool("GAP"),a.independent=t.bool("INDEPENDENT"),a.relurl=t.enumeratedString("URI"),a.fragment=i,a.index=n;var o=t.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,s),s&&(a.fragOffset=s.fragOffset+s.duration),a}return h(t,e),n(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)}}])}(ee);function ne(e,t){var i=Object.getPrototypeOf(e);if(i)return Object.getOwnPropertyDescriptor(i,t)||ne(i,t)}var se=Math.pow(2,32)-1,ae=[].push,oe={video:1,audio:2,id3:3,text:4};function le(e){return String.fromCharCode.apply(null,e)}function he(e,t){var i=e[t]<<8|e[t+1];return i<0?65536+i:i}function ue(e,t){var i=ce(e,t);return i<0?4294967296+i:i}function de(e,t){var i=ue(e,t);return(i*=Math.pow(2,32))+ue(e,t+4)}function ce(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function fe(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function ge(e,t){var i=[];if(!t.length)return i;for(var r=e.byteLength,n=0;n<r;){var s=ue(e,n),a=s>1?n+s:r;if(le(e.subarray(n+4,n+8))===t[0])if(1===t.length)i.push(e.subarray(n+8,a));else{var o=ge(e.subarray(n+8,a),t.slice(1));o.length&&ae.apply(i,o)}n=a}return i}function pe(e){var t=[],i=e[0],r=8,n=ue(e,r);r+=4;var s=0,a=0;0===i?(s=ue(e,r),a=ue(e,r+4),r+=8):(s=de(e,r),a=de(e,r+8),r+=16),r+=2;var o=e.length+a,l=he(e,r);r+=2;for(var h=0;h<l;h++){var u=r,d=ue(e,u);u+=4;var c=2147483647&d;if(1==(2147483648&d)>>>31)return $.warn("SIDX has hierarchical references (not supported)"),null;var f=ue(e,u);u+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+c-1}}),o+=c,r=u+=4}return{earliestPresentationTime:s,timescale:n,version:i,referencesCount:l,references:t}}function ve(e){for(var t=[],i=ge(e,["moov","trak"]),r=0;r<i.length;r++){var n=i[r],s=ge(n,["tkhd"])[0];if(s){var a=s[0],o=ue(s,0===a?12:20),l=ge(n,["mdia","mdhd"])[0];if(l){var h=ue(l,0===(a=l[0])?12:20),u=ge(n,["mdia","hdlr"])[0];if(u){var d=le(u.subarray(8,12)),f={soun:Q,vide:J}[d],g=me(ge(n,["mdia","minf","stbl","stsd"])[0]);f?(t[o]={timescale:h,type:f,stsd:g},t[f]=c({timescale:h,id:o},g)):t[o]={timescale:h,type:d,stsd:g}}}}}return ge(e,["moov","mvex","trex"]).forEach((function(e){var i=ue(e,4),r=t[i];r&&(r.default={duration:ue(e,12),flags:ue(e,20)})})),t}function me(e){var t,i=e.subarray(8),r=i.subarray(86),n=le(i.subarray(4,8)),s=n,a="enca"===n||"encv"===n;if(a){var o=ge(i,[n])[0];ge(o.subarray("enca"===n?28:78),["sinf"]).forEach((function(e){var t=ge(e,["schm"])[0];if(t){var i=le(t.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=ge(e,["frma"])[0];r&&(s=le(r))}}}))}var l=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":var h=ge(r,["avcC"])[0];h&&h.length>3&&(s+="."+Se(h[1])+Se(h[2])+Se(h[3]),t=ye("avc1"===l?"dva1":"dvav",r));break;case"mp4a":var u=ge(i,[n])[0],d=ge(u.subarray(28),["esds"])[0];if(d&&d.length>7){var c=4;if(3!==d[c++])break;c=Ee(d,c),c+=2;var f=d[c++];if(128&f&&(c+=2),64&f&&(c+=d[c++]),4!==d[c++])break;c=Ee(d,c);var g=d[c++];if(64!==g)break;if(s+="."+Se(g),c+=12,5!==d[c++])break;c=Ee(d,c);var p=d[c++],v=(248&p)>>3;31===v&&(v+=1+((7&p)<<3)+((224&d[c])>>5)),s+="."+v}break;case"hvc1":case"hev1":var m=ge(r,["hvcC"])[0];if(m&&m.length>12){var y=m[1],E=["","A","B","C"][y>>6],S=31&y,T=ue(m,2),L=(32&y)>>5?"H":"L",_=m[12],b=m.subarray(6,12);s+="."+E+S,s+="."+T.toString(16).toUpperCase(),s+="."+L+_;for(var A="",I=b.length;I--;){var R=b[I];(R||A)&&(A="."+R.toString(16).toUpperCase()+A)}s+=A}t=ye("hev1"==l?"dvhe":"dvh1",r);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=ye(s,r)||s;break;case"vp09":var P=ge(r,["vpcC"])[0];if(P&&P.length>6){var k=P[4],D=P[5],w=P[6]>>4&15;s+="."+Te(k)+"."+Te(D)+"."+Te(w)}break;case"av01":var C=ge(r,["av1C"])[0];if(C&&C.length>2){var M=C[1]>>>5,O=31&C[1],x=C[2]>>>7?"H":"M",F=(64&C[2])>>6,N=(32&C[2])>>5,B=2===M&&F?N?12:10:F?10:8,U=(16&C[2])>>4,G=(8&C[2])>>3,H=(4&C[2])>>2,V=3&C[2];s+="."+M+"."+Te(O)+x+"."+Te(B)+"."+U+"."+G+H+V+"."+Te(1)+"."+Te(1)+"."+Te(1)+".0",t=ye("dav1",r)}}return{codec:s,encrypted:a,supplemental:t}}function ye(e,t){var i=ge(t,["dvvC"]),r=i.length?i[0]:ge(t,["dvcC"])[0];if(r){var n=r[2]>>1&127,s=r[2]<<5&32|r[3]>>3&31;return e+"."+Te(n)+"."+Te(s)}}function Ee(e,t){for(var i=t+5;128&e[t++]&&t<i;);return t}function Se(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Te(e){return(e<10?"0":"")+e}function Le(e){var t=ge(e,["schm"])[0];if(t){var i=le(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return ge(e,["schi","tenc"])[0]}return null}function _e(e){var t=ue(e,0),i=8;1&t&&(i+=4),4&t&&(i+=4);for(var r=0,n=ue(e,4),s=0;s<n;s++)256&t&&(r+=ue(e,i),i+=4),512&t&&(i+=4),1024&t&&(i+=4),2048&t&&(i+=4);return r}function be(e,t){var i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function Ae(e,t){var i=[],r=t.samples,n=t.timescale,s=t.id,a=!1;return ge(r,["moof"]).map((function(o){var l=o.byteOffset-8;ge(o,["traf"]).map((function(o){var h=ge(o,["tfdt"]).map((function(e){var t=e[0],i=ue(e,4);return 1===t&&(i*=Math.pow(2,32),i+=ue(e,8)),i/n}))[0];return void 0!==h&&(e=h),ge(o,["tfhd"]).map((function(h){var u=ue(h,4),d=16777215&ue(h,0),c=0,f=!!(16&d),g=0,p=!!(32&d),v=8;u===s&&(!!(1&d)&&(v+=8),!!(2&d)&&(v+=4),!!(8&d)&&(c=ue(h,v),v+=4),f&&(g=ue(h,v),v+=4),p&&(v+=4),"video"===t.type&&(a=Ie(t.codec)),ge(o,["trun"]).map((function(s){var o=s[0],h=16777215&ue(s,0),u=!!(1&h),d=0,f=!!(4&h),p=!!(256&h),v=0,m=!!(512&h),y=0,E=!!(1024&h),S=!!(2048&h),T=0,L=ue(s,4),_=8;u&&(d=ue(s,_),_+=4),f&&(_+=4);for(var b=d+l,A=0;A<L;A++){if(p?(v=ue(s,_),_+=4):v=c,m?(y=ue(s,_),_+=4):y=g,E&&(_+=4),S&&(T=0===o?ue(s,_):ce(s,_),_+=4),t.type===J)for(var I=0;I<y;){var R=ue(r,b);Re(a,r[b+=4])&&Pe(r.subarray(b,b+R),a?2:1,e+T/n,i),b+=R,I+=R+4}e+=v/n}})))}))}))})),i}function Ie(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Re(e,t){if(e){var i=t>>1&63;return 39===i||40===i}return 6==(31&t)}function Pe(e,t,i,r){var n=ke(e),s=0;s+=t;for(var a=0,o=0,l=0;s<n.length;){a=0;do{if(s>=n.length)break;a+=l=n[s++]}while(255===l);o=0;do{if(s>=n.length)break;o+=l=n[s++]}while(255===l);var h=n.length-s,u=s;if(o<h)s+=o;else if(o>h){$.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===n[u++]){var d=he(n,u);if(u+=2,49===d){var c=ue(n,u);if(u+=4,1195456820===c){var f=n[u++];if(3===f){var g=n[u++],p=64&g,v=p?2+3*(31&g):0,m=new Uint8Array(v);if(p){m[0]=g;for(var y=1;y<v;y++)m[y]=n[u++]}r.push({type:f,payloadType:a,pts:i,bytes:m})}}}}}else if(5===a&&o>16){for(var E=[],S=0;S<16;S++){var T=n[u++].toString(16);E.push(1==T.length?"0"+T:T),3!==S&&5!==S&&7!==S&&9!==S||E.push("-")}for(var L=o-16,_=new Uint8Array(L),b=0;b<L;b++)_[b]=n[u++];r.push({payloadType:a,pts:i,uuid:E.join(""),userData:Y(_),userDataBytes:_})}}}function ke(e){for(var t=e.byteLength,i=[],r=1;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;var n=t-i.length,s=new Uint8Array(n),a=0;for(r=0;r<n;a++,r++)a===i[0]&&(a++,i.shift()),s[r]=e[a];return s}function De(e){var t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:i,size:t};var s=e.buffer,a=z(new Uint8Array(s,i+12,16)),o=e.getUint32(28),l=null,h=null;if(0===n){if(t-32<o||o<22)return{offset:i,size:t};h=new Uint8Array(s,i+32,o)}else if(1===n){if(!o||r<i+32+16*o+16)return{offset:i,size:t};l=[];for(var u=0;u<o;u++)l.push(new Uint8Array(s,i+32+16*u,16))}return{version:n,systemId:a,kids:l,data:h,offset:i,size:t}}var we=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 Me(e,t){var i=Ce[t];return!!i&&!!i[e.slice(0,4)]}function Oe(e,t,i){return void 0===i&&(i=!0),!e.split(",").some((function(e){return!xe(e,t,i)}))}function xe(e,t,i){var r;void 0===i&&(i=!0);var n=q(i);return null!=(r=null==n?void 0:n.isTypeSupported(Fe(e,t)))&&r}function Fe(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 Be(e){var t=we();return e.split(",").reduce((function(e,i){var r=t&&Ie(i)?9:Ce.video[i];return r?(2*r+e)/(e?3:2):(Ce.audio[i]+e)/(e?2:1)}),0)}var Ue={},Ge=/flac|opus|mp4a\.40\.34/i;function He(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 i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],r=0;r<i.length;r++){var n;if(xe(i[r],"audio",t))return Ue[e]=i[r],i[r];if("mp3"===i[r]&&null!=(n=q(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)}))}function Ve(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){var i=t.split(",");if(i.length>1){if(e)for(var r=i.length;r--;)if(i[r].substring(0,4)===e.substring(0,4))return i[r];return i[0]}}return t||e}function Ke(e){if(e.startsWith("av01.")){for(var t=e.split("."),i=["0","111","01","01","01","0"],r=t.length;r>4&&r<10;r++)t[r]=i[r-4];return t.join(".")}return e}function We(e){var t=q(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function $e(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var qe={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function je(e,t){return{supported:!1,configurations:t,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:e}}var Ye={};function ze(e,t,i){var r=e.videoCodec,n=e.audioCodec;if(!r&&!n||!i)return Promise.resolve(qe);var s=[];if(r){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=r.split(","),h=navigator.userAgent;if(l.some((function(e){return Ie(e)}))&&we())return Promise.resolve(je(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: ("+h+")"),s));s.push.apply(s,l.map((function(e){return{type:"media-source",video:c(c({},a),{},{contentType:Fe(Ke(e),"video")})}})))}return n&&e.audioGroups&&e.audioGroups.forEach((function(e){var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((function(t){if(t.groupId===e){var i=t.channels||"",r=parseFloat(i);_(r)&&r>2&&s.push.apply(s,n.split(",").map((function(e){return{type:"media-source",audio:{contentType:Fe(e,"audio"),channels:""+r}}})))}})))})),Promise.all(s.map((function(e){var t=function(e){var t=e.audio,i=e.video,r=i||t;if(r){var n=$e(r.contentType);if(i)return"r"+i.height+"x"+i.width+"f"+Math.ceil(i.framerate)+(i.transferFunction||"sd")+"_"+n+"_"+Math.ceil(i.bitrate/1e5);if(t)return"c"+t.channels+(t.spatialRendering?"s":"n")+"_"+n}return""}(e);return Ye[t]||(Ye[t]=i.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:s,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:s,decodingInfoResults:[],error:e}}))}var Xe=["NONE","TYPE-0","TYPE-1",null],Qe=["SDR","PQ","HLG"];function Je(e){var t=e.canSkipUntil,i=e.canSkipDateRanges,r=e.age;return t&&r<t/2?i?"v2":"YES":""}var Ze=function(){function e(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}return e.prototype.addDirectives=function(e){var t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href},e}(),et=function(){function e(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((function(e){return!!e})).map((function(e){return e.substring(0,4)})).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;var i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=","+i.substring(0,4))}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}var t=e.prototype;return t.hasAudioGroup=function(e){return tt(this._audioGroups,e)},t.hasSubtitleGroup=function(e){return tt(this._subtitleGroups,e)},t.addGroupId=function(e,t){if(t)if("audio"===e){var i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(t)&&i.push(t)}else if("text"===e){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(t)&&r.push(t)}},t.addFallback=function(){},n(e,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}}])}();function tt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}var it=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(i,r){if(e&&(r=e(i,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}}(t))};function rt(e,t){$.log('[abr] start candidates with "'+e+'" ignored because '+t)}function nt(e){return e.reduce((function(e,t){var i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);var r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function st(e){if(!e)return e;var t=e;return{lang:t.lang,assocLang:t.assocLang,characteristics:t.characteristics,channels:t.channels,audioCodec:t.audioCodec}}function at(e,t,i){if("attrs"in e){var r=t.indexOf(e);if(-1!==r)return r}for(var n=0;n<t.length;n++)if(ot(e,t[n],i))return n;return-1}function ot(e,t,i){var r,n,s=e.groupId,a=e.name,o=e.lang,l=e.assocLang,h=e.default,u=e.forced;return(void 0===s||t.groupId===s)&&(void 0===a||t.name===a)&&(void 0===o||(r=o,void 0===(n=t.lang)&&(n="--"),r.length===n.length?r===n:r.startsWith(n)||n.startsWith(r)))&&(void 0===o||t.assocLang===l)&&(void 0===h||t.default===h)&&(void 0===u||t.forced===u)&&(!("characteristics"in e)||function(e,t){void 0===t&&(t="");var i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some((function(e){return-1===r.indexOf(e)}))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function lt(e,t){var i=e.audioCodec,r=e.channels;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function ht(e,t,i){for(var r=t;r>-1;r--)if(i(e[r]))return r;for(var n=t+1;n<e.length;n++)if(i(e[n]))return n;return-1}function ut(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}var dt=function(e){function t(t){var i;return(i=e.call(this,"abr",t.logger)||this).hls=void 0,i.lastLevelLoadSec=0,i.lastLoadedFragLevel=-1,i.firstSelection=-1,i._nextAutoLevel=-1,i.nextAutoLevelKey="",i.audioTracksByGroup=null,i.codecTiers=null,i.timer=-1,i.fragCurrent=null,i.partCurrent=null,i.bitrateTestDelay=0,i.rebufferNotice=-1,i.bwEstimator=void 0,i._abandonRulesCheck=function(e){var t,r=i,n=r.fragCurrent,s=r.partCurrent,a=r.hls,o=a.autoLevelEnabled,l=a.media;if(n&&l){var h=performance.now(),u=s?s.stats:n.stats,d=s?s.duration:n.duration,c=h-u.loading.start,f=a.minAutoLevel,g=n.level,p=i._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=f)return i.clearTimer(),void(i._nextAutoLevel=-1);if(o){var v=p>-1&&p!==g,m=!!e||v;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=a.mainForwardBufferInfo;if(m||null!==y){var E=i.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(!(c<=Math.max(E,d/(2*S)*1e3))){var T=y?y.len/S:0,L=u.loading.first?u.loading.first-u.loading.start:-1,b=u.loaded&&L>-1,A=i.getBwEstimate(),I=a.levels,R=I[g],k=Math.max(u.loaded,Math.round(d*(n.bitrate||R.averageBitrate)/8)),D=b?c-L:c;D<1&&b&&(D=Math.min(c,8*u.loaded/A));var w=b?1e3*u.loaded/D:0,C=E/1e3,M=w?(k-u.loaded)/w:8*k/A+C;if(!(M<=T)){var O,x=w?8*w:A,F=!0===(null==(t=(null==e?void 0:e.details)||i.hls.latestLevelDetails)?void 0:t.live),N=i.hls.config.abrBandWidthUpFactor,B=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){var U=I[O].maxBitrate,G=!I[O].details||F;if((B=i.getTimeToLoadFrag(C,x,d*U,G))<Math.min(T,d+C))break}if(!(B>=M||B>10*d)){b?i.bwEstimator.sample(c-Math.min(E,L),u.loaded):i.bwEstimator.sampleTTFB(c);var H=I[O].maxBitrate;i.getBwEstimate()*N>H&&i.resetEstimator(H);var V=i.findBestLevel(H,f,O,0,T,1,1);V>-1&&(O=V),i.warn("Fragment "+n.sn+(s?" part "+s.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+n.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: "+(_(A)?0|A:"Unknown")+" bps\n New BW estimate: "+(0|i.getBwEstimate())+" bps\n Switching to level "+O+" @ "+(0|H)+" bps"),a.nextLoadLevel=a.nextAutoLevel=O,i.clearTimer();var K=function(){if(i.clearTimer(),i.fragCurrent===n&&i.hls.loadLevel===O&&O>0){var e=i.getStarvationDelay();if(i.warn("Aborting inflight request "+(O>0?"and switching down":"")+"\n Fragment duration: "+n.duration.toFixed(3)+" s\n Time to underbuffer: "+e.toFixed(3)+" s"),n.abortRequests(),i.fragCurrent=i.partCurrent=null,O>f){var t=i.findBestLevel(i.hls.levels[f].bitrate,f,O,0,e,1,1);-1===t&&(t=f),i.hls.nextLoadLevel=i.hls.nextAutoLevel=t,i.resetEstimator(i.hls.levels[t].bitrate)}}};v||M>2*B?K():i.timer=self.setInterval(K,1e3*B),a.trigger(P.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:s,stats:u})}}}}}}}},i.hls=t,i.bwEstimator=i.initEstimator(),i.registerListeners(),i}h(t,e);var i=t.prototype;return i.resetEstimator=function(e){e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},i.initEstimator=function(){var e=this.hls.config;return new N(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},i.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)},i.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))},i.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},i.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},i.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},i.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},i.onFragLoading=function(e,t){var i,r=t.frag;this.ignoreFragment(r)||(r.bitrateTest||(this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},i.onLevelSwitching=function(e,t){this.clearTimer()},i.onError=function(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:var i=t.frag,r=this.fragCurrent,n=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var s=performance.now(),a=n?n.stats:i.stats,o=s-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){var h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}}},i.getTimeToLoadFrag=function(e,t,i,r){return e+i/t+(r?e+this.lastLevelLoadSec:0)},i.onLevelLoaded=function(e,t){var i=this.hls.config,r=t.stats.loading,n=r.end-r.first;_(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},i.onFragLoaded=function(e,t){var i=t.frag,r=t.part,n=r?r.stats:i.stats;if(i.type===M&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var s=r?r.duration:i.duration,a=this.hls.levels[i.level],o=(a.loaded?a.loaded.bytes:0)+n.loaded,l=(a.loaded?a.loaded.duration:0)+s;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(i.bitrateTest){var h={stats:n,frag:i,part:r,id:i.type};this.onFragBuffered(P.FRAG_BUFFERED,h),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,n=null!=r&&r.stats.loaded?r.stats:i.stats;if(!n.aborted&&!this.ignoreFragment(i)){var s=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}},i.ignoreFragment=function(e){return e.type!==M||"initSegment"===e.sn},i.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},i.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},i.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,i=this.hls;if(i.levels.length<=1)return i.loadLevel;var r=i.maxAutoLevel,n=i.config,s=i.minAutoLevel,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,s,r,l,0,h,u);if(d>=0)return this.rebufferNotice=-1,d}var c=a?Math.min(a,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(a?Math.min(a,n.maxLoadingDelay):n.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,s,r,l,c,h,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var p=i.levels[s],v=i.loadLevelObj;return v&&(null==p?void 0:p.bitrate)<v.bitrate?s:i.loadLevel},i.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i},i.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},i.findBestLevel=function(e,t,i,r,n,s,a){var o,l=this,h=r+n,u=this.lastLoadedFragLevel,d=-1===u?this.hls.firstLevel:u,c=this.fragCurrent,f=this.partCurrent,g=this.hls,p=g.levels,v=g.allAudioTracks,m=g.loadLevel,y=g.config;if(1===p.length)return 0;var E,S=p[d],T=!(null==(o=this.hls.latestLevelDetails)||!o.live),L=-1===m||-1===u,b="SDR",A=(null==S?void 0:S.frameRate)||0,I=y.audioPreference,R=y.videoPreference,P=this.audioTracksByGroup||(this.audioTracksByGroup=nt(v)),k=-1;if(L){if(-1!==this.firstSelection)return this.firstSelection;var D=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce((function(e,i,r){if(!i.codecSet)return e;var n=i.audioGroups,s=e[i.codecSet];s||(e[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);var a=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.minIndex=Math.min(s.minIndex,r),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,n&&n.forEach((function(e){if(e){var i=t.groups[e];i&&(s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((function(e){s.channels[e]=(s.channels[e]||0)+i.channels[e]})))}})),e}),{})}(p,P,t,i)),w=function(e,t,i,r,n){for(var s=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=null==n?void 0:n.videoCodec,h=a&&2===parseInt(a),u=!1,d=!1,c=1/0,f=1/0,g=1/0,p=1/0,v=0,m=[],y=function(e,t){var i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){var n="SDR"!==(r=t.allowedVideoRanges||Qe.slice(0)).join("")&&!t.videoCodec;(i=void 0!==t.preferHDR?t.preferHDR:n&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}(t,n),E=y.preferHDR,S=y.allowedVideoRanges,T=function(){var t=e[s[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=s.length;L--;)T();c=_(c)?c:0,f=_(f)?f:0;var b=Math.max(1080,c),A=Math.max(30,f);g=_(g)?g:i,i=Math.max(g,i),d||(t=void 0);var I=s.length>1;return{codecSet:s.reduce((function(t,r){var n=e[r];if(r===t)return t;if(m=d?S.filter((function(e){return n.videoRanges[e]>0})):[],I){if(n.minBitrate>i)return rt(r,"min bitrate of "+n.minBitrate+" > current estimate of "+i),t;if(!n.hasDefaultAudio)return rt(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return rt(r,'audio codec preference "'+o+'" not found'),t;if(a&&!h){if(!n.channels[a])return rt(r,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(n.channels)+")"),t}else if((!o||h)&&u&&0===n.channels[2])return rt(r,"no renditions with stereo sound found"),t;if(n.minHeight>b)return rt(r,"min resolution of "+n.minHeight+" > maximum of "+b),t;if(n.minFramerate>A)return rt(r,"min framerate of "+n.minFramerate+" > maximum of "+A),t;if(!m.some((function(e){return n.videoRanges[e]>0})))return rt(r,"no variants with VIDEO-RANGE of "+it(m)+" found"),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return rt(r,'video codec preference "'+l+'" not found'),t;if(n.maxScore<v)return rt(r,"max score of "+n.maxScore+" < selected max of "+v),t}return t&&(Be(r)>=Be(t)||n.fragmentError>e[t].fragmentError)?t:(p=n.minIndex,v=n.maxScore,r)}),void 0),videoRanges:m,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}(D,b,e,I,R),C=w.codecSet,M=w.videoRanges,O=w.minFramerate,x=w.minBitrate,F=w.minIndex,N=w.preferHDR;k=F,E=C,b=N?M[M.length-1]:M[0],A=O,e=Math.max(e,x),this.log("picked start tier "+it(w))}else E=null==S?void 0:S.codecSet,b=null==S?void 0:S.videoRange;for(var B,U=f?f.duration:c?c.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,H=[],V=function(){var t,o=p[K],c=K>d;if(!o)return 0;if(y.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&(function(e,t,i,r,n,s){var a=e.audioCodec?e.audioGroups:null,o=null==s?void 0:s.audioCodec,l=null==s?void 0:s.channels,h=l?parseInt(l):o?1/0:2,u=null;if(null!=a&&a.length)try{u=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce((function(e,i){if(i){var r=t.groups[i];if(!r)throw new Error("Audio track group "+i+" not found");Object.keys(r.channels).forEach((function(t){e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(n,8e6))||!!u&&_(h)&&Object.keys(u).some((function(e){return parseInt(e)>h}))}(o,P,b,A,e,I)||Ie(o.videoCodec))?(o.supportedPromise=ze(o,P,g),o.supportedPromise.then((function(e){if(l.hls){o.supportedResult=e;var t=l.hls.levels,i=t.indexOf(o);e.error?l.warn('MediaCapabilities decodingInfo error: "'+e.error+'" for level '+i+" "+it(e)):e.supported||(l.warn("Unsupported MediaCapabilities decodingInfo result for level "+i+" "+it(e)),i>-1&&t.length>1&&(l.log("Removing unsupported level "+i),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}}))):o.supportedResult=qe}if((E&&o.codecSet!==E||b&&o.videoRange!==b||c&&A>o.frameRate||!c&&A>0&&A<o.frameRate||o.supportedResult&&(null==(t=o.supportedResult.decodingInfoResults)||!t[0].smooth))&&(!L||K!==k))return H.push(K),0;var v,S=o.details,R=(f?null==S?void 0:S.partTarget:null==S?void 0:S.averagetargetduration)||U;v=c?a*e:s*e;var D=U&&r>=2*U&&0===n?o.averageBitrate:o.maxBitrate,w=l.getTimeToLoadFrag(G,v,D*R,void 0===S);if(v>=D&&(K===u||0===o.loadError&&0===o.fragmentError)&&(w<=G||!_(w)||T&&!l.bitrateTestDelay||w<h)){var C=l.forcedAutoLevel;return K===m||-1!==C&&C===m||(H.length&&l.trace("Skipped level(s) "+H.join(",")+" of "+i+' max with CODECS and VIDEO-RANGE:"'+p[H[0]].codecs+'" '+p[H[0]].videoRange+'; not compatible with "'+E+'" '+b),l.info("switch candidate:"+d+"->"+K+" adjustedbw("+Math.round(v)+")-bitrate="+Math.round(v-D)+" ttfb:"+G.toFixed(1)+" avgDuration:"+R.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+w.toFixed(1)+" firstSelection:"+L+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+m)),L&&(l.firstSelection=K),{v:K}}},K=i;K>=t;K--)if(0!==(B=V())&&B)return B.v;return-1},i.deriveNextAutoLevel=function(e){var t=this.hls,i=t.maxAutoLevel,r=t.minAutoLevel;return Math.min(Math.max(e,r),i)},n(t,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,i=e.minAutoLevel,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,i,t,0,n,1,1);if(s>-1)return s;var a=this.hls.firstLevel,o=Math.min(Math.max(a,i),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+a+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(B),ct=function(e,t){for(var i=0,r=e.length-1,n=null,s=null;i<=r;){var a=t(s=e[n=(i+r)/2|0]);if(a>0)i=n+1;else{if(!(a<0))return s;r=n-1}}return null};function ft(e,t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=.005);var s=null;if(e){s=t[1+e.sn-t[0].sn]||null;var a=e.endDTS-i;a>0&&a<15e-7&&(i+=15e-7),s&&e.level!==s.level&&s.end<=e.end&&(s=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(s=t[0]);if(s&&((!e||e.level===s.level)&&0===gt(i,r,s)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var r=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),i);return e.start<=r}return!1}(s,e,Math.min(n,r))))return s;var o=ct(t,gt.bind(null,i,r));return!o||o===e&&s?s:o}function gt(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=0),i.start<=e&&i.start+i.duration>e)return 0;var r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function pt(e,t,i){var r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}function vt(e,t){return ct(e,(function(e){return e.cc<t?1:e.cc>t?-1:0}))}function mt(e){switch(e.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function yt(e,t){var i=mt(t);return e.default[(i?"timeout":"error")+"Retry"]}function Et(e,t){var i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function St(e){return c(c({},e),{errorRetry:null,timeoutRetry:null})}function Tt(e,t,i,r){if(!e)return!1;var n=null==r?void 0:r.code,s=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(n)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,s):s}var Lt=function(e){function t(t){var i;return(i=e.call(this,"error-controller",t.logger)||this).hls=void 0,i.playlistError=0,i.penalizedRenditions={},i.hls=t,i.registerListeners(),i}h(t,e);var i=t.prototype;return i.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)},i.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))},i.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},i.startLoad=function(e){},i.stopLoad=function(){this.playlistError=0},i.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===M?e.level:this.hls.loadLevel},i.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},i.onLevelUpdated=function(){this.playlistError=0},i.onError=function(e,t){var i;if(!t.fatal){var r=this.hls,n=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case R.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=_t());case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=2);case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:var s,a,o=t.parent===M?t.level:r.loadLevel;return void(t.details===R.LEVEL_EMPTY_ERROR&&null!=(s=t.context)&&null!=(a=s.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o)));case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var l=r.loadLevelObj;if(l&&(n.type===w&&l.hasAudioGroup(n.groupId)||n.type===C&&l.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var h=r.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 R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:var d;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(d=t.level)?d:r.loadLevel)));case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=_t())}t.type===I.KEY_SYSTEM_ERROR&&this.keySystemError(t)}},i.keySystemError=function(e){var t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)},i.getPlaylistRetryOrSwitchAction=function(e,t){var i=yt(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Tt(i,r,mt(e),e.response))return{action:5,flags:0,retryConfig:i,retryCount:r};var n=this.getLevelSwitchAction(e,t);return i&&(n.retryConfig=i,n.retryCount=r),n},i.getFragRetryOrSwitchAction=function(e){var t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],n=t.config,s=n.fragLoadPolicy,a=n.keyLoadPolicy,o=yt(e.details.startsWith("key")?a:s,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(r&&(e.details!==R.FRAG_GAP&&r.fragmentError++,Tt(o,l,mt(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(e,i);return o&&(h.retryConfig=o,h.retryCount=l),h},i.getLevelSwitchAction=function(e,t){var i=this.hls;null==t&&(t=i.loadLevel);var r=this.hls.levels[t];if(r){var n,s,a=e.details;r.loadError++,a===R.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,h=i.loadLevel,u=i.minAutoLevel,d=i.maxAutoLevel;i.autoLevelEnabled||(i.loadLevel=-1);for(var c,f=null==(n=e.frag)?void 0:n.type,g=(f===O&&a===R.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(a===R.BUFFER_ADD_CODEC_ERROR||a===R.BUFFER_APPEND_ERROR))&&l.some((function(e){var t=e.audioCodec;return r.audioCodec!==t})),p="video"===e.sourceBufferName&&(a===R.BUFFER_ADD_CODEC_ERROR||a===R.BUFFER_APPEND_ERROR)&&l.some((function(e){var t=e.codecSet,i=e.audioCodec;return r.codecSet!==t&&r.audioCodec===i})),v=null!=(s=e.context)?s:{},m=v.type,y=v.groupId,E=function(){var t=(S+h)%l.length;if(t!==h&&t>=u&&t<=d&&0===l[t].loadError){var i,n,s=l[t];if(a===R.FRAG_GAP&&f===M&&e.frag){var c=l[t].details;if(c){var v=ft(e.frag,c.fragments,e.frag.start);if(null!=v&&v.gap)return 0}}else{if(m===w&&s.hasAudioGroup(y)||m===C&&s.hasSubtitleGroup(y))return 0;if(f===O&&null!=(i=r.audioGroups)&&i.some((function(e){return s.hasAudioGroup(e)}))||f===x&&null!=(n=r.subtitleGroups)&&n.some((function(e){return s.hasSubtitleGroup(e)}))||g&&r.audioCodec===s.audioCodec||!g&&r.audioCodec!==s.audioCodec||p&&r.codecSet===s.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(c=E())||1!==c););if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}},i.onErrorOut=function(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===R.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'+t.sourceBufferName+'" sourceBuffer append error. Attempting to recover from media error.'),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()},i.sendAlternateToPenaltyBox=function(e){var t=this.hls,i=e.errorAction;if(i){var r=i.flags,n=i.hdcpLevel,s=i.nextAutoLevel;switch(r){case 0:this.switchLevel(e,s);break;case 2:n&&(t.maxHdcpLevel=Xe[Xe.indexOf(n)-1],i.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')}i.resolved||this.switchLevel(e,s)}},i.switchLevel=function(e,t){if(void 0!==t&&e.errorAction&&(this.warn("switching to level "+t+" after "+e.details),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var i=$e(e.mimeType),r=this.hls.levels,n=r.length;n--;)r[n][e.sourceBufferName+"Codec"]===i&&this.hls.removeLevel(n)},t}(B);function _t(e){var t={action:0,flags:0};return e&&(t.resolved=!0),t}var bt="NOT_LOADED",At="APPENDING",It="PARTIAL",Rt="OK",Pt=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 i=this.activePartLists[t];if(i)for(var r=i.length;r--;){var n=i[r];if(!n)break;var s=n.end;if(n.start<=e&&null!==s&&e<=s)return n}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){return this.getFragAtPos(e,t,!0)},t.getFragAtPos=function(e,t,i){for(var r=this.fragments,n=Object.keys(r),s=n.length;s--;){var a=r[n[s]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){var o=a.body;if(o.start<=e&&e<=o.end)return o}}return null},t.detectEvictedFragments=function(e,t,i,r,n){var s=this;this.timeRanges&&(this.timeRanges[e]=t);var a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(r){var o=s.fragments[r];if(o&&!(a>=o.body.sn))if(o.buffered||o.loaded&&!n){var l=o.range[e];l&&(0!==l.time.length?l.time.some((function(e){var i=!s.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&s.removeFragment(o.body),i})):s.removeFragment(o.body))}else o.body.type===i&&s.removeFragment(o.body)}))},t.detectPartialFragments=function(e){var t=this,i=this.timeRanges;if(i&&"initSegment"!==e.frag.sn){var r=e.frag,n=Dt(r),s=this.fragments[n];if(!(!s||s.buffered&&r.gap)){var a=!r.relurl;Object.keys(i).forEach((function(n){var o=r.elementaryStreams[n];if(o){var l=i[n],h=a||!0===o.partial;s.range[n]=t.getBufferedTimes(r,e.part,h,l)}})),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=r.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),kt(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}}},t.removeParts=function(e,t){var i=this.activePartLists[t];i&&(this.activePartLists[t]=wt(i,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var i=Dt(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)},t.getBufferedTimes=function(e,t,i,r){for(var n={time:[],partial:i},s=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||s,h=0;h<r.length;h++){var u=r.start(h)-this.bufferPadding,d=r.end(h)+this.bufferPadding;if(l>=u&&o<=d){n.time.push({startPTS:Math.max(s,r.start(h)),endPTS:Math.min(a,r.end(h))});break}if(s<d&&a>u){var c=Math.max(s,r.start(h)),f=Math.min(a,r.end(h));f>c&&(n.partial=!0,n.time.push({startPTS:c,endPTS:f}))}else if(a<=u)break}return n},t.getPartialFragment=function(e){var t,i,r,n=null,s=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&kt(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),s<=t&&(n=h.body,s=t)))})),n},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||kt(t))},t.getState=function(e){var t=Dt(e),i=this.fragments[t];return i?i.buffered?kt(i)?It:Rt:At:bt},t.isTimeBuffered=function(e,t,i){for(var r,n,s=0;s<i.length;s++){if(r=i.start(s)-this.bufferPadding,n=i.end(s)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var i=t.frag,r=t.part?null:t,n=Dt(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var i=t.frag,r=t.part,n=t.timeRanges,s=t.type;if("initSegment"!==i.sn){var a=i.type;if(r){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(r)}this.timeRanges=n;var l=n[s];this.detectEvictedFragments(s,l,a,r)}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Dt(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,i=Object.keys(t);if(!e)return i.length>0;for(var r=i.length;r--;){var n=t[i[r]];if((null==n?void 0:n.body.type)===e)return!0}return!1},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.removeFragmentsInRange=function(e,t,i,r,n){var s=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=s.fragments[a];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&s.removeFragment(l)}}))},t.removeFragment=function(e){var t=Dt(e);e.clearElementaryStreamInfo();var i=this.activePartLists[e.type];if(i){var r=e.sn;this.activePartLists[e.type]=wt(i,(function(e){return e.fragment.sn!==r}))}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 i=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;i&&i.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function kt(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function Dt(e){return e.type+"_"+e.level+"_"+e.sn}function wt(e,t){return e.filter((function(e){var i=t(e);return i||e.clearElementaryStreamInfo(),i}))}var Ct=function(){function e(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}return e.prototype.decrypt=function(e,t){switch(this.aesMode){case 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},e}(),Mt=function(){function e(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),i=new Uint32Array(4),r=0;r<4;r++)i[r]=t.getUint32(4*r);return i},t.initTable=function(){var e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],s=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],u=o[2],d=o[3],c=new Uint32Array(256),f=0,g=0,p=0;for(p=0;p<256;p++)c[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^255&v^99,e[f]=v,t[v]=f;var m=c[f],y=c[m],E=c[y],S=257*c[v]^16843008*v;r[f]=S<<24|S>>>8,n[f]=S<<16|S>>>16,s[f]=S<<8|S>>>24,a[f]=S,S=16843009*E^65537*y^257*m^16843008*f,l[v]=S<<24|S>>>8,h[v]=S<<16|S>>>16,u[v]=S<<8|S>>>24,d[v]=S,f?(f=m^c[c[c[E^m]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;r<t.length&&i;)i=t[r]===this.key[r],r++;if(!i){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var s,a,o,l,h=this.ksRows=4*(n+6+1),u=this.keySchedule=new Uint32Array(h),d=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,p=g[0],v=g[1],m=g[2],y=g[3];for(s=0;s<h;s++)s<n?o=u[s]=t[s]:(l=o,s%n==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[s/n|0]<<24):n>6&&s%n==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),u[s]=o=(u[s-n]^l)>>>0);for(a=0;a<h;a++)s=h-a,l=3&a?u[s]:u[s-4],d[a]=a<4||s<=4?l:p[c[l>>>24]]^v[c[l>>>16&255]]^m[c[l>>>8&255]]^y[c[255&l]],d[a]=d[a]>>>0}},t.networkToHostOrderSwap=function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},t.decrypt=function(e,t,i){for(var r,n,s,a,o,l,h,u,d,c,f,g,p,v,m=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,S=this.invSubMix,T=S[0],L=S[1],_=S[2],b=S[3],A=this.uint8ArrayToUint32Array_(i),I=A[0],R=A[1],P=A[2],k=A[3],D=new Int32Array(e),w=new Int32Array(D.length),C=this.networkToHostOrderSwap;t<D.length;){for(d=C(D[t]),c=C(D[t+1]),f=C(D[t+2]),g=C(D[t+3]),o=d^y[0],l=g^y[1],h=f^y[2],u=c^y[3],p=4,v=1;v<m;v++)r=T[o>>>24]^L[l>>16&255]^_[h>>8&255]^b[255&u]^y[p],n=T[l>>>24]^L[h>>16&255]^_[u>>8&255]^b[255&o]^y[p+1],s=T[h>>>24]^L[u>>16&255]^_[o>>8&255]^b[255&l]^y[p+2],a=T[u>>>24]^L[o>>16&255]^_[l>>8&255]^b[255&h]^y[p+3],o=r,l=n,h=s,u=a,p+=4;r=E[o>>>24]<<24^E[l>>16&255]<<16^E[h>>8&255]<<8^E[255&u]^y[p],n=E[l>>>24]<<24^E[h>>16&255]<<16^E[u>>8&255]<<8^E[255&o]^y[p+1],s=E[h>>>24]<<24^E[u>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[p+2],a=E[u>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&h]^y[p+3],w[t]=C(r^I),w[t+1]=C(a^R),w[t+2]=C(s^P),w[t+3]=C(n^k),I=d,R=c,P=f,k=g,t+=4}return w.buffer},e}(),Ot=function(){function e(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}return e.prototype.expandKey=function(){var e=function(e){switch(e){case 0:return"AES-CBC";case 1:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode "+e)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])},e}(),xt=function(){function e(e,t){var i=(void 0===t?{}:t).removePKCS7Padding,r=void 0===i||i;if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=r,r)try{var n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}var t=e.prototype;return t.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},t.isSync=function(){return this.useSoftware},t.flush=function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var i,r,n,s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(n=(r=(i=s).byteLength)&&new DataView(i.buffer).getUint8(r-1))?i.slice(0,r-n):i:s},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,i,r){var n=this;return this.useSoftware?new Promise((function(s,a){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);n.softwareDecrypt(o,t,i,r);var l=n.flush();l?s(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)},t.softwareDecrypt=function(e,t,i,r){var n=this.currentIV,s=this.currentResult,a=this.remainderData;if(0!==r||16!==t.byteLength)return $.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;n&&(i=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Mt),l.expandKey(t);var h=s;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null},t.webCryptoDecrypt=function(e,t,i,r){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Ot(this.subtle,t,r)}return this.fastAesKey.expandKey().then((function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new Ct(n.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(s){return $.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+s.name+": "+s.message),n.onWebCryptoError(e,t,i,r)}))},t.onWebCryptoError=function(e,t,i,r){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);var s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")},t.getValidChunk=function(e){var t=e,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t},t.logOnce=function(e){this.logEnabled&&($.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),Ft=Math.pow(2,17),Nt=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t){var i=this,r=e.url;if(!r)return Promise.reject(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();var n=this.config,s=n.fLoader,a=n.loader;return new Promise((function(o,l){if(i.loader&&i.loader.destroy(),e.gap){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void l(Ut(e));e.gap=!1}var h=i.loader=s?new s(n):new a(n),u=Bt(e);e.loader=h;var d=St(n.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Ft};e.stats=h.stats;var g={onSuccess:function(t,r,n,s){i.resetLoader(e,h);var a=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:s})},onError:function(t,n,s,a){i.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:c({url:r,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:s,stats:a}))},onAbort:function(t,r,n){i.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,r,n){i.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:t}))}};t&&(g.onProgress=function(i,r,n,s){return t({frag:e,part:null,payload:n,networkDetails:s})}),h.load(u,f,g)}))},t.loadPart=function(e,t,i){var r=this;this.abort();var n=this.config,s=n.fLoader,a=n.loader;return new Promise((function(o,l){if(r.loader&&r.loader.destroy(),e.gap||t.gap)l(Ut(e,t));else{var h=r.loader=s?new s(n):new a(n),u=Bt(e,t);e.loader=h;var d=St(n.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ft};t.stats=h.stats,h.load(u,f,{onSuccess:function(n,s,a,l){r.resetLoader(e,h),r.updateStatsFromPart(e,t);var u={frag:e,part:t,payload:n.data,networkDetails:l};i(u),o(u)},onError:function(i,n,s,a){r.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:c({url:u.url,data:void 0},i),error:new Error("HTTP Error "+i.code+" "+i.text),networkDetails:s,stats:a}))},onAbort:function(i,n,s){e.stats.aborted=t.stats.aborted,r.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:function(i,n,s){r.resetLoader(e,h),l(new Gt({type:I.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:s,stats:i}))}})}}))},t.updateStatsFromPart=function(e,t){var i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){var s=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/n),s),o=(s-a)*Math.round(i.loaded/a);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,h=r.loading;l.start?l.first+=h.first-h.start:(l.start=h.start,l.first=h.first),l.end=h.end},t.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function Bt(e,t){void 0===t&&(t=null);var i,r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(_(s)&&_(a)){var o,l=s,h=a;if("initSegment"===e.sn&&("AES-128"===(i=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===i)){var u=a-s;u%16&&(h=a+(16-u%16)),0!==s&&(n.resetIV=!0,l=s-16)}n.rangeStart=l,n.rangeEnd=h}return n}function Ut(e,t){var i=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),r={type:I.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Gt(r)}var Gt=function(e){function t(t){var i;return(i=e.call(this,t.error.message)||this).data=void 0,i.data=t,i}return h(t,e),t}(p(Error)),Ht=function(e){function t(t,i){var r;return(r=e.call(this,t,i)||this)._boundTick=void 0,r._tickTimer=null,r._tickInterval=null,r._tickCallCount=0,r._boundTick=r.tick.bind(r),r}h(t,e);var i=t.prototype;return i.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},i.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},i.onHandlerDestroyed=function(){},i.hasInterval=function(){return!!this._tickInterval},i.hasNextTick=function(){return!!this._tickTimer},i.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},i.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},i.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},i.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},i.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},i.doTick=function(){},t}(B),Vt=function(e,t,i,r,n,s){void 0===r&&(r=0),void 0===n&&(n=-1),void 0===s&&(s=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=s},Kt={length:0,start:function(){return 0},end:function(){return 0}},Wt=function(){function e(){}return e.isBuffered=function(t,i){if(t)for(var r=e.getBuffered(t),n=r.length;n--;)if(i>=r.start(n)&&i<=r.end(n))return!0;return!1},e.bufferedRanges=function(t){if(t){var i=e.getBuffered(t);return e.timeRangesToArray(i)}return[]},e.timeRangesToArray=function(e){for(var t=[],i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t},e.bufferInfo=function(t,i,r){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,i,r)}return{len:0,start:i,end:i,bufferedIndex:-1}},e.bufferedInfo=function(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var r=-1,n=[];if(i)for(var s=0;s<e.length;s++){t>=e[s].start&&t<=e[s].end&&(r=s);var a=n.length;if(a){var o=n[a-1].end;e[s].start-o<i?e[s].end>o&&(n[a-1].end=e[s].end):n.push(e[s])}else n.push(e[s])}else n=e;for(var l,h=0,u=t,d=t,c=0;c<n.length;c++){var f=n[c].start,g=n[c].end;if(-1===r&&t>=f&&t<=g&&(r=c),t+i>=f&&t<g)u=f,h=(d=g)-t;else if(t+i<f){l=f;break}}return{len:h,start:u||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:r}},e.getBuffered=function(e){try{return e.buffered||Kt}catch(e){return $.log("failed to get media.buffered",e),Kt}},e}(),$t=/\{\$([a-zA-Z0-9-_]+)\}/g;function qt(e){return $t.test(e)}function jt(e,t){if(null!==e.variableList||e.hasVariableRefs){var i=e.variableList;return t.replace($t,(function(t){var r=t.substring(2,t.length-1),n=null==i?void 0:i[r];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+r+'"')),t):n}))}return t}function Yt(e,t,i){var r,n,s=e.variableList;if(s||(e.variableList=s={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{var a=new self.URL(i).searchParams;if(!a.has(r))throw new Error('"'+r+'" does not match any query parameter in URI: "'+i+'"');n=a.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+t.message))}}else r=t.NAME,n=t.VALUE;r in s?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+r+'"')):s[r]=n||""}function zt(e,t,i){var r=t.IMPORT;if(i&&r in i){var n=e.variableList;n||(e.variableList=n={}),n[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+r+'"'))}var Xt=/^(\d+)x(\d+)$/,Qt=/(.+?)=(".*?"|.*?)(?:,|$)/g,Jt=function(){function e(t,i){"string"==typeof t&&(t=e.parseAttrList(t,i)),o(this,t)}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var i=new Uint8Array(t.length/2),r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(2*r,2*r+2),16);return i}return null},t.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var i=this[e];return i?parseFloat(i):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((function(e,t){return e[t.toLowerCase()]=!0,e}),t)},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=Xt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var i,r={};for(Qt.lastIndex=0;null!==(i=Qt.exec(e));){var n=i[1].trim(),s=i[2],a=0===s.indexOf('"')&&s.lastIndexOf('"')===s.length-1,o=!1;if(a)s=s.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))s=jt(t,s);else if(!o&&!a)switch(n){case"CLOSED-CAPTIONS":if("NONE"===s)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":$.warn(e+": attribute "+n+" is missing quotes")}r[n]=s}return r},n(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function Zt(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var ei=n((function(e,t,i){var r;if(void 0===i&&(i=0),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:i,t){var n=t.attr;for(var s in n)if(Object.prototype.hasOwnProperty.call(e,s)&&e[s]!==n[s]){$.warn('DATERANGE tag attribute: "'+s+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=s;break}e=o(new Jt({}),n,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 a=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);_(a.getTime())&&(this._endDate=a)}}),[{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?($.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)}}]),ti=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,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1},n(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 i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function ii(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function ri(e){switch(e){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw new Error("invalid full segment method "+e)}}function ni(e){return Uint8Array.from(atob(e),(function(e){return e.charCodeAt(0)}))}function si(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}var ai="undefined"!=typeof self?self:void 0,oi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},li="org.w3.clearkey",hi="com.apple.streamingkeydelivery",ui="com.microsoft.playready",di="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function ci(e){switch(e){case hi:return oi.FAIRPLAY;case ui:return oi.PLAYREADY;case di:return oi.WIDEVINE;case li:return oi.CLEARKEY}}function fi(e){return"edef8ba979d64acea3c827dcd51d21ed"===e?oi.WIDEVINE:"9a04f07998404286ab92e65be0885f95"===e?oi.PLAYREADY:"1077efecc0b24d02ace33c1e52e2fb4b"===e||"e2719d58a985b3c9781ab030af78d30e"===e?oi.CLEARKEY:void 0}function gi(e){switch(e){case oi.FAIRPLAY:return hi;case oi.PLAYREADY:return ui;case oi.WIDEVINE:return di;case oi.CLEARKEY:return li}}function pi(e){var t=e.drmSystems,i=e.widevineLicenseUrl,r=t?[oi.FAIRPLAY,oi.WIDEVINE,oi.PLAYREADY,oi.CLEARKEY].filter((function(e){return!!t[e]})):[];return!r[oi.WIDEVINE]&&i&&r.push(oi.WIDEVINE),r}var vi,mi=null!=ai&&null!=(vi=ai.navigator)&&vi.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function yi(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){var s=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(s){var a=ni(s).subarray(0,16);return function(e){var t=function(e,t,i){var r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(a),a}}return null}var Ei={},Si=function(){function e(e,t,i,r,n){void 0===r&&(r=[1]),void 0===n&&(n=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!ii(e)}e.clearKeyUriToKeyIdMap=function(){Ei={}};var t=e.prototype;return t.isSupported=function(){if(this.method){if(ii(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case hi:case di:case ui:case li:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},t.getDecryptData=function(t){if(!this.encrypted||!this.uri)return null;if(ii(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&($.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0);var i=function(e){for(var t=new Uint8Array(16),i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(t);return new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}var r=function(e){var t,i,r=e.split(":"),n=null;if("data"===r[0]&&2===r.length){var s=r[1].split(";"),a=s[s.length-1].split(",");if(2===a.length){var o="base64"===a[0],l=a[1];o?(s.splice(-1,1),n=ni(l)):(t=si(l).subarray(0,16),(i=new Uint8Array(16)).set(t,16-t.length),n=i)}}return n}(this.uri);if(r)switch(this.keyFormat){case di:this.pssh=r,r.length>=22&&(this.keyId=r.subarray(r.length-22,r.length-6));break;case ui:var n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");var r,n;r=new Uint8Array,n=new Uint8Array;var s=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(s.buffer).setUint32(0,i.byteLength,!1),function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var n=i.length,s=8,a=n;a--;)s+=i[a].byteLength;var o=new Uint8Array(s);for(o[0]=s>>24&255,o[1]=s>>16&255,o[2]=s>>8&255,o[3]=255&s,o.set(e,4),a=0,s=8;a<n;a++)o.set(i[a],s),s+=i[a].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,s,i||new Uint8Array)}(n,0,r),this.keyId=yi(r);break;default:var s=r.subarray(0,16);if(16!==s.length){var a=new Uint8Array(16);a.set(s,16-s.length),s=a}this.keyId=s}if(!this.keyId||16!==this.keyId.byteLength){var o=Ei[this.uri];if(!o){var l=Object.keys(Ei).length%Number.MAX_SAFE_INTEGER;o=new Uint8Array(16),new DataView(o.buffer,12,4).setUint32(0,l),Ei[this.uri]=o}this.keyId=o}return this},e}(),Ti=/#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,Li=/#EXT-X-MEDIA:(.*)/g,_i=/^#EXT(?:INF|-X-TARGETDURATION):/m,bi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ai=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("|")),Ii=function(){function e(){}return e.findGroup=function(e,t){for(var i=0;i<e.length;i++){var r=e[i];if(r.id===t)return r}},e.resolve=function(e,t){return L.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.isMediaPlaylist=function(e){return _i.test(e)},e.parseMasterPlaylist=function(t,i){var r,n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:qt(t)},s=[];for(Ti.lastIndex=0;null!=(r=Ti.exec(t));)if(r[1]){var a,o=new Jt(r[1],n),l=jt(n,r[2]),h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,i)},u=o.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),wi(o.CODECS,h);var d=o["SUPPLEMENTAL-CODECS"];d&&(h.supplemental={},wi(d,h.supplemental)),null!=(a=h.unknownCodecs)&&a.length||s.push(h),n.levels.push(h)}else if(r[3]){var c=r[3],f=r[4];switch(c){case"SESSION-DATA":var g=new Jt(f,n),p=g["DATA-ID"];p&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[p]=g);break;case"SESSION-KEY":var v=ki(f,i,n);v.encrypted&&v.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(v)):$.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+f+'"');break;case"DEFINE":Yt(n,new Jt(f,n),i);break;case"CONTENT-STEERING":var m=new Jt(f,n);n.contentSteering={uri:e.resolve(m["SERVER-URI"],i),pathwayId:m["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Di(f)}}var y=s.length>0&&s.length<n.levels.length;return n.levels=y?s:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n},e.parseMasterPlaylistMedia=function(t,i,r){var n,s={},a=r.levels,o={AUDIO:a.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),SUBTITLES:a.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),"CLOSED-CAPTIONS":[]},l=0;for(Li.lastIndex=0;null!==(n=Li.exec(t));){var h=new Jt(n[1],r),u=h.TYPE;if(u){var d=o[u],c=s[u]||[];s[u]=c;var f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],p=h.CHANNELS,v=h.CHARACTERISTICS,m=h["INSTREAM-ID"],y={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:u,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?e.resolve(h.URI,i):""};if(g&&(y.assocLang=g),p&&(y.channels=p),v&&(y.characteristics=v),m&&(y.instreamId=m),null!=d&&d.length){var E=e.findGroup(d,y.groupId)||d[0];Ci(y,E,"audioCodec"),Ci(y,E,"textCodec")}c.push(y)}}return s},e.parseLevelPlaylist=function(e,t,i,r,n,s){var a,l,h,u,d,c={url:t},f=new ti(t),g=f.fragments,p=[],v=null,m=0,y=0,E=0,S=0,T=0,L=null,b=new ie(r,c),A=-1,I=!1,R=null;if(bi.lastIndex=0,f.m3u8=e,f.hasVariableRefs=qt(e),"#EXTM3U"!==(null==(a=bi.exec(e))?void 0:a[0]))return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;null!==(l=bi.exec(e));){I&&(I=!1,(b=new ie(r,c)).playlistOffset=E,b.start=E,b.sn=m,b.cc=S,T&&(b.bitrate=T),b.level=i,v&&(b.initSegment=v,v.rawProgramDateTime&&(b.rawProgramDateTime=v.rawProgramDateTime,v.rawProgramDateTime=null),R&&(b.setByteRange(R),R=null)));var P=l[1];if(P){b.duration=parseFloat(P);var k=(" "+l[2]).slice(1);b.title=k||null,b.tagList.push(k?["INF",P,k]:["INF",P])}else if(l[3]){if(_(b.duration)){b.playlistOffset=E,b.start=E,u&&xi(b,u,f),b.sn=m,b.level=i,b.cc=S,g.push(b);var D=(" "+l[3]).slice(1);b.relurl=jt(f,D),Mi(b,L,p),L=b,E+=b.duration,m++,y=0,I=!0}}else{if(!(l=l[0].match(Ai))){$.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);var w=(" "+l[h]).slice(1),C=(" "+l[h+1]).slice(1),M=l[h+2]?(" "+l[h+2]).slice(1):null;switch(w){case"BYTERANGE":L?b.setByteRange(C,L):b.setByteRange(C);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=C,b.tagList.push(["PROGRAM-DATE-TIME",C]),-1===A&&(A=g.length);break;case"PLAYLIST-TYPE":f.type&&Fi(f,w,l),f.type=C.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?Fi(f,w,l):g.length>0&&Ni(f,w,l),m=f.startSN=parseInt(C);break;case"SKIP":f.skippedSegments&&Fi(f,w,l);var O=new Jt(C,f),x=O.decimalInteger("SKIPPED-SEGMENTS");if(_(x)){f.skippedSegments+=x;for(var F=x;F--;)g.push(null);m+=x}var N=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");N&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(N.split("\t")));break;case"TARGETDURATION":0!==f.targetduration&&Fi(f,w,l),f.targetduration=Math.max(parseInt(C),1);break;case"VERSION":null!==f.version&&Fi(f,w,l),f.version=parseInt(C);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":f.live||Fi(f,w,l),f.live=!1;break;case"#":(C||M)&&b.tagList.push(M?[C,M]:[C]);break;case"DISCONTINUITY":S++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([w]);break;case"BITRATE":b.tagList.push([w,C]),T=1e3*parseInt(C),_(T)?b.bitrate=T:T=0;break;case"DATERANGE":var B=new Jt(C,f),U=new ei(B,f.dateRanges[B.ID],f.dateRangeTagCount);f.dateRangeTagCount++,U.isValid||f.skippedSegments?f.dateRanges[U.id]=U:$.warn('Ignoring invalid DATERANGE tag: "'+C+'"'),b.tagList.push(["EXT-X-DATERANGE",C]);break;case"DEFINE":var G=new Jt(C,f);"IMPORT"in G?zt(f,G,s):Yt(f,G,t);break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?Fi(f,w,l):g.length>0&&Ni(f,w,l),f.startCC=S=parseInt(C);break;case"KEY":var H=ki(C,t,f);if(H.isSupported()){if("NONE"===H.method){u=void 0;break}u||(u={}),u[H.keyFormat]&&(u=o({},u)),u[H.keyFormat]=H}else $.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+C+'"');break;case"START":f.startTimeOffset=Di(C);break;case"MAP":var V=new Jt(C,f);if(b.duration){var K=new ie(r,c);Oi(K,V,i,u),v=K,b.initSegment=v,v.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=v.rawProgramDateTime)}else{var W=b.byteRangeEndOffset;if(W){var q=b.byteRangeStartOffset;R=W-q+"@"+q}else R=null;Oi(b,V,i,u),v=b,I=!0}v.cc=S;break;case"SERVER-CONTROL":d&&Fi(f,w,l),d=new Jt(C),f.canBlockReload=d.bool("CAN-BLOCK-RELOAD"),f.canSkipUntil=d.optionalFloat("CAN-SKIP-UNTIL",0),f.canSkipDateRanges=f.canSkipUntil>0&&d.bool("CAN-SKIP-DATERANGES"),f.partHoldBack=d.optionalFloat("PART-HOLD-BACK",0),f.holdBack=d.optionalFloat("HOLD-BACK",0);break;case"PART-INF":f.partTarget&&Fi(f,w,l);var j=new Jt(C);f.partTarget=j.decimalFloatingPoint("PART-TARGET");break;case"PART":var Y=f.partList;Y||(Y=f.partList=[]);var z=y>0?Y[Y.length-1]:void 0,X=y++,Q=new Jt(C,f),J=new re(Q,b,c,X,z);Y.push(J),b.duration+=J.duration;break;case"PRELOAD-HINT":var Z=new Jt(C,f);f.preloadHint=Z;break;case"RENDITION-REPORT":var ee=new Jt(C,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(ee);break;default:$.warn("line parsed but not handled: "+l)}}}L&&!L.relurl?(g.pop(),E-=L.duration,f.partList&&(f.fragmentHint=L)):f.partList&&(Mi(b,L,p),b.cc=S,f.fragmentHint=b,u&&xi(b,u,f)),f.targetduration||(f.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));var te=g.length,ne=g[0],se=g[te-1];if((E+=f.skippedSegments*f.targetduration)>0&&te&&se){f.averagetargetduration=E/te;var ae=se.sn;f.endSN="initSegment"!==ae?ae:0,f.live||(se.endList=!0),ne&&void 0===f.startCC&&(f.startCC=ne.cc),A>0&&(function(e,t){for(var i=e[t],r=t;r--;){var n=e[r];if(!n)return;n.programDateTime=i.programDateTime-1e3*n.duration,i=n}}(g,A),ne&&p.unshift(ne))}else f.endSN=0,f.startCC=0;return f.fragmentHint&&(E+=f.fragmentHint.duration),f.totalduration=E,p.length&&f.dateRangeTagCount&&ne&&Ri(p,f),f.endCC=S,f},e}();function Ri(e,t){for(var i=e.length,r=e[i-1],n=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),a=s.length;a--;){var o=t.dateRanges[s[a]],l=o.startDate.getTime();o.tagAnchor=r.ref;for(var h=i;h--;){var u=Pi(t,l,e,h,n);if(-1!==u){o.tagAnchor=t.fragments[u].ref;break}}}}function Pi(e,t,i,r,n){var s=i[r];if(s){var a,o=s.programDateTime;if((t>=o||0===r)&&t<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||n)-s.start)){var l=i[r].sn-e.startSN,h=e.fragments;if(h.length>i.length)for(var u=(i[r+1]||h[h.length-1]).sn-e.startSN;u>l;u--){var d=h[u].programDateTime;if(t>=d&&t<d+1e3*h[u].duration)return u}return l}}return-1}function ki(e,t,i){var r,n,s=new Jt(e,i),a=null!=(r=s.METHOD)?r:"",o=s.URI,l=s.hexadecimalInteger("IV"),h=s.KEYFORMATVERSIONS,u=null!=(n=s.KEYFORMAT)?n:"identity";o&&s.IV&&!l&&$.error("Invalid IV: "+s.IV);var d=o?Ii.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Si(a,d,u,c,l)}function Di(e){var t=new Jt(e).decimalFloatingPoint("TIME-OFFSET");return _(t)?t:null}function wi(e,t){var i=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var r=i.filter((function(t){return Me(t,e)}));r.length&&(t[e+"Codec"]=r.map((function(e){return e.split("/")[0]})).join(","),i=i.filter((function(e){return-1===r.indexOf(e)})))})),t.unknownCodecs=i}function Ci(e,t,i){var r=t[i];r&&(e[i]=r)}function Mi(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Oi(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function xi(e,t,i){e.levelkeys=t;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||r.push(e)}function Fi(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must not appear more than once ("+i[0]+")")}function Ni(e,t,i){e.playlistParsingError=new Error("#EXT-X-"+t+" must appear before the first Media Segment ("+i[0]+")")}function Bi(e,t){var i=t.startPTS;if(_(i)){var r,n=0;t.sn>e.sn?(n=i-e.start,r=e):(n=e.start-i,r=t),r.duration!==n&&r.setDuration(n)}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 Ui(e,t,i,r,n,s){r-i<=0&&($.warn("Fragment should have a positive duration",t),r=i+t.duration,s=n+t.duration);var a=i,o=r,l=t.startPTS,h=t.endPTS;if(_(l)){var u=Math.abs(l-i);_(t.deltaPTS)?t.deltaPTS=Math.max(u,t.deltaPTS):t.deltaPTS=u,a=Math.max(i,l),i=Math.min(i,l),n=Math.min(n,t.startDTS),o=Math.min(r,h),r=Math.max(r,h),s=Math.max(s,t.endDTS)}var d=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=a,t.startDTS=n,t.endPTS=r,t.minEndPTS=o,t.endDTS=s;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--)Bi(p[c],p[c-1]);for(c=g;c<p.length-1;c++)Bi(p[c],p[c+1]);return e.fragmentHint&&Bi(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function Gi(e,t){if(e!==t){for(var i,r=null,n=e.fragments,s=n.length-1;s>=0;s--){var a=n[s].initSegment;if(a){r=a;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){for(var r=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=n;h<=s;h++){var u=l[a+h],d=o[h];if(r&&!d&&u&&(d=t.fragments[h]=u),u&&d){if(i(u,d,h,o),u.url&&u.url!==d.url)return void(t.playlistParsingError=Hi("media sequence mismatch "+d.sn+":",e,t,0,d));if(u.cc!==d.cc)return void(t.playlistParsingError=Hi("discontinuity sequence mismatch ("+u.cc+"!="+d.cc+")",e,t,0,d))}}}(e,t,(function(n,s,a,o){if(!t.startCC&&s.cc!==n.cc){for(var l,h,u=n.cc-s.cc,d=a;d<o.length;d++)o[d].cc+=u;t.startCC=null!=(l=null==(h=$i(e,t.startSN-1))?void 0:h.cc)?l:o[0].cc,t.endCC=o[o.length-1].cc}_(n.startPTS)&&_(n.endPTS)&&(s.setStart(s.startPTS=n.startPTS),s.startDTS=n.startDTS,s.maxStartPTS=n.maxStartPTS,s.endPTS=n.endPTS,s.endDTS=n.endDTS,s.minEndPTS=n.minEndPTS,s.setDuration(n.endPTS-n.startPTS),s.duration&&(i=s),t.PTSKnown=t.alignedSliding=!0),n.hasStreams&&(s.elementaryStreams=n.elementaryStreams),s.loader=n.loader,n.hasStats&&(s.stats=n.stats),n.initSegment&&(s.initSegment=n.initSegment,r=n.initSegment)}));var l=t.fragments,h=t.fragmentHint?l.concat(t.fragmentHint):l;if(r&&h.forEach((function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)})),t.skippedSegments)if(t.deltaUpdateFailed=l.some((function(e){return!e})),t.deltaUpdateFailed){$.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 i=t.dateRanges,r=t.recentlyRemovedDateranges,n=o({},e);r&&r.forEach((function(e){delete n[e]}));var s=Object.keys(n).length;return s&&Object.keys(i).forEach((function(e){var t=n[e],r=new ei(i[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=s)):$.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+it(i[e].attr)+'"')})),n}(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&&Mi(h[c],h[c-1],d);Ri(d,t)}!function(e,t,i){if(e&&t)for(var r=0,n=0,s=e.length;n<=s;n++){var a=e[n],o=t[n+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):r--}}(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),i?Ui(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):Vi(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 Hi(e,t,i,r,n){return new Error(e+" "+n.url+"\nPlaylist starting @"+t.startSN+"\n"+t.m3u8+"\n\nPlaylist starting @"+i.startSN+"\n"+i.m3u8)}function Vi(e,t,i){void 0===i&&(i=!0);var r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,s=r>=0,a=0;if(s&&r<n.length)a=n[r].start;else if(s&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(s&&i)a=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}Ki(t,a)}function Ki(e,t){if(t){for(var i=e.fragments,r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Wi(e,t){void 0===t&&(t=1/0);var i=1e3*e.targetduration;if(e.updated){var r=e.fragments;if(r.length&&4*i>t){var n=1e3*r[r.length-1].duration;n<i&&(i=n)}}else i/=2;return Math.round(i)}function $i(e,t,i){if(!e)return null;var r=e.fragments[t-e.startSN];return r||((r=e.fragmentHint)&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null)}function qi(e,t,i){return e?ji(e.partList,t,i):null}function ji(e,t,i){if(e)for(var r=e.length;r--;){var n=e[r];if(n.index===i&&n.fragment.sn===t)return n}return null}function Yi(e){e.forEach((function(e,t){var i;null==(i=e.details)||i.fragments.forEach((function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function zi(e,t){for(var i=0,r=e.length;i<r;i++){var n;if((null==(n=e[i])?void 0:n.cc)===t)return e[i]}return null}function Xi(e,t){if(e){var i=e.start+t;e.start=e.startPTS=i,e.endPTS=i+e.duration}}function Qi(e,t){for(var i=t.fragments,r=0,n=i.length;r<n;r++)Xi(i[r],e);t.fragmentHint&&Xi(t.fragmentHint,e),t.alignedSliding=!0}function Ji(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var i=Math.min(t.endCC,e.endCC),r=zi(t.fragments,i),n=zi(e.fragments,i);r&&n&&($.log("Aligning playlist at start of dicontinuity sequence "+i),Qi(r.start-n.start,e))}}function Zi(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i=e.fragments,r=t.fragments;if(i.length&&r.length){var n,s,a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(n=zi(r,a),s=zi(i,a)),n&&s||(s=zi(i,(n=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.length/2)]);var o=n.programDateTime,l=s.programDateTime;o&&l&&Qi((l-o)/1e3-(s.start-n.start),e)}}}var er={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},tr=function(e){function t(t,i,r,n,s){var a;return(a=e.call(this,n,t.logger)||this).hls=void 0,a.fragPrevious=null,a.fragCurrent=null,a.fragmentTracker=void 0,a.transmuxer=null,a._state=er.STOPPED,a.playlistType=void 0,a.media=null,a.mediaBuffer=null,a.config=void 0,a.bitrateTest=!1,a.lastCurrentTime=0,a.nextLoadPosition=0,a.startPosition=0,a.startTimeOffset=null,a.retryDate=0,a.levels=null,a.fragmentLoader=void 0,a.keyLoader=void 0,a.levelLastLoaded=null,a.startFragRequested=!1,a.decrypter=void 0,a.initPTS=[],a.buffering=!0,a.loadingParts=!1,a.loopSn=void 0,a.onMediaSeeking=function(){var e=a,t=e.config,i=e.fragCurrent,r=e.media,n=e.mediaBuffer,s=e.state,o=r?r.currentTime:0,l=Wt.bufferInfo(n||r,o,t.maxBufferHole);if(a.log("media seeking to "+(_(o)?o.toFixed(3):o)+", state: "+s),a.state===er.ENDED)a.resetLoadingState();else if(i){var h=t.maxFragLookUpTolerance,u=i.start-h,d=i.start+i.duration+h;if(!l.len||d<l.start||u>l.end){var c=o>d;(o<u||c)&&(c&&i.loader&&(a.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),i.abortRequests(),a.resetLoadingState()),a.fragPrevious=null)}}if(r&&(a.fragmentTracker.removeFragmentsInRange(o,1/0,a.playlistType,!0),o>a.lastCurrentTime&&(a.lastCurrentTime=o),!a.loadingParts)){var 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=s,a.hls=t,a.fragmentLoader=new Nt(t.config),a.keyLoader=r,a.fragmentTracker=i,a.config=t.config,a.decrypter=new xt(t.config),a}h(t,e);var i=t.prototype;return i.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)},i.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)},i.doTick=function(){this.onTickEnd()},i.onTickEnd=function(){},i.startLoad=function(e){},i.stopLoad=function(){if(this.state!==er.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=er.STOPPED}},i.pauseBuffering=function(){this.buffering=!1},i.resumeBuffering=function(){this.buffering=!0},i._streamEnded=function(e,t){if(t.live||!this.media)return!1;var i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;var n=e.nextStart;if(n&&n>r&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var a=s[s.length-1];return Wt.isBuffered(this.media,a.start+a.duration/2)}var o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)},i.getLevelDetails=function(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details},i.onMediaAttached=function(e,t){var i=this.media=this.mediaBuffer=t.media;i.removeEventListener("seeking",this.onMediaSeeking),i.removeEventListener("ended",this.onMediaEnded),i.addEventListener("seeking",this.onMediaSeeking),i.addEventListener("ended",this.onMediaEnded);var r=this.config;this.levels&&r.autoStartLoad&&this.state===er.STOPPED&&this.startLoad(r.startPosition)},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}},i.onManifestLoading=function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1},i.onError=function(e,t){},i.onManifestLoaded=function(e,t){this.startTimeOffset=t.startTimeOffset},i.onHandlerDestroying=function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),e.prototype.onHandlerDestroying.call(this),this.hls=this.onMediaSeeking=this.onMediaEnded=null},i.onHandlerDestroyed=function(){this.state=er.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,e.prototype.onHandlerDestroyed.call(this)},i.loadFragment=function(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)},i._loadFragForPlayback=function(e,t,i){var r=this;this._doFragLoad(e,t,i,(function(e){var t=e.frag;if(r.fragContextChanged(t))return r.warn(t.type+" sn: "+t.sn+(e.part?" part: "+e.part.index:"")+" of "+r.fragInfo(t,!1,e.part)+") was dropped during download."),void r.fragmentTracker.removeFragment(t);t.stats.chunkCount++,r._handleFragmentLoadProgress(e)})).then((function(e){if(e){var t=r.state,i=e.frag;r.fragContextChanged(i)?(t===er.FRAG_LOADING||!r.fragCurrent&&t===er.PARSING)&&(r.fragmentTracker.removeFragment(i),r.state=er.IDLE):("payload"in e&&(r.log("Loaded "+i.type+" sn: "+i.sn+" of "+r.playlistLabel()+" "+i.level),r.hls.trigger(P.FRAG_LOADED,e)),r._handleFragmentLoadComplete(e))}})).catch((function(t){r.state!==er.STOPPED&&r.state!==er.ERROR&&(r.warn("Frag error: "+((null==t?void 0:t.message)||t)),r.resetFragmentLoading(e))}))},i.clearTrackerIfNeeded=function(e){var t,i=this.fragmentTracker;if(i.getState(e)===At){var r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),s=Math.max(e.duration,n?n.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?e.sn-a.sn:0)||this.reduceMaxBufferLength(s,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===It&&i.removeFragment(e))},i.checkLiveUpdate=function(e){if(e.updated&&!e.live){var t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)},i.waitForLive=function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)},i.flushMainBuffer=function(e,t,i){if(void 0===i&&(i=null),e-t){var r={startOffset:e,endOffset:t,type:i};this.hls.trigger(P.BUFFER_FLUSHING,r)}},i._loadInitSegment=function(e,t){var i=this;this._doFragLoad(e,t).then((function(e){var t=null==e?void 0:e.frag;if(!t||i.fragContextChanged(t)||!i.levels)throw new Error("init load aborted");return e})).then((function(e){var t=i.hls,r=e.frag,n=e.payload,s=r.decryptdata;if(n&&n.byteLength>0&&null!=s&&s.key&&s.iv&&ii(s.method)){var a=self.performance.now();return i.decrypter.decrypt(new Uint8Array(n),s.key.buffer,s.iv.buffer,ri(s.method)).catch((function(e){throw t.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e})).then((function(n){var s=self.performance.now();return t.trigger(P.FRAG_DECRYPTED,{frag:r,payload:n,stats:{tstart:a,tdecrypt:s}}),e.payload=n,i.completeInitSegmentLoad(e)}))}return i.completeInitSegmentLoad(e)})).catch((function(t){i.state!==er.STOPPED&&i.state!==er.ERROR&&(i.warn(t),i.resetFragmentLoading(e))}))},i.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==er.STOPPED&&(this.state=er.IDLE),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()},i.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},i.fragBufferedComplete=function(e,t){var i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+" > buffer:"+(i?function(e){for(var t="",i=e.length,r=0;r<i;r++)t+="["+e.start(r).toFixed(3)+"-"+e.end(r).toFixed(3)+"]";return t}(Wt.getBuffered(i)):"(detached)")+")"),te(e)){var r;if(e.type!==x){var n=e.elementaryStreams;if(!Object.keys(n).some((function(e){return!!n[e]})))return void(this.state=er.IDLE)}var s=null==(r=this.levels)?void 0:r[e.level];null!=s&&s.fragmentError&&(this.log("Resetting level fragment error count of "+s.fragmentError+" on frag buffered"),s.fragmentError=0)}this.state=er.IDLE},i._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var i=e.frag,r=e.part,n=e.partsLoaded,s=!n||0===n.length||n.some((function(e){return!e})),a=new Vt(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!s);t.flush(a)}},i._handleFragmentLoadProgress=function(e){},i._doFragLoad=function(e,t,i,r){var n,s=this;void 0===i&&(i=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!=(n=e.decryptdata)&&n.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=er.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!s.fragContextChanged(e.frag))return s.hls.trigger(P.KEY_LOADED,e),s.state===er.KEY_LOADING&&(s.state=er.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(te(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(i=Math.max(e.start,i||0),this.loadingParts&&te(e)){var u=a.partList;if(u&&r){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);var d=this.getNextPart(u,e,i);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(i.toFixed(3))),this.nextLoadPosition=f.start+f.duration,this.state=er.FRAG_LOADING,c=o?o.then((function(i){return!i||s.fragContextChanged(i.frag)?null:s.doFragPartsLoad(e,f,t,r)})).catch((function(e){return s.handleFragLoadError(e)})):this.doFragPartsLoad(e,f,t,r).catch((function(e){return s.handleFragLoadError(e)})),this.hls.trigger(P.FRAG_LOADING,{frag:e,part:f,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}if(te(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+i.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(i.toFixed(3))),_(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=er.FRAG_LOADING;var g,p=this.config.progressive;return g=p&&o?o.then((function(t){return!t||s.fragContextChanged(null==t?void 0:t.frag)?null:s.fragmentLoader.load(e,r)})).catch((function(e){return s.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,p?r:void 0),o]).then((function(e){var t=e[0];return!p&&t&&r&&r(t),t})).catch((function(e){return s.handleFragLoadError(e)})),this.hls.trigger(P.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g},i.doFragPartsLoad=function(e,t,i,r){var n=this;return new Promise((function(s,a){var o,l=[],h=null==(o=i.details)?void 0:o.partList,u=function(t){n.fragmentLoader.loadPart(e,t,r).then((function(r){l[t.index]=r;var a=r.part;n.hls.trigger(P.FRAG_LOADED,r);var o=qi(i.details,e.sn,t.index+1)||ji(h,e.sn,t.index+1);if(!o)return s({frag:e,part:a,partsLoaded:l});u(o)})).catch(a)};u(t)}))},i.handleFragLoadError=function(e){if("data"in e){var t=e.data;e.data&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(P.ERROR,t)}else this.hls.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},i._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===er.PARSING){var i=t.frag,r=t.part,n=t.level,s=self.performance.now();i.stats.parsing.end=s,r&&(r.stats.parsing.end=s);var a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+i.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(i,r,n,e.partial)}else this.fragCurrent||this.state===er.STOPPED||this.state===er.ERROR||(this.state=er.IDLE)},i.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var i,r,n=e.partList[0];if(t>=n.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1},i.getCurrentContext=function(e){var t=this.levels,i=this.fragCurrent,r=e.level,n=e.sn,s=e.part;if(null==t||!t[r])return this.warn("Levels object was unset while buffering fragment "+n+" of "+this.playlistLabel()+" "+r+". The current chunk will not be buffered."),null;var a=t[r],o=a.details,l=s>-1?qi(o,n,s):null,h=l?l.fragment:$i(o,n,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null},i.bufferFragmentData=function(e,t,i,r,n){var s;if(e&&this.state===er.PARSING){var a=e.data1,o=e.data2,l=a;if(a&&o&&(l=be(a,o)),null!=(s=l)&&s.length){var h={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:l};if(this.hls.trigger(P.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}}},i.flushBufferGap=function(e){var t=this.media;if(t)if(Wt.isBuffered(t,t.currentTime)){var i=t.currentTime,r=Wt.bufferInfo(t,i,0),n=e.duration,s=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),a=Math.max(Math.min(e.start-s,r.end-s),i+s);e.start-a>s&&this.flushMainBuffer(a,e.start)}else this.flushMainBuffer(0,e.start)},i.getFwdBufferInfo=function(e,t){var i,r=this.getLoadPosition();if(!_(r))return null;var n=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,n)},i.getFwdBufferInfoAtPos=function(e,t,i,r){var n=Wt.bufferInfo(e,t,r);if(0===n.len&&void 0!==n.nextStart){var s=this.fragmentTracker.getBufferedFrag(t,i);if(s&&(n.nextStart<=s.end||s.gap)){var a=Math.max(Math.min(n.nextStart,s.end)-t,r);return Wt.bufferInfo(e,t,a)}}return n},i.getMaxBufferLength=function(e){var t,i=this.config;return t=e?Math.max(8*i.maxBufferSize/e,i.maxBufferLength):i.maxBufferLength,Math.min(t,i.maxMaxBufferLength)},i.reduceMaxBufferLength=function(e,t){var i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return n>=r&&(i.maxMaxBufferLength=n,this.warn("Reduce max buffer length to "+n+"s"),!0)},i.getAppendedFrag=function(e,t){var i;void 0===t&&(t=M);var r=null==(i=this.fragmentTracker)?void 0:i.getAppendedFrag(e,t);return r&&"fragment"in r?r.fragment:r},i.getNextFragment=function(e,t){var i=t.fragments,r=i.length;if(!r)return null;var n=this.config,s=i[0].start,a=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(r<l)return this.warn("Not enough fragments to start playback (have: "+r+", need: "+l+")"),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<s){var h;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t,i);var u=this.hls.startPosition,d=this.hls.liveSyncPosition,c=o?(-1!==u&&u>=s?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<=s&&(o=i[0]);if(!o){var f=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,f,t)}var g=this.filterReplacedPrimary(o,t);if(!g&&o){var p=o.sn-t.startSN;g=this.filterReplacedPrimary(i[p+1]||null,t)}return this.mapToInitFragWhenRequired(g)},i.isLoopLoading=function(e,t){var i=this.fragmentTracker.getState(e);return(i===Rt||i===It&&!!e.gap)&&this.nextLoadPosition>t},i.getNextFragmentLoopLoading=function(e,t,i,r,n){var s=null;if(e.gap&&(s=this.getNextFragment(this.nextLoadPosition,t))&&!s.gap&&i.nextStart){var a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==a&&i.len+a.len>=n){var o=s.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+r+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,s},i.filterReplacedPrimary=function(e,t){if(!e)return e;if(ir(this.hls.config)&&e.type!==x){var i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){var n=r.event;if(n){if(n.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}var s=null==i?void 0:i.playerQueue;if(s)for(var a=s.length;a--;){var o=s[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e},i.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment},i.getNextPart=function(e,t,i){for(var r=-1,n=!1,s=!0,a=0,o=e.length;a<o;a++){var l=e[a];if(s=s&&!l.independent,r>-1&&i<l.start)break;var h=l.loaded;h?r=-1:(n||l.independent||s)&&l.fragment===t&&(r=a),n=h}return r},i.loadedEndOfParts=function(e,t){var i=e[e.length-1];return i&&t>i.start&&i.loaded},i.getInitialLiveFragment=function(e,t){var i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+i.programDateTime),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!_(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(var r=0;r<e.length;++r){var n=e[r];if(pt(t,i,n))return n}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){var s=t[n-e.startSN];i.cc===s.cc&&(r=s,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=vt(t,i.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn)}}else{var a=this.hls.liveSyncPosition;null!==a&&(r=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r},i.getFragmentAtPosition=function(e,t,i){var r,n,s=this.config,a=this.fragPrevious,o=i.fragments,l=i.endSN,h=i.fragmentHint,u=s.maxFragLookUpTolerance,d=i.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),r=e<t?ft(a,o,e,e<this.lastCurrentTime||e>t-u||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:u):o[o.length-1]){var f=r.sn-i.startSN,g=this.fragmentTracker.getState(r);if((g===Rt||g===It&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!c||d[0].fragment.sn>r.sn||!i.live&&!c)&&a&&r.level===a.level){var p=o[f+1];r=r.sn<l&&this.fragmentTracker.getState(p)!==Rt?p:null}}return r},i.alignPlaylists=function(e,t,i){var r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;var n=e.fragmentStart,s=!t,a=e.alignedSliding&&_(n);if(s||!a&&!n){!function(e,t){e&&(Ji(t,e),!t.alignedSliding&&e&&Zi(t,e),t.alignedSliding||!e||t.skippedSegments||Vi(e,t,!1))}(i,e);var o=e.fragmentStart;return this.log("Live playlist sliding: "+o.toFixed(2)+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" fragments: "+r),o}return n},i.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},i.setStartPosition=function(e,t){var i=this.startPosition;i<t&&(i=-1);var r=this.timelineOffset;if(-1===i){var n=null!==this.startTimeOffset,s=n?this.startTimeOffset:e.startTimeOffset;null!==s&&_(s)?(i=t+s,s<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log("Setting startPosition to "+i+" for start time offset "+s+" found in "+(n?"multivariant":"media")+" playlist"),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge "+i),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r},i.getLoadPosition=function(){var e,t=this.media,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i},i.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&te(e)&&e.stats.aborted&&(this.warn("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},i.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===er.FRAG_LOADING_WAITING_RETRY)||(this.state=er.IDLE)},i.onFragmentOrKeyLoadError=function(e,t){if(t.chunkMeta&&!t.frag){var i=this.getCurrentContext(t.chunkMeta);i&&(t.frag=i.frag)}var r=t.frag;if(r&&r.type===e&&this.levels)if(this.fragContextChanged(r)){var n;this.warn("Frag load error must match current frag to retry "+r.url+" > "+(null==(n=this.fragCurrent)?void 0:n.url))}else{var s=t.details===R.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!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&&te(r)&&!r.endList)this.resetFragmentErrors(e),this.treatAsGap(r),a.resolved=!0;else if((g||p)&&d<c.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);var v=Et(c,d);this.warn("Fragment "+r.sn+" of "+e+" "+r.level+" errored with "+t.details+", retrying loading "+(d+1)+"/"+c.maxNumRetry+" in "+v+"ms"),a.resolved=!0,this.retryDate=self.performance.now()+v,this.state=er.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+")");s||3===l||(a.resolved=!0)}else this.state=2===l?er.WAITING_LEVEL:er.ERROR;this.tickImmediate()}},i.reduceLengthAndFlushBuffer=function(e){if(this.state===er.PARSING||this.state===er.PARSED){var t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);var s=!n;return s&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+i+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),s}return!1},i.resetFragmentErrors=function(e){e===O&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==er.STOPPED&&(this.state=er.IDLE)},i.afterBufferFlushed=function(e,t,i){if(e){var r=Wt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===er.ENDED&&this.resetLoadingState()}},i.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==er.STOPPED&&(this.state=er.IDLE)},i.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}},i.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()},i.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},i.updateLevelTiming=function(e,t,i,r){var n=this,s=i.details;if(s){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 n.warn("Could not parse fragment "+e.sn+" "+a+" duration reliably ("+l+")"),t||!1;var h=r?0:Ui(s,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return n.hls.trigger(P.LEVEL_PTS_UPDATED,{details:s,level:i,drift:h,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(a=this.transmuxer)?void 0:a.error))){var o=new Error("Found no media in fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+" resetting transmuxer to fallback to playlist timing");if(this.warn(o.message),this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+i.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=er.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")},i.playlistLabel=function(){return this.playlistType===M?"level":"track"},i.fragInfo=function(e,t,i){var r,n;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(i?"part":"frag")+":["+(null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN).toFixed(3)+"-"+(null!=(n=t&&!i?e.endPTS:(i||e).end)?n:NaN).toFixed(3)+"]"+(i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):"")},i.treatAsGap=function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)},i.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},i.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},n(t,[{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"primaryPrefetch",get:function(){var e,t;return!(!ir(this.hls.config)||!(null==(e=this.hls.interstitialsManager)||null==(t=e.playingItem)?void 0:t.event))}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}(Ht);function ir(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var rr=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,i=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var i=new Uint8Array(t),r=0,n=0;n<e.length;n++){var s=e[n];i.set(s,r),r+=s.length}return i}(t,i),this.reset(),e):new Uint8Array(0)},t.reset=function(){this.chunks.length=0,this.dataLength=0},e}();function nr(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 sr(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 ar(e,t){var i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,(i|=(127&e[t+2])<<7)|127&e[t+3]}function or(e,t){for(var i=t,r=0;sr(e,t);)r+=10,r+=ar(e,t+6),nr(e,t+10)&&(r+=10),t+=r;if(r>0)return e.subarray(i,i+r)}function lr(e,t){return 255===e[t]&&240==(246&e[t+1])}function hr(e,t){return 1&e[t+1]?7:9}function ur(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function dr(e,t){return t+1<e.length&&lr(e,t)}function cr(e,t){if(dr(e,t)){var i=hr(e,t);if(t+i>=e.length)return!1;var r=ur(e,t);if(r<=i)return!1;var n=t+r;return n===e.length||dr(e,n)}return!1}function fr(e,t,i,r,n){if(!e.samplerate){var s=function(e,t,i,r){var n=t[i+2],s=n>>2&15;if(!(s>12)){var a=1+(n>>6&3),o=t[i+3]>>6&3|(1&n)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][s],u=s;5!==a&&29!==a||(u-=3);var d=[a<<3|(14&u)>>1,(1&u)<<7|o<<3];return $.log("manifest codec:"+r+", parsed codec:"+l+", channels:"+o+", rate:"+h+" (ADTS object type:"+a+" sampling index:"+s+")"),{config:d,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:r}}var c=new Error("invalid ADTS sampling index:"+s);e.emit(P.ERROR,P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}(t,i,r,n);if(!s)return;o(e,s)}}function gr(e){return 9216e4/e}function pr(e,t,i,r,n){var s,a=r+n*gr(e.samplerate),o=function(e,t){var i=hr(e,t);if(t+i<=e.length){var r=ur(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(o){var l=o.frameLength,h=o.headerLength,u=h+l,d=Math.max(0,i+u-t.length);d?(s=new Uint8Array(u-h)).set(t.subarray(i+h,t.length),0):s=t.subarray(i+h,i+u);var c={unit:s,pts:a};return d||e.samples.push(c),{sample:c,length:u,missing:d}}var f=t.length-i;return(s=new Uint8Array(f)).set(t.subarray(i,t.length),0),{sample:{unit:s,pts:a},length:f,missing:-1}}function vr(e,t){return sr(e,t)&&ar(e,t+6)+10<=e.length-t}function mr(e,t){if(e<0)return-mr(-e,t);var i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){var r=Math.floor(e*i);return(r%2==0?r:r+1)/i}return Math.round(e*i)/i}function yr(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1/0),function(e,t,i,r){var n=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),s=1;"BYTES_PER_ELEMENT"in r&&(s=r.BYTES_PER_ELEMENT);var a,o=(a=e)&&a.buffer instanceof ArrayBuffer&&void 0!==a.byteLength&&void 0!==a.byteOffset?e.byteOffset:0,l=(o+e.byteLength)/s,h=(o+t)/s,u=Math.floor(Math.max(0,Math.min(h,l)));return new r(n,u,Math.floor(Math.min(u+Math.max(i,0),l))-u)}(e,t,i,Uint8Array)}function Er(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Y(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,i=Y(e.data.subarray(t),!0);t+=i.length+1;var r=Y(e.data.subarray(t));return{key:e.type,info:i,data:r}}var n=Y(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?function(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var i=e.data.subarray(1).indexOf(0);if(-1!==i){var r=Y(yr(e.data,1,i)),n=e.data[2+i],s=e.data.subarray(3+i).indexOf(0);if(-1!==s){var a,o=Y(yr(e.data,3+i,s));return a="--\x3e"===r?Y(yr(e.data,4+i+s)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+s)),t.mimeType=r,t.pictureType=n,t.description=o,t.data=a,t}}}else console.log("Ignore frame with unrecognized character encoding")}(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,i=Y(e.data.subarray(t),!0);t+=i.length+1;var r=Y(e.data.subarray(t));return{key:e.type,info:i,data:r}}var n=Y(e.data.subarray(1));return{key:e.type,info:"",data:n}}}(e)}function Sr(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=ar(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}var Tr=10,Lr=10;function _r(e){for(var t=0,i=[];sr(e,t);){var r=ar(e,t+6);e[t+5]>>6&1&&(t+=Tr);for(var n=(t+=Tr)+r;t+Lr<n;){var s=Sr(e.subarray(t)),a=Er(s);a&&i.push(a),t+=s.size+Tr}nr(e,t)&&(t+=Tr)}return i}function br(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Ar(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function Ir(e){for(var t=_r(e),i=0;i<t.length;i++){var r=t[i];if(br(r))return Ar(r)}}var Rr=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 Pr(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 kr=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,i){},t.demux=function(e,t){this.cachedData&&(e=be(this.cachedData,e),this.cachedData=null);var i,r=or(e,0),n=r?r.length:0,s=this._audioTrack,a=this._id3Track,o=r?Ir(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&_(o))&&(this.basePTS=Dr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Rr.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){var h=this.appendFrame(s,e,n);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i=n+=h.length):n=l}else vr(e,n)?(r=or(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Rr.audioId3,duration:Number.POSITIVE_INFINITY}),i=n+=r.length):n++;if(n===l&&i!==l){var u=e.slice(i);this.cachedData?this.cachedData=be(this.cachedData,u):this.cachedData=u}}return{audioTrack:s,videoTrack:Pr(),id3Track:a,textTrack:Pr()}},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},t.flush=function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Pr(),id3Track:this._id3Track,textTrack:Pr()}},t.destroy=function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0},e}(),Dr=function(e,t,i){return _(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0)},wr=null,Cr=[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],Mr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Or=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],xr=[0,1,1,4];function Fr(e,t,i,r,n){if(!(i+24>t.length)){var s=Nr(t,i);if(s&&i+s.frameLength<=t.length){var a=r+n*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:t.subarray(i,i+s.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=s.channelCount,e.samplerate=s.sampleRate,e.samples.push(o),{sample:o,length:s.frameLength,missing:0}}}}function Nr(e,t){var i=e[t+1]>>3&3,r=e[t+1]>>1&3,n=e[t+2]>>4&15,s=e[t+2]>>2&3;if(1!==i&&0!==n&&15!==n&&3!==s){var a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Cr[14*(3===i?3-r:3===r?3:4)+n-1],h=Mr[3*(3===i?0:2===i?1:2)+s],u=3===o?1:2,d=Or[i][r],c=xr[r],f=8*d*c,g=Math.floor(d*l/h+a)*c;if(null===wr){var p=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);wr=p?parseInt(p[1]):0}return!!wr&&wr<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:u,frameLength:g,samplesPerFrame:f}}}function Br(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Ur(e,t){return t+1<e.length&&Br(e,t)}function Gr(e,t){if(t+1<e.length&&Br(e,t)){var i=Nr(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);var n=t+r;return n===e.length||Ur(e,n)}return!1}var Hr=function(e){function t(t,i){var r;return(r=e.call(this)||this).observer=void 0,r.config=void 0,r.observer=t,r.config=i,r}h(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,n){e.prototype.resetInitSegment.call(this,t,i,r,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:n,inputTimeScale:9e4,dropped:0}},t.probe=function(e,t){if(!e)return!1;var i=or(e,0),r=(null==i?void 0:i.length)||0;if(Gr(e,r))return!1;for(var n=e.length;r<n;r++)if(cr(e,r))return t.log("ADTS sync word found !"),!0;return!1},i.canParse=function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&lr(e,t)&&ur(e,t)<=e.length-t}(e,t)},i.appendFrame=function(e,t,i){fr(e,this.observer,t,i,e.manifestCodec);var r=pr(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r},t}(kr),Vr=function(e,t){var i=0,r=5;t+=r;for(var n=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);r>0;){a[0]=e[t];var o=Math.min(r,8),l=8-o;s[0]=4278190080>>>24+l<<l,n[0]=(a[0]&s[0])>>l,i=i?i<<o|n[0]:n[0],t+=1,r-=o}return i},Kr=function(e){function t(t){var i;return(i=e.call(this)||this).observer=void 0,i.observer=t,i}h(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,n){e.prototype.resetInitSegment.call(this,t,i,r,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:n,inputTimeScale:9e4,dropped:0}},i.canParse=function(e,t){return t+64<e.length},i.appendFrame=function(e,t,i){var r=Wr(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}},t.probe=function(e){if(!e)return!1;var t=or(e,0);if(!t)return!1;var i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Ir(t)&&Vr(e,i)<16},t}(kr);function Wr(e,t,i,r,n){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;var s=t[i+4]>>6;if(s>=3)return-1;var a=[48e3,44100,32e3][s],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+s];if(i+l>t.length)return-1;var h=t[i+6]>>5,u=0;2===h?u+=2:(1&h&&1!==h&&(u+=2),4&h&&(u+=2));var d=(t[i+6]<<8|t[i+7])>>12-u&1,c=[2,1,2,3,3,4,4,5][h]+d,f=t[i+5]>>3,g=7&t[i+5],p=new Uint8Array([s<<6|f<<1|g>>2,(3&g)<<6|h<<3|d<<2|o>>4,o<<4&224]),v=r+n*(1536/a*9e4),m=t.subarray(i,i+l);return e.config=p,e.channelCount=c,e.samplerate=a,e.samples.push({unit:m,pts:v}),l}var $r=function(e){function t(){return e.apply(this,arguments)||this}h(t,e);var i=t.prototype;return i.resetInitSegment=function(t,i,r,n){e.prototype.resetInitSegment.call(this,t,i,r,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:n,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=or(e,0),i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Ir(t)&&Vr(e,i)<=16)return!1;for(var r=e.length;i<r;i++)if(Gr(e,i))return $.log("MPEG Audio sync word found !"),!0;return!1},i.canParse=function(e,t){return function(e,t){return Br(e,t)&&4<=e.length-t}(e,t)},i.appendFrame=function(e,t,i){if(null!==this.basePTS)return Fr(e,t,i,this.basePTS,this.frameIndex)},t}(kr),qr=/\/emsg[-/]ID3/i,jr=function(){function e(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}var t=e.prototype;return t.resetTimeStamp=function(){},t.resetInitSegment=function(e,t,i,r){var n=this.videoTrack=Pr("video",1),s=this.audioTrack=Pr("audio",1),a=this.txtTrack=Pr("text",1);if(this.id3Track=Pr("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;n.id=h,n.timescale=a.timescale=u,n.codec=d,n.supplemental=c}if(o.audio){var f=o.audio,g=f.id,p=f.timescale,v=f.codec;s.id=g,s.timescale=p,s.codec=v}a.id=oe.text,n.sampleDuration=0,n.duration=s.duration=r}},t.resetContiguity=function(){this.remainderData=null},e.probe=function(e){return function(e){for(var t=e.byteLength,i=0;i<t;){var r=ue(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var i=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=be(this.remainderData,e));var s=function(e){var t={valid:null,remainder:null},i=ge(e,["moof"]);if(i.length<2)return t.remainder=e,t;var r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=s.remainder,r.samples=s.valid||new Uint8Array}else r.samples=i;var a=this.extractID3Track(r,t);return n.samples=Ae(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(t,this.timeOffset);return i.samples=Ae(e,t),{videoTrack:t,audioTrack:Pr(),id3Track:r,textTrack:Pr()}},t.extractID3Track=function(e,t){var i=this,r=this.id3Track;if(e.samples.length){var n=ge(e.samples,["emsg"]);n&&n.forEach((function(e){var n=function(e){var t=e[0],i="",r="",n=0,s=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==le(e.subarray(h,h+1));)i+=le(e.subarray(h,h+1)),h+=1;for(i+=le(e.subarray(h,h+1)),h+=1;"\0"!==le(e.subarray(h,h+1));)r+=le(e.subarray(h,h+1)),h+=1;r+=le(e.subarray(h,h+1)),h+=1,n=ue(e,12),s=ue(e,16),o=ue(e,20),l=ue(e,24),h=28}else if(1===t){n=ue(e,h+=4);var u=ue(e,h+=4),d=ue(e,h+=4);for(h+=4,a=Math.pow(2,32)*u+d,b(a)||(a=Number.MAX_SAFE_INTEGER,$.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=ue(e,h),l=ue(e,h+=4),h+=4;"\0"!==le(e.subarray(h,h+1));)i+=le(e.subarray(h,h+1)),h+=1;for(i+=le(e.subarray(h,h+1)),h+=1;"\0"!==le(e.subarray(h,h+1));)r+=le(e.subarray(h,h+1)),h+=1;r+=le(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(qr.test(n.schemeIdUri)){var s=Yr(n,t),a=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var o=n.payload;r.samples.push({data:o,len:o.byteLength,dts:s,pts:s,type:Rr.emsg,duration:a})}else if(i.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=Yr(n,t);r.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:Rr.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return r},t.demuxSampleAes=function(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0},e}();function Yr(e,t){return _(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var zr=function(){function e(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new xt(t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,0)},t.decryptAacSample=function(e,t,i){var r=this,n=e[t].unit;if(!(n.length<=16)){var s=n.subarray(16,n.length-n.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then((function(s){var a=new Uint8Array(s);n.set(a,16),r.decrypter.isSync()||r.decryptAacSamples(e,t+1,i)}))}},t.decryptAacSamples=function(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,i),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0,n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i},t.getAvcDecryptedUnit=function(e,t){for(var i=new Uint8Array(t),r=0,n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e},t.decryptAvcSample=function(e,t,i,r,n){var s=this,a=ke(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then((function(o){n.data=s.getAvcDecryptedUnit(a,o),s.decrypter.isSync()||s.decryptAvcSamples(e,t,i+1,r)}))},t.decryptAvcSamples=function(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();for(var n=e[t].units;!(i>=n.length);i++){var s=n[i];if(!(s.data.length<=48||1!==s.type&&5!==s.type||(this.decryptAvcSample(e,t,i,r,s),this.decrypter.isSync())))return}}},e}(),Xr=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}},t.getLastNalUnit=function(e){var t,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){var n=r.units;i=n[n.length-1]}return i},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var i=t.samples,r=i.length;if(!r)return void t.dropped++;var n=i[r-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}},t.parseNALu=function(e,t,i){var r,n,s=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<s;)if(r=t[h++],a)if(1!==a)if(r)if(1===r){if(n=h-a-1,u>=0){var c={data:t.subarray(u,n),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)),n>0&&(f.data=be(f.data,t.subarray(0,n)),f.state=0))}h<s?(u=h,d=this.getNALuType(t,h),a=0):a=-1}else a=0;else a=3;else a=r?0:2;else a=r?0:1;if(u>=0&&a>=0){var g={data:t.subarray(u,s),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}(),Qr=function(){function e(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&$.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i},t.skipLZ=function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},e}(),Jr=function(e){function t(){return e.apply(this,arguments)||this}h(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var n,s=this,a=this.parseNALu(e,i.data,r),o=this.VideoSample,l=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,h;switch(r.type){case 1:var u=!1;n=!0;var d,c=r.data;if(l&&c.length>4){var f=s.readSliceType(c);2!==f&&4!==f&&7!==f&&9!==f||(u=!0)}u&&null!=(d=o)&&d.frame&&!o.key&&(s.pushAccessUnit(o,e),o=s.VideoSample=null),o||(o=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=u;break;case 5:n=!0,null!=(a=o)&&a.frame&&!o.key&&(s.pushAccessUnit(o,e),o=s.VideoSample=null),o||(o=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:n=!0,Pe(r.data,1,i.pts,t.samples);break;case 7:var g,p;n=!0,l=!0;var v=r.data,m=s.readSPS(v);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(g=e.pixelRatio)?void 0:g[0])!==m.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[v];for(var y=v.subarray(1,4),E="avc1.",S=0;S<3;S++){var T=y[S].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:n=!0,e.pps=[r.data];break;case 9:n=!0,e.audFound=!0,null!=(h=o)&&h.frame&&(s.pushAccessUnit(o,e),o=null),o||(o=s.VideoSample=s.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}o&&n&&o.units.push(r)})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},i.getNALuType=function(e,t){return 31&e[t]},i.readSliceType=function(e){var t=new Qr(e);return t.readUByte(),t.readUEG(),t.readUEG()},i.skipScalingList=function(e,t){for(var i=8,r=8,n=0;n<e;n++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r},i.readSPS=function(e){var t,i,r,n=new Qr(e),s=0,a=0,o=0,l=0,h=n.readUByte.bind(n),u=n.readBits.bind(n),d=n.readUEG.bind(n),c=n.readBoolean.bind(n),f=n.skipBits.bind(n),g=n.skipEG.bind(n),p=n.skipUEG.bind(n),v=this.skipScalingList.bind(this);h();var m=h();if(u(5),f(3),h(),p(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),p(),p(),f(1),c())for(i=3!==y?8:12,r=0;r<i;r++)c()&&v(r<6?16:64,n)}p();var E=d();if(0===E)d();else if(1===E)for(f(1),g(),g(),t=d(),r=0;r<t;r++)g();p(),f(1);var S=d(),T=d(),L=u(1);0===L&&f(1),f(1),c()&&(s=d(),a=d(),o=d(),l=d());var _=[1,1];if(c()&&c())switch(h()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:_=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil(16*(S+1)-2*s-2*a),height:(2-L)*(T+1)*16-(L?2:4)*(o+l),pixelRatio:_}},t}(Xr),Zr=function(e){function t(){for(var t,i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return(t=e.call.apply(e,[this].concat(r))||this).initVPS=null,t}h(t,e);var i=t.prototype;return i.parsePES=function(e,t,i,r){var n,s=this,a=this.parseNALu(e,i.data,r),l=this.VideoSample,h=!1;i.data=null,l&&a.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach((function(r){var a,u;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=s.VideoSample=s.createVideoSample(!1,i.pts,i.dts)),l.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;n=!0,h&&null!=(d=l)&&d.frame&&!l.key&&(s.pushAccessUnit(l,e),l=s.VideoSample=null),l||(l=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:n=!0,null!=(a=l)&&a.frame&&!l.key&&(s.pushAccessUnit(l,e),l=s.VideoSample=null),l||(l=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 39:n=!0,Pe(r.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=o(e.params,s.readVPS(r.data)),s.initVPS=r.data),e.vps=[r.data];break;case 33:if(n=!0,h=!0,void 0===e.vps||e.vps[0]===s.initVPS||void 0===e.sps||s.matchSPS(e.sps[0],r.data)||(s.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var c=s.readSPS(r.data);for(var f in e.width=c.width,e.height=c.height,e.pixelRatio=c.pixelRatio,e.codec=c.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),c.params)e.params[f]=c.params[f]}s.pushParameterSet(e.sps,r.data,e.vps),l||(l=s.VideoSample=s.createVideoSample(!0,i.pts,i.dts)),l.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];var g=s.readPPS(r.data);for(var p in g)e.params[p]=g[p]}s.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(u=l)&&u.frame&&(s.pushAccessUnit(l,e),l=null),l||(l=s.VideoSample=s.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}l&&n&&l.units.push(r)})),r&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)},i.pushParameterSet=function(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)},i.getNALuType=function(e,t){return(126&e[t])>>>1},i.ebsp2rbsp=function(e){for(var t=new Uint8Array(e.byteLength),i=0,r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)},i.pushAccessUnit=function(t,i){e.prototype.pushAccessUnit.call(this,t,i),this.initVPS&&(this.initVPS=null)},i.readVPS=function(e){var t=new Qr(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}},i.readSPS=function(e){var t=new Qr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var i=t.readBits(3);t.readBoolean();for(var r=t.readBits(2),n=t.readBoolean(),s=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),m=[],y=[],E=0;E<i;E++)m.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(var S=i;S<8;S++)t.readBits(2);for(var T=0;T<i;T++)m[T]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[T]&&t.readUByte();t.readUEG();var L=t.readUEG();3==L&&t.skipBits(1);var _=t.readUEG(),b=t.readUEG(),A=t.readBoolean(),I=0,R=0,P=0,k=0;A&&(I+=t.readUEG(),R+=t.readUEG(),P+=t.readUEG(),k+=t.readUEG());for(var D=t.readUEG(),w=t.readUEG(),C=t.readUEG(),M=t.readBoolean()?0:i;M<=i;M++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(var O=0;O<4;O++)for(var x=0;x<(3===O?2:6);x++)if(t.readBoolean()){var F=Math.min(64,1<<4+(O<<1));O>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var B=t.readUEG(),U=0,G=0;G<B;G++){var H=!1;if(0!==G&&(H=t.readBoolean()),H){G===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var V=0,K=0;K<=U;K++){var W=t.readBoolean(),$=!1;W||($=t.readBoolean()),(W||$)&&V++}U=V}else{var q=t.readUEG(),j=t.readUEG();U=q+j;for(var Y=0;Y<q;Y++)t.readUEG(),t.readBoolean();for(var z=0;z<j;z++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var X=t.readUEG(),Q=0;Q<X;Q++){for(var J=0;J<C+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,ie=!0,re=1,ne=0;t.readBoolean(),t.readBoolean();var se=!1;if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),(se=t.readBoolean())&&(I+=t.readUEG(),R+=t.readUEG(),P+=t.readUEG(),k+=t.readUEG()),t.readBoolean()&&(re=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){var oe=t.readBoolean(),le=t.readBoolean(),he=!1;(oe||le)&&((he=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),he&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=i;ue++){var de=!1;(ie=t.readBoolean())||t.readBoolean()?t.readEG():de=t.readBoolean();var ce=de?1:t.readUEG()+1;if(oe)for(var fe=0;fe<ce;fe++)t.readUEG(),t.readUEG(),he&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(le)for(var ge=0;ge<ce;ge++)t.readUEG(),t.readUEG(),he&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var pe=_,ve=b;if(A||se){var me=1,ye=1;1===L?me=ye=2:2==L&&(me=2),pe=_-me*R-me*I,ve=b-ye*k-ye*P}for(var Ee=r?["A","B","C"][r]:"",Se=a<<24|o<<16|l<<8|h,Te=0,Le=0;Le<32;Le++)Te=(Te|(Se>>Le&1)<<31-Le)>>>0;var _e=Te.toString(16);return 1===s&&"2"===_e&&(_e="6"),{codecString:"hvc1."+Ee+s+"."+_e+"."+(n?"H":"L")+v+".B0",params:{general_tier_flag:n,general_profile_idc:s,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[u,d,c,f,g,p],general_level_idc:v,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:w,min_spatial_segmentation_idc:Z,chroma_format_idc:L,frame_rate:{fixed:ie,fps:ne/re}},width:pe,height:ve,pixelRatio:[ee,te]}},i.readPPS=function(e){var t=new Qr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var i=t.readBoolean(),r=t.readBoolean(),n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}},i.matchSPS=function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)},t}(Xr),en=188,tn=function(){function e(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}e.probe=function(t,i){var r=e.syncOffset(t);return r>0&&i.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},e.syncOffset=function(e){for(var t=e.length,i=Math.min(940,t-en)+1,r=0;r<i;){for(var n=!1,s=-1,a=0,o=r;o<t;o+=en){if(71!==e[o]||t-o!==en&&71!==e[o+en]){if(a)return-1;break}if(a++,-1===s&&0!==(s=o)&&(i=Math.min(s+18612,e.length-en)+1),n||(n=0===rn(e,o)),n&&a>1&&(0===s&&a>2||o+en>i))return s}r++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:oe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,i,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=r},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,i=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,i,r,n){var s;void 0===r&&(r=!1),void 0===n&&(n=!1),r||(this.sampleAes=null);var a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,u=a.pid,d=a.pesData,c=o.pid,f=l.pid,g=o.pesData,p=l.pesData,v=null,m=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=be(this.remainderData,t)).length,this.remainderData=null),E<en&&!n)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var S=Math.max(0,e.syncOffset(t));(E-=(E-S)%en)<t.byteLength&&!n&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));for(var T=0,L=S;L<E;L+=en)if(71===t[L]){var _=!!(64&t[L+1]),b=rn(t,L),A=void 0;if((48&t[L+3])>>4>1){if((A=L+5+t[L+4])===L+en)continue}else A=L+4;switch(b){case u:if(_){if(d&&(s=ln(d,this.logger))){if(null===this.videoParser)switch(a.segmentCodec){case"avc":this.videoParser=new Jr;break;case"hevc":this.videoParser=new Zr}null!==this.videoParser&&this.videoParser.parsePES(a,h,s,!1)}d={data:[],size:0}}d&&(d.data.push(t.subarray(A,L+en)),d.size+=L+en-A);break;case c:if(_){if(g&&(s=ln(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s);break;case"ac3":this.parseAC3PES(o,s)}g={data:[],size:0}}g&&(g.data.push(t.subarray(A,L+en)),g.size+=L+en-A);break;case f:_&&(p&&(s=ln(p,this.logger))&&this.parseID3PES(l,s),p={data:[],size:0}),p&&(p.data.push(t.subarray(A,L+en)),p.size+=L+en-A);break;case 0:_&&(A+=t[A]+1),y=this._pmtId=nn(t,A);break;case y:_&&(A+=t[A]+1);var I=sn(t,A,this.typeSupported,r,this.observer,this.logger);(u=I.videoPid)>0&&(a.pid=u,a.segmentCodec=I.segmentVideoCodec),(c=I.audioPid)>0&&(o.pid=c,o.segmentCodec=I.segmentAudioCodec),(f=I.id3Pid)>0&&(l.pid=f),null===v||m||(this.logger.warn("MPEG-TS PMT found at "+L+" after unknown PID '"+v+"'. Backtracking to sync byte @"+S+" to parse all TS packets."),v=null,L=S-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:v=b}}else T++;T>0&&an(this.observer,new Error("Found "+T+" TS packet/s that do not start with 0x47"),void 0,this.logger),a.pesData=d,o.pesData=g,l.pesData=p;var R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return n&&this.extractRemainingSamples(R),R},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,i=e.audioTrack,r=e.videoTrack,n=e.id3Track,s=e.textTrack,a=r.pesData,o=i.pesData,l=n.pesData;if(a&&(t=ln(a,this.logger))){if(null===this.videoParser)switch(r.segmentCodec){case"avc":this.videoParser=new Jr;break;case"hevc":this.videoParser=new Zr}null!==this.videoParser&&(this.videoParser.parsePES(r,s,t,!0),r.pesData=null)}else r.pesData=a;if(o&&(t=ln(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(t=ln(l,this.logger))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l},t.demuxSampleAes=function(e,t,i){var r=this.demux(e,i,!0,!this.config.progressive),n=this.sampleAes=new zr(this.observer,this.config,t);return this.decrypt(r,n)},t.decrypt=function(e,t){return new Promise((function(i){var r=e.audioTrack,n=e.videoTrack;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(function(){n.samples?t.decryptAvcSamples(n.samples,0,0,(function(){i(e)})):i(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(function(){i(e)}))}))},t.destroy=function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0},t.parseAACPES=function(e,t){var i,r,n,s=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),s=a.missing}}for(i=s,r=o.length;i<r-1&&!dr(o,i);i++);if(i!==s){var d,c=i<r-1;if(d=c?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES",an(this.observer,new Error(d),c,this.logger),!c)return}if(fr(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)n=t.pts;else{if(!a)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=gr(e.samplerate);n=a.sample.pts+f}for(var g,p=0;i<r;){if(i+=(g=pr(e,o,i,n,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;i<r-1&&!dr(o,i);i++);}},t.parseMPEGPES=function(e,t){var i=t.data,r=i.length,n=0,s=0,a=t.pts;if(void 0!==a)for(;s<r;)if(Ur(i,s)){var o=Fr(e,i,s,a,n);if(!o)break;s+=o.length,n++}else s++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},t.parseAC3PES=function(e,t){var i=t.data,r=t.pts;if(void 0!==r)for(var n,s=i.length,a=0,o=0;o<s&&(n=Wr(e,i,o,r,a++))>0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var i=o({},t,{type:this._videoTrack?Rr.emsg:Rr.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function rn(e,t){return((31&e[t+1])<<8)+e[t+2]}function nn(e,t){return(31&e[t+10])<<8|e[t+11]}function sn(e,t,i,r,n,s){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=rn(e,t),h=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){on("ADTS AAC",s);break}case 15:-1===a.audioPid&&(a.audioPid=l);break;case 21:-1===a.id3Pid&&(a.id3Pid=l);break;case 219:if(!r){on("H.264",s);break}case 27:-1===a.videoPid&&(a.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="mp3"):s.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){on("AC-3",s);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=l,a.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&h>0)for(var u=t+5,d=h;d>2;){106===e[u]&&(!0!==i.ac3?s.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=l,a.segmentAudioCodec="ac3"));var c=e[u+1]+2;u+=c,d-=c}break;case 194:case 135:return an(n,new Error("Unsupported EC-3 in M2TS found"),void 0,s),a;case 36:-1===a.videoPid&&(a.videoPid=l,a.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"))}t+=h+5}return a}function an(e,t,i,r){r.warn("parsing error: "+t.message),e.emit(P.ERROR,P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function on(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function ln(e,t){var i,r,n,s,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===((i=l[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>e.size-6)return null;var h=i[7];192&h&&(s=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?s-(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2)>54e5&&(t.warn(Math.round((s-a)/9e4)+"s delta between PTS and DTS, align them"),s=a):a=s);var u=(n=i[8])+9;if(e.size<=u)return null;e.size-=u;for(var d=new Uint8Array(e.size),c=0,f=l.length;c<f;c++){var g=(i=l[c]).byteLength;if(u){if(u>g){u-=g;continue}i=i.subarray(u),g-=u,u=0}d.set(i,o),o+=g}return r&&(r-=n+3),{data:d,pts:s,dts:a,len:r}}return null}var hn=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}(),un=Math.pow(2,32)-1,dn=function(){function e(){}return e.init=function(){var t;for(t in e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var i=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:i,audio:r};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=s,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,n))},e.box=function(e){for(var t=8,i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];for(var s=r.length,a=s;s--;)t+=r[s].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),s=0,t=8;s<a;s++)o.set(r[s],t),t+=r[s].byteLength;return o},e.hdlr=function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])},e.mdat=function(t){return e.box(e.types.mdat,t)},e.mdhd=function(t,i){i*=t;var r=Math.floor(i/(un+1)),n=Math.floor(i%(un+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,i,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,i))},e.moov=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(e.mvex(t)))},e.mvex=function(t){for(var i=t.length,r=[];i--;)r[i]=e.trex(t[i]);return e.box.apply(null,[e.types.mvex].concat(r))},e.mvhd=function(t,i){i*=t;var r=Math.floor(i/(un+1)),n=Math.floor(i%(un+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,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,s)},e.sdtp=function(t){var i,r,n=t.samples||[],s=new Uint8Array(4+n.length);for(i=0;i<n.length;i++)r=n[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,s)},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))},e.avc1=function(t){var i,r,n,s=[],a=[];for(i=0;i<t.sps.length;i++)n=(r=t.sps[i]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)n=(r=t.pps[i]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(r));var o=e.box(e.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,d>>24,d>>16&255,d>>8&255,255&d])))},e.esds=function(e){var t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2].concat(t,[6,1,2]))},e.audioStsd=function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){return e.box(e.types[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))},e.stsd=function(t){var i=t.segmentCodec;if("audio"===t.type){if("aac"===i)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===i&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===i&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===i)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===i&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+i+"/"+t.codec+")")},e.tkhd=function(t){var i=t.id,r=(t.duration||0)*(t.timescale||0),n=t.width||0,s=t.height||0,a=Math.floor(r/(un+1)),o=Math.floor(r%(un+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,s>>8&255,255&s,0,0]))},e.traf=function(t,i){var r=e.sdtp(t),n=t.id,s=Math.floor(i/(un+1)),a=Math.floor(i%(un+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,r.length+16+20+8+16+8+8),r)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var i=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,i){var r,n,s,a,o,l,h=t.samples||[],u=h.length,d=12+16*u,c=new Uint8Array(d);for(i+=8+d,c.set(["video"===t.type?1:0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<u;r++)s=(n=h[r]).duration,a=n.size,o=n.flags,l=n.cts,c.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*r);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var i=e.moov(t);return be(e.FTYP,i)},e.hvc1=function(t){for(var i=t.params,r=[t.vps,t.sps,t.pps],n=new Uint8Array([1,i.general_profile_space<<6|(i.general_tier_flag?32:0)|i.general_profile_idc,i.general_profile_compatibility_flags[0],i.general_profile_compatibility_flags[1],i.general_profile_compatibility_flags[2],i.general_profile_compatibility_flags[3],i.general_constraint_indicator_flags[0],i.general_constraint_indicator_flags[1],i.general_constraint_indicator_flags[2],i.general_constraint_indicator_flags[3],i.general_constraint_indicator_flags[4],i.general_constraint_indicator_flags[5],i.general_level_idc,240|i.min_spatial_segmentation_idc>>8,255&i.min_spatial_segmentation_idc,252|i.parallelismType,252|i.chroma_format_idc,248|i.bit_depth_luma_minus8,248|i.bit_depth_chroma_minus8,0,parseInt(i.frame_rate.fps),3|i.temporal_id_nested<<2|i.num_temporal_layers<<3|(i.frame_rate.fixed?64:0),r.length]),s=n.length,a=0;a<r.length;a+=1){s+=3;for(var o=0;o<r[a].length;o+=1)s+=2+r[a][o].length}var l=new Uint8Array(s);l.set(n,0),s=n.length;for(var h=r.length-1,u=0;u<r.length;u+=1){l.set(new Uint8Array([32+u|(u===h?128:0),0,r[u].length]),s),s+=3;for(var d=0;d<r[u].length;d+=1)l.set(new Uint8Array([r[u][d].length>>8,255&r[u][d].length]),s),s+=2,l.set(r[u][d],s),s+=r[u][d].length}var c=e.box(e.types.hvcC,l),f=t.width,g=t.height,p=t.pixelRatio[0],v=t.pixelRatio[1];return e.box(e.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,255&f,g>>8&255,255&g,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,255&p,v>>24,v>>16&255,v>>8&255,255&v])))},e}();dn.types=void 0,dn.HDLR_TYPES=void 0,dn.STTS=void 0,dn.STSC=void 0,dn.STCO=void 0,dn.STSZ=void 0,dn.VMHD=void 0,dn.SMHD=void 0,dn.STSD=void 0,dn.FTYP=void 0,dn.DINF=void 0;function cn(e,t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);var n=e*t*i;return r?Math.round(n):n}function fn(e,t){return cn(e,1e3,1/9e4,t)}var gn=null,pn=null;function vn(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var mn=function(){function e(e,t,i,r){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=i,this.logger=r,this.ISGenerated=!1,null===gn){var n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);gn=n?parseInt(n[1]):0}if(null===pn){var s=navigator.userAgent.match(/Safari\/(\d+)/i);pn=s?parseInt(s[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,i=e[0].pts,r=e.reduce((function(e,r){var n=r.pts,s=n-e;return s<-4294967296&&(t=!0,s=(n=yn(n,i))-e),s>0?e:n}),i);return t&&this.logger.debug("PTS rollover detected"),r},t.remux=function(e,t,i,r,n,s,a,o){var l,h,u,d,c,f,g=n,p=n,v=e.pid>-1,m=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!v||E)&&(!m||S)||this.ISGenerated||a){if(this.ISGenerated){var T,L,_,b,A=this.videoTrackConfig;(A&&(t.width!==A.width||t.height!==A.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(L=A.pixelRatio)?void 0:L[0])||(null==(_=t.pixelRatio)?void 0:_[1])!==(null==(b=A.pixelRatio)?void 0:b[1]))||!A&&S||null===this.nextAudioPts&&E)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,n,s));var I,R=this.isVideoContiguous,P=-1;if(S&&(P=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!R&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,P>0){this.logger.warn("[mp4-remuxer]: Dropped "+P+" out of "+y+" video samples due to a missing keyframe");var k=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,I=p+=(t.samples[0].pts-k)/t.inputTimeScale}else-1===P&&(this.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),w=(yn(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,w),p+=Math.max(0,-w)}if(E){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,s)),h=this.remuxAudio(e,g,this.isAudioContiguous,s,m||S||o===O?p:void 0),S){var C=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,s)),l=this.remuxVideo(t,p,R,C)}}else S&&(l=this.remuxVideo(t,p,R,0));l&&(l.firstKeyFrame=P,l.independent=-1!==P,l.firstKeyFramePTS=I)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=En(i,n,this._initPTS,this._initDTS)),r.samples.length&&(d=Sn(r,n,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:c}},t.generateIS=function(e,t,i,r){var n,s,a,o=e.samples,l=t.samples,h=this.typeSupported,u={},d=this._initPTS,c=!d||r,f="audio/mp4";if(c&&(n=s=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):dn.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(a=e.inputTimeScale,d&&a===d.timescale?c=!1:n=s=o[0].pts-Math.round(a*i))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:dn.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*i);s=Math.min(s,yn(l[0].dts,g)-p),n=Math.min(n,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:n,timescale:a},this._initDTS={baseTime:s,timescale:a}):n=a=void 0,{tracks:u,initPTS:n,timescale:a}},t.remuxVideo=function(e,t,i,r){var n,s,a=e.inputTimeScale,l=e.samples,h=[],u=l.length,d=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,m=!1;if(!i||null===c){var y=t*a,E=l[0].pts-yn(l[0].dts,l[0].pts);gn&&null!==c&&Math.abs(y-E-c)<15e3?i=!0:c=y-E}for(var S=d.baseTime*a/d.timescale,T=0;T<u;T++){var L=l[T];L.pts=yn(L.pts-S,c),L.dts=yn(L.dts-S,c),L.dts<l[T>0?T-1:T].dts&&(m=!0)}m&&l.sort((function(e,t){var i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),n=l[0].dts;var _=l[l.length-1].dts-n,b=_?Math.round(_/(u-1)):g||e.inputTimeScale/30;if(i){var A=n-c,k=A>b,D=A<-1;if((k||D)&&(k?this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+fn(A,!0)+" ms ("+A+"dts) hole between fragments detected at "+t.toFixed(3)):this.logger.warn((e.segmentCodec||"").toUpperCase()+": "+fn(-A,!0)+" ms ("+A+"dts) overlapping between fragments detected at "+t.toFixed(3)),!D||c>=l[0].pts||gn)){n=c;var w=l[0].pts-A;if(k)l[0].dts=n,l[0].pts=w;else for(var C=!0,M=0;M<l.length&&!(l[M].dts>w&&C);M++){var O=l[M].pts;if(l[M].dts-=A,l[M].pts-=A,M<l.length-1){var x=l[M+1].pts;C=x<=l[M].pts==x<=O}}this.logger.log("Video: Initial PTS/DTS adjusted: "+fn(w,!0)+"/"+fn(n,!0)+", delta: "+fn(A,!0)+" ms")}}for(var F=0,N=0,B=n=Math.max(0,n),U=0;U<u;U++){for(var G=l[U],H=G.units,V=H.length,K=0,W=0;W<V;W++)K+=H[W].data.length;N+=K,F+=V,G.length=K,G.dts<B?(G.dts=B,B+=b/4|0||1):B=G.dts,p=Math.min(G.pts,p),v=Math.max(G.pts,v)}s=l[u-1].dts;var $,q=N+4*F+8;try{$=new Uint8Array(q)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:I.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:q,reason:"fail allocating video mdat "+q})}var j=new DataView($.buffer);j.setUint32(0,q),$.set(dn.types.mdat,4);for(var Y=!1,z=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,ie=0,re=0,ne=te.length;re<ne;re++){var se=te[re],ae=se.data,oe=se.data.byteLength;j.setUint32(f,oe),f+=4,$.set(ae,f),f+=oe,ie+=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*a),ce=(r?p+r*a:this.nextAudioPts)-ee.pts;ce>de?((g=ce-ue)<0?g=ue:Y=!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);z=Math.min(z,g),Q=Math.max(Q,g),X=Math.min(X,le),J=Math.max(J,le),h.push(vn(ee.key,g,ie,fe))}if(h.length)if(gn){if(gn<70){var ge=h[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(pn&&J-X<Q-z&&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=n,ve=0,me=h.length;ve<me;ve++){var ye=pe+h[ve].duration,Ee=pe+h[ve].cts;if(ve<me-1){var Se=ye+h[ve+1].cts;h[ve].duration=Se-Ee}else h[ve].duration=ve?h[ve-1].duration:b;h[ve].cts=0,pe=ye}}g=Y||!g?b:g,this.nextAvcDts=c=s+g,this.videoSampleDuration=g,this.isVideoContiguous=!0;var Te={data1:dn.moof(e.sequenceNumber++,n,o(e,{samples:h})),data2:$,startPTS:p/a,endPTS:(v+g)/a,startDTS:n/a,endDTS:c/a,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,i,r,n){var s=e.inputTimeScale,a=s/(e.samplerate?e.samplerate:s),l=this.getSamplesPerFrame(e),h=l*a,u=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],f=void 0!==n,g=e.samples,p=d?0:8,v=this.nextAudioPts||-1,m=t*s,y=u.baseTime*s/u.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(r&&Math.abs(m-v)<9e3||Math.abs(yn(g[0].pts-y,m)-v)<20*h),g.forEach((function(e){e.pts=yn(e.pts-y,m)})),!i||v<0){if(g=g.filter((function(e){return e.pts>=0})),!g.length)return;v=0===n?0:r&&!f?Math.max(0,m):g[0].pts}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,S=0,T=v;S<g.length;S++){var L=g[S],_=L.pts,b=_-T,A=Math.abs(1e3*b/s);if(b<=-E*h&&f)0===S&&(this.logger.warn("Audio frame @ "+(_/s).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*b/s)+" ms."),this.nextAudioPts=v=T=_);else if(b>=E*h&&A<1e4&&f){var k=Math.round(b/h);(T=_-k*h)<0&&(k--,T+=h),0===S&&(this.nextAudioPts=v=T),this.logger.warn("[mp4-remuxer]: Injecting "+k+" audio frame @ "+(T/s).toFixed(3)+"s due to "+Math.round(1e3*b/s)+" ms gap.");for(var D=0;D<k;D++){var w=Math.max(T,0),C=hn.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);C||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),C=L.unit.subarray()),g.splice(S,0,{unit:C,pts:w}),T+=h,S++}}L.pts=T,T+=h}for(var M,O=null,x=null,F=0,N=g.length;N--;)F+=g[N].unit.byteLength;for(var B=0,U=g.length;B<U;B++){var G=g[B],H=G.unit,V=G.pts;if(null!==x)c[B-1].duration=Math.round((V-x)/a);else{if(i&&"aac"===e.segmentCodec&&(V=v),O=V,!(F>0))return;F+=p;try{M=new Uint8Array(F)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:I.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:F,reason:"fail allocating audio mdat "+F})}d||(new DataView(M.buffer).setUint32(0,F),M.set(dn.types.mdat,4))}M.set(H,p);var K=H.byteLength;p+=K,c.push(vn(!0,l,K,0)),x=V}var W=c.length;if(W){var $=c[c.length-1];this.nextAudioPts=v=x+a*$.duration;var q=d?new Uint8Array(0):dn.moof(e.sequenceNumber++,O/a,o({},e,{samples:c}));e.samples=[];var j=O/s,Y=v/s,z={data1:q,data2:M,startPTS:j,endPTS:Y,startDTS:j,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:W};return this.isAudioContiguous=!0,z}},e}();function yn(e,t){var i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function En(e,t,i,r){var n=e.samples.length;if(n){for(var s=e.inputTimeScale,a=0;a<n;a++){var o=e.samples[a];o.pts=yn(o.pts-i.baseTime*s/i.timescale,t*s)/s,o.dts=yn(o.dts-r.baseTime*s/r.timescale,t*s)/s}var l=e.samples;return e.samples=[],{samples:l}}}function Sn(e,t,i){var r=e.samples.length;if(r){for(var n=e.inputTimeScale,s=0;s<r;s++){var a=e.samples[s];a.pts=yn(a.pts-i.baseTime*n/i.timescale,t*n)/n}e.samples.sort((function(e,t){return e.pts-t.pts}));var o=e.samples;return e.samples=[],{samples:o}}}var Tn,Ln=function(){function e(e,t,i,r){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=r}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,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;var i=t.keyId;return i&&t.isCommonEncryption&&ge(e,["moov","trak"]).forEach((function(e){var t=ge(e,["mdia","minf","stbl","stsd"])[0].subarray(8),r=ge(t,["enca"]),n=r.length>0;n||(r=ge(t,["encv"])),r.forEach((function(e){ge(n?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=Le(e);if(t){var r=t.subarray(8,24);r.some((function(e){return 0!==e}))||($.log("[eme] Patching keyId in 'enc"+(n?"a":"v")+">sinf>>tenc' box: "+z(r)+" -> "+z(i)),t.set(i,8))}}))}))})),e}(e,r)),this.emitInitSegment=!0},t.generateInitSegment=function(e){var t=this.audioCodec,i=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var r=this.initData=ve(e);r.audio&&(t=_n(r.audio,Q)),r.video&&(i=_n(r.video,J));var n={};r.audio&&r.video?n.audiovideo={container:"video/mp4",codec:t+","+i,supplemental:r.video.supplemental,initSegment:e,id:"main"}:r.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?n.video={container:"video/mp4",codec:i,supplemental:r.video.supplemental,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n},t.remux=function(e,t,i,r,n,s){var a,o,l=this.initPTS,h=this.lastEndTime,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};_(h)||(h=this.lastEndTime=n||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 i=0,r=0,n=0,s=ge(e,["moof","traf"]),a=0;a<s.length;a++){var o=s[a],l=ge(o,["tfhd"])[0],h=t[ue(l,4)];if(h){var u=h.default,d=ue(l,0)|(null==u?void 0:u.flags),c=null==u?void 0:u.duration;8&d&&(c=ue(l,2&d?12:8));for(var f=h.timescale||9e4,g=ge(o,["trun"]),p=0;p<g.length;p++)!(i=_e(g[p]))&&c&&(i=c*ue(g[p],4)),h.type===J?r+=i/f:h.type===Q&&(n+=i/f)}}if(0===r&&0===n){for(var v=1/0,m=0,y=0,E=ge(e,["sidx"]),S=0;S<E.length;S++){var T=pe(E[S]);if(null!=T&&T.references){v=Math.min(v,T.earliestPresentationTime/T.timescale);var L=T.references.reduce((function(e,t){return e+t.info.duration||0}),0);y=(m=Math.max(m,L+T.earliestPresentationTime/T.timescale))-v}}if(y&&_(y))return y}return r||n}(d,f),p=function(e,t){return ge(t,["moof","traf"]).reduce((function(t,i){var r=ge(i,["tfdt"])[0],n=r[0],s=ge(i,["tfhd"]).reduce((function(t,i){var s=ue(i,4),a=e[s];if(a){var o=ue(r,4);if(1===n){if(o===se)return $.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;o*=se+1,o+=ue(r,8)}var l=o/(a.timescale||9e4);if(_(l)&&(null===t||l<t))return l}return t}),null);return null!==s&&_(s)&&(null===t||s<t)?s:t}),null)}(f,d),v=null===p?n:p;!s&&l||!function(e,t,i,r){if(null===e)return!0;var n=Math.max(r,1),s=t-e.baseTime/e.timescale;return Math.abs(s-i)>n}(l,v,n,g)&&c.timescale===l.timescale||(c.initPTS=v-n,l&&1===l.timescale&&this.logger.warn("Adjusting initPTS @"+n+" from "+l.baseTime/l.timescale+" to "+c.initPTS),this.initPTS=l={baseTime:c.initPTS,timescale:1});var m=e?v-l.baseTime/l.timescale:h,y=m+g;!function(e,t,i){ge(t,["moof","traf"]).forEach((function(t){ge(t,["tfhd"]).forEach((function(r){var n=ue(r,4),s=e[n];if(s){var a=s.timescale||9e4;ge(t,["tfdt"]).forEach((function(e){var t=e[0],r=i*a;if(r){var n=ue(e,4);if(0===t)n-=r,fe(e,4,n=Math.max(n,0));else{n*=Math.pow(2,32),n+=ue(e,8),n-=r,n=Math.max(n,0);var s=Math.floor(n/(se+1)),o=Math.floor(n%(se+1));fe(e,4,s),fe(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:m,startDTS:m,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=En(i,n,l,l),r.samples.length&&(u.text=Sn(r,n,l)),u},e}();function _n(e,t){var i=null==e?void 0:e.codec;return i&&i.length>4?i:t===Q?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?He(i,!1):($.warn('Unhandled audio codec "'+i+'" in mp4 MAP'),i||"mp4a"):($.warn('Unhandled video codec "'+i+'" in mp4 MAP'),i||"avc1")}try{Tn=self.performance.now.bind(self.performance)}catch(e){Tn=Date.now}var bn=[{demux:jr,remux:Ln},{demux:tn,remux:mn},{demux:Hr,remux:mn},{demux:$r,remux:mn}];bn.splice(2,0,{demux:Kr,remux:mn});var An=function(){function e(e,t,i,r,n,s){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=s}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,i,r){var n=this,s=i.transmuxing;s.executeStart=Tn();var a=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var h=r||o,u=h.contiguous,d=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,p=h.initSegmentChange,v=l.audioCodec,m=l.videoCodec,y=l.defaultInitPts,E=l.duration,S=l.initSegmentData,T=function(e,t){var i=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t),i}(a,t);if(T&&ii(T.method)){var L=this.getDecrypter(),_=ri(T.method);if(!L.isSync())return this.asyncResult=!0,this.decryptionPromise=L.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,_).then((function(e){var t=n.push(e,null,i);return n.decryptionPromise=null,t})),this.decryptionPromise;var b=L.softwareDecrypt(a,T.key.buffer,T.iv.buffer,_);if(i.part>-1){var A=L.flush();b=A?A.buffer:A}if(!b)return s.executeEnd=Tn(),In(i);a=new Uint8Array(b)}var k=this.needsProbing(d,c);if(k){var D=this.configureTransmuxer(a);if(D)return this.logger.warn("[transmuxer] "+D.message),this.observer.emit(P.ERROR,P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),s.executeEnd=Tn(),In(i)}(d||c||p||k)&&this.resetInitSegment(S,v,m,E,t),(d||p||k)&&this.resetInitialTimestamp(y),u||this.resetContiguity();var w=this.transmux(a,T,g,f,i);this.asyncResult=Rn(w);var C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,s.executeEnd=Tn(),w},t.flush=function(e){var t=this,i=e.transmuxing;i.executeStart=Tn();var r=this.decrypter,n=this.currentTransmuxState,s=this.decryptionPromise;if(s)return this.asyncResult=!0,s.then((function(){return t.flush(e)}));var a=[],o=n.timeOffset;if(r){var l=r.flush();l&&a.push(this.push(l.buffer,null,e))}var h=this.demuxer,u=this.remuxer;if(!h||!u){i.executeEnd=Tn();var d=[In(e)];return this.asyncResult?Promise.resolve(d):d}var c=h.flush(o);return Rn(c)?(this.asyncResult=!0,c.then((function(i){return t.flushRemux(a,i,e),a}))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)},t.flushRemux=function(e,t,i){var r=t.audioTrack,n=t.videoTrack,s=t.id3Track,a=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,h=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+i.sn+(i.part>-1?" part: "+i.part:"")+" of "+(this.id===M?"level":"track")+" "+i.level);var u=this.remuxer.remux(r,n,s,a,h,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Tn()},t.resetInitialTimestamp=function(e){var t=this.demuxer,i=this.remuxer;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,i,r,n){var s=this.demuxer,a=this.remuxer;s&&a&&(s.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,n))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,i,r,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,n):this.transmuxUnencrypted(e,i,r,n)},t.transmuxUnencrypted=function(e,t,i,r){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),s=n.audioTrack,a=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(s,a,o,l,t,i,!1,this.id),chunkMeta:r}},t.transmuxSampleAes=function(e,t,i,r,n){var s=this;return this.demuxer.demuxSampleAes(e,t,i).then((function(e){return{remuxResult:s.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,s.id),chunkMeta:n}}))},t.configureTransmuxer=function(e){for(var t,i=this.config,r=this.observer,n=this.typeSupported,s=0,a=bn.length;s<a;s++){var o;if(null!=(o=bn[s].demux)&&o.probe(e,this.logger)){t=bn[s];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,h=this.remuxer,u=t.remux,d=t.demux;h&&h instanceof u||(this.remuxer=new u(r,i,n,this.logger)),l&&l instanceof d||(this.demuxer=new d(r,i,n,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 xt(this.config)),e},e}(),In=function(e){return{remuxResult:{},chunkMeta:e}};function Rn(e){return"then"in e&&e.then instanceof Function}var Pn=function(e,t,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null},kn=function(e,t,i,r,n,s){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=s},Dn=[];function wn(e,t,i){if(!((r=t.remuxResult).audio||r.video||r.text||r.id3||r.initSegment))return!1;var r,n=[],s=t.remuxResult,a=s.audio,o=s.video;return a&&Cn(n,a),o&&Cn(n,o),e.postMessage({event:"transmuxComplete",data:t,instanceNo:i},n),!0}function Cn(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function Mn(e,t,i,r){t.reduce((function(t,i){return wn(e,i,r)||t}),!1)||e.postMessage({event:"transmuxComplete",data:t[0],instanceNo:r}),e.postMessage({event:"flush",data:i,instanceNo:r})}function On(e,t,i){self.postMessage({event:e,data:t,instanceNo:i})}void 0!==i&&i&&self.addEventListener("message",(function(e){var t=e.data,i=t.instanceNo;if(void 0!==i){var r=Dn[i];if("reset"===t.cmd&&(delete Dn[t.resetNo],r&&r.destroy(),t.cmd="init"),"init"===t.cmd){var n=JSON.parse(t.config),s=new S;s.on(P.FRAG_DECRYPTED,On),s.on(P.ERROR,On);var a=W(n.debug,t.id);return function(e,t){var i=function(i){e[i]=function(e){On("workerLog",{logType:i,message:e},t)}};for(var r in e)i(r)}(a,i),Dn[i]=new An(s,t.typeSupported,n,"",t.id,a),void On("init",null,i)}if(r)switch(t.cmd){case"configure":r.configure(t.config);break;case"demux":var o=r.push(t.data,t.decryptdata,t.chunkMeta,t.state);Rn(o)?o.then((function(e){wn(self,e,i)})).catch((function(e){On(P.ERROR,{instanceNo:i,type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker push error"},i)})):wn(self,o,i);break;case"flush":var l=t.chunkMeta,h=r.flush(l);Rn(h)?h.then((function(e){Mn(self,e,l,i)})).catch((function(e){On(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t.chunkMeta,fatal:!1,error:e,err:e,reason:"transmuxer-worker flush error"},i)})):Mn(self,h,l,i)}}}));var xn="1.6.2",Fn={},Nn=0,Bn=function(){function e(e,i,r,n){var s=this;this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Nn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,i=s.hls;if(i&&null!=t&&t.event&&t.instanceNo===s.instanceNo)switch(t.event){case"init":var r,n=null==(r=s.workerContext)?void 0:r.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(t.data);break;case"flush":s.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=s.frag,t.data.part=s.part,t.data.id=s.id,i.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(s.hls){var t=new Error(e.message+" ("+e.filename+":"+e.lineno+")");s.hls.config.enableWorker=!1,s.hls.logger.warn('Error in "'+s.id+'" Web Worker, fallback to inline'),s.hls.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var a=e.config;this.hls=e,this.id=i,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;var o=function(e,t){(t=t||{}).frag=s.frag||void 0,e===P.ERROR&&(t.parent=s.id,t.part=s.part,s.error=t.error),s.hls.trigger(e,t)};this.observer=new S,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 "'+i+'"'),this.workerContext=function(e){var t=Fn[e];if(t)return t.clientCount++,t;var i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Fn[e]=r,r}(a.workerPath)):(h.log('injecting Web Worker for "'+i+'"'),this.workerContext=function(){var e=Fn[xn];if(e)return e.clientCount++,e;var i=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+t.toString()+")(true);"],{type:"text/javascript"}),r=self.URL.createObjectURL(i),n={worker:new self.Worker(r),objectURL:r,clientCount:1};return Fn[xn]=n,n}());var u=this.workerContext.worker;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:i,config:it(a)})}catch(t){h.warn('Error setting up "'+i+'" Web Worker, fallback to inline',t),this.terminateWorker(),this.error=null,this.transmuxer=new An(this.observer,l,a,"",i,e.logger)}}else this.transmuxer=new An(this.observer,l,a,"",i,e.logger)}var i=e.prototype;return i.reset=function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=Nn++;var t=this.hls.config,i=We(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:it(t)})}},i.terminateWorker=function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=Fn[e||xn];if(t&&1==t.clientCount--){var i=t.worker,r=t.objectURL;delete Fn[e||xn],r&&self.URL.revokeObjectURL(r),i.terminate()}}(this.hls.config.workerPath)}},i.destroy=function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null},i.push=function(e,t,i,r,n,s,a,o,l,h){var u,d,c=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,g=this.transmuxer,p=s?s.start:n.start,v=n.decryptdata,m=this.frag,y=!(m&&n.cc===m.cc),E=!(m&&l.level===m.level),S=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,L=0===S&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),_=!E&&(1===S||0===S&&(1===T||L&&T<=0)),b=self.performance.now();(E||S||0===n.stats.parsing.start)&&(n.stats.parsing.start=b),!s||!T&&_||(s.stats.parsing.start=b);var A=!(m&&(null==(u=n.initSegment)?void 0:u.url)===(null==(d=m.initSegment)?void 0:d.url)),I=new kn(y,_,o,E,p,A);if(!_||y||A){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+n.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===M?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+_+"\n accurateTimeOffset: "+o+"\n timeOffset: "+p+"\n initSegmentChange: "+A);var R=new Pn(i,r,t,a,h);this.configureTransmuxer(R)}if(this.frag=n,this.part=s,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:v,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(g){var P=g.push(e,v,l,I);Rn(P)?P.then((function(e){c.handleTransmuxComplete(e)})).catch((function(e){c.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(P)}},i.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var i=this.instanceNo,r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:i,cmd:"flush",chunkMeta:e});else if(r){var n=r.flush(e);Rn(n)?n.then((function(i){t.handleFlushResult(i,e)})).catch((function(i){t.transmuxerError(i,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}},i.transmuxerError=function(e,t,i){this.hls&&(this.error=e,this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))},i.handleFlushResult=function(e,t){var i=this;e.forEach((function(e){i.handleTransmuxComplete(e)})),this.onFlush(t)},i.configureTransmuxer=function(e){var t=this.instanceNo,i=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)},i.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}(),Un=function(e){function t(t,i,r){var n;return(n=e.call(this,t,i,r,"audio-stream-controller",O)||this).mainAnchor=null,n.mainFragLoading=null,n.audioOnly=!1,n.bufferedTrack=null,n.switchingTrack=null,n.trackId=-1,n.waitingData=null,n.mainDetails=null,n.flushing=!1,n.bufferFlushed=!1,n.cachedTrackLoadedData=null,n.registerListeners(),n}h(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.resetItem()},i.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(P.LEVEL_LOADED,this.onLevelLoaded,this),t.on(P.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(P.BUFFER_RESET,this.onBufferReset,this),t.on(P.BUFFER_CREATED,this.onBufferCreated,this),t.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(P.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(P.FRAG_LOADING,this.onFragLoading,this),t.on(P.FRAG_BUFFERED,this.onFragBuffered,this)},i.unregisterListeners=function(){var t=this.hls;t&&(e.prototype.unregisterListeners.call(this),t.off(P.LEVEL_LOADED,this.onLevelLoaded,this),t.off(P.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(P.BUFFER_RESET,this.onBufferReset,this),t.off(P.BUFFER_CREATED,this.onBufferCreated,this),t.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(P.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(P.FRAG_LOADING,this.onFragLoading,this),t.off(P.FRAG_BUFFERED,this.onFragBuffered,this))},i.onInitPtsFound=function(e,t){var i=t.frag,r=t.id,n=t.initPTS,s=t.timescale;if(r===M){var a=i.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:n,timescale:s},this.log("InitPTS for cc: "+a+" found from main: "+n+"/"+s),this.mainAnchor=i,this.state===er.WAITING_INIT_PTS){var l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==a)&&(this.nextLoadPosition=this.findSyncFrag(i).start),this.tick()}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(i).start,o.abortRequests(),this.resetLoadingState()):this.state===er.IDLE&&this.tick()}},i.findSyncFrag=function(e){var t=this.getLevelDetails(),i=e.cc;return function(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){var r=i.start,n=i.end,s=e.fragments;if(!i.relurl){var a=e.fragmentHint;a&&(s=s.concat(a))}return ct(s,(function(e){return e.cc<t||e.end<=r?1:e.cc>t||e.start>=n?-1:0}))}return null}(t,i,e)||t&&vt(t.fragments,i)||e},i.startLoad=function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=er.STOPPED);var i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i,this.state=er.IDLE):this.state=er.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.doTick=function(){switch(this.state){case er.IDLE:this.doTickIdle();break;case er.WAITING_TRACK:var t=this.levels,i=this.trackId,r=null==t?void 0:t[i],n=null==r?void 0:r.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=er.WAITING_INIT_PTS}break;case er.FRAG_LOADING_WAITING_RETRY:var s,a=performance.now(),o=this.retryDate;if(!o||a>=o||null!=(s=this.media)&&s.seeking){var l=this.levels,h=this.trackId;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==l?void 0:l[h])||null),this.state=er.IDLE}break;case er.WAITING_INIT_PTS:var u=this.waitingData;if(u){var d=u.frag,c=u.part,f=u.cache,g=u.complete,p=this.mainAnchor;if(void 0!==this.initPTS[d.cc]){this.waitingData=null,this.state=er.FRAG_LOADING;var v={frag:d,part:c,payload:f.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(v),g&&e.prototype._handleFragmentLoadComplete.call(this,v)}else p&&p.cc!==u.frag.cc&&(this.log("Waiting fragment cc ("+d.cc+") cancelled because video is at cc "+p.cc),this.nextLoadPosition=this.findSyncFrag(p).start,this.clearWaitingFragment())}else this.state=er.IDLE}this.onTickEnd()},i.clearWaitingFragment=function(){var e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==er.STOPPED&&(this.state=er.IDLE))},i.resetLoadingState=function(){this.clearWaitingFragment(),e.prototype.resetLoadingState.call(this)},i.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)},i.doTickIdle=function(){var e,t=this.hls,i=this.levels,r=this.media,n=this.trackId,s=t.config;if(this.buffering&&(r||this.primaryPrefetch||!this.startFragRequested&&s.startFragPrefetch)&&null!=i&&i[n]){var a=i[n],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=er.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Q,O));var h=this.getFwdBufferInfo(l,O);if(null!==h){if(!this.switchingTrack&&this._streamEnded(h,o))return t.trigger(P.BUFFER_EOS,{type:"audio"}),void(this.state=er.ENDED);var u=h.len,d=t.maxBufferLength,c=o.fragments,f=c[0].start,g=this.getLoadPosition(),p=this.flushing?g:h.end;if(this.switchingTrack&&r){var v=g;o.PTSKnown&&v<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(!(u>=d&&!this.switchingTrack&&p<c[c.length-1].start)){var m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,h,M,d)),m){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&te(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Rt&&(this.mainFragLoading=y=null),y&&te(y))){if(m.start>y.end){var E=this.fragmentTracker.getFragAtPos(p,M);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(m.start>y.end)return}this.loadFragment(m,a,p)}else this.bufferFlushed=!0}}}},i.onMediaDetaching=function(t,i){this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this,t,i)},i.onAudioTracksUpdated=function(e,t){var i=t.audioTracks;this.resetTransmuxer(),this.levels=i.map((function(e){return new et(e)}))},i.onAudioTrackSwitching=function(e,t){var i=!!t.url;this.trackId=t.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==er.STOPPED&&(this.setInterval(100),this.state=er.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},i.onLevelLoaded=function(e,t){this.mainDetails=t.details;var i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(P.AUDIO_TRACK_LOADED,i))},i.onAudioTrackLoaded=function(e,t){var i,r=this.levels,n=t.details,s=t.id,a=t.groupId,o=t.track;if(r){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==er.STOPPED&&(this.state=er.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+s+' "'+o.name+'" of "'+a+'" loaded ['+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration);var h=r[s],u=0;if(n.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var d;h.details&&(u=this.alignPlaylists(n,h.details,null==(d=this.levelLastLoaded)?void 0:d.details)),n.alignedSliding||(Ji(n,l),n.alignedSliding||Zi(n,l),u=n.fragmentStart)}h.details=n,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(P.AUDIO_TRACK_UPDATED,{details:n,id:s,groupId:t.groupId}),this.state!==er.WAITING_TRACK||this.waitForCdnTuneIn(n)||(this.state=er.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+s+' "'+o.name+'" of "'+a+'"')},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,n=e.payload,s=this.config,a=this.trackId,o=this.levels;if(o){var l=o[a];if(l){var h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);var u=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new Bn(this.hls,O,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){var g=r?r.index:-1,p=-1!==g,v=new Vt(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,p);d.push(n,f,u,"",i,r,h.totalduration,!1,v,c)}else this.log("Unknown video PTS for cc "+i.cc+", waiting for video PTS before demuxing audio frag "+i.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+a),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new rr,complete:!1}).cache.push(new Uint8Array(n)),this.state!==er.STOPPED&&(this.state=er.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},i.onBufferReset=function(){this.mediaBuffer=null},i.onBufferCreated=function(e,t){this.bufferFlushed=this.flushing=!1;var i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)},i.onFragLoading=function(e,t){!this.audioOnly&&t.frag.type===M&&te(t.frag)&&(this.mainFragLoading=t,this.state===er.IDLE&&this.tick())},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part;if(i.type===O)if(this.fragContextChanged(i))this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if(te(i)){this.fragPrevious=i;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(P.AUDIO_TRACK_SWITCHED,c({},n)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==M||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},i.onError=function(t,i){var r;if(i.fatal)this.state=er.ERROR;else switch(i.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(O,i);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==er.WAITING_TRACK||(null==(r=i.context)?void 0:r.type)!==w||(this.state=er.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if("audio"!==i.parent)return;this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if("audio"!==i.parent)return;this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}},i.onBufferFlushing=function(e,t){t.type!==J&&(this.flushing=!0)},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==J){this.flushing=!1,this.bufferFlushed=!0,this.state===er.ENDED&&(this.state=er.IDLE);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,O),this.tick())}},i._handleTransmuxComplete=function(e){var t,i="audio",r=this.hls,n=e.remuxResult,s=e.chunkMeta,a=this.getCurrentContext(s);if(a){var l=a.frag,h=a.part,u=a.level,d=u.details,c=n.audio,f=n.text,g=n.id3,p=n.initSegment;if(!this.fragContextChanged(l)&&d){if(this.state=er.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){var v=l.initSegment||l;this._bufferInitSegment(u,p.tracks,v,s),r.trigger(P.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:p.tracks})}if(c){var m=c.startPTS,y=c.endPTS,E=c.startDTS,S=c.endDTS;h&&(h.elementaryStreams[Q]={startPTS:m,endPTS:y,startDTS:E,endDTS:S}),l.setElementaryStreamInfo(Q,m,y,E,S),this.bufferFragmentData(c,l,h,s)}if(null!=g&&null!=(t=g.samples)&&t.length){var T=o({id:i,frag:l,details:d},g);r.trigger(P.FRAG_PARSING_METADATA,T)}if(f){var L=o({id:i,frag:l,details:d},f);r.trigger(P.FRAG_PARSING_USERDATA,L)}}else this.fragmentTracker.removeFragment(l)}else this.resetWhenMissingContext(s)},i._bufferInitSegment=function(e,t,i,r){if(this.state===er.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=O;var s=e.audioCodec;this.log("Init audio buffer, container:"+n.container+", codecs[level/parsed]=["+s+"/"+n.codec+"]"),s&&1===s.split(",").length&&(n.levelCodec=s),this.hls.trigger(P.BUFFER_CODECS,t);var a=n.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(P.BUFFER_APPENDING,o)}this.tickImmediate()}},i.loadFragment=function(t,i,r){var n,s=this.fragmentTracker.getState(t);if(this.switchingTrack||s===bt||s===It)if(te(t))if(null!=(n=i.details)&&n.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=er.WAITING_INIT_PTS;var a=this.mainDetails;a&&a.fragmentStart!==i.details.fragmentStart&&Zi(i.details,a)}else e.prototype.loadFragment.call(this,t,i,r);else this._loadInitSegment(t,i);else this.clearTrackerIfNeeded(t)},i.flushAudioIfNeeded=function(t){if(this.media&&this.bufferedTrack){var i=this.bufferedTrack;ot({name:i.name,lang:i.lang,assocLang:i.assocLang,characteristics:i.characteristics,audioCodec:i.audioCodec,channels:i.channels},t,lt)||(ut(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}},i.completeAudioSwitch=function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(P.AUDIO_TRACK_SWITCHED,c({},e))},t}(tr),Gn=function(e){function t(t,i){var r;return(r=e.call(this,i,t.logger)||this).hls=void 0,r.canLoad=!1,r.timer=-1,r.hls=t,r}h(t,e);var i=t.prototype;return i.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},i.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},i.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},i.stopLoad=function(){this.canLoad=!1,this.clearTimer()},i.switchParams=function(e,t,i){var r=null==t?void 0:t.renditionReports;if(r){for(var n=-1,s=0;s<r.length;s++){var a=r[s],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){n=s;break}o===e.substring(0,o.length)&&(n=s)}if(-1!==n){var l=r[n],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=i&&Je(i);return new Ze(h,u>=0?u:void 0,c)}}},i.loadPlaylist=function(e){this.clearTimer()},i.loadingPlaylist=function(e,t){this.clearTimer()},i.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},i.getUrlWithDirectives=function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}return e},i.playlistLoaded=function(e,t,i){var r=t.details,n=t.stats,s=self.performance.now(),a=n.loading.first?Math.max(0,s-n.loading.first):0;r.advancedDateTime=Date.now()-a;var o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){var l=Math.max(o||0,0);r.appliedTimelineOffset=l,r.fragments.forEach((function(e){e.start=e.playlistOffset+l}))}if(r.live||null!=i&&i.live){var h="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){Gi(i,r);var u=r.playlistParsingError;if(u){this.warn(u);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var c,f=t.networkDetails;return void d.trigger(P.ERROR,{type:I.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:u,reason:u.message,level:t.level||void 0,parent:null==(c=r.fragments[0])?void 0:c.type,networkDetails:f,stats:n})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=n.loading.start);var g,p=this.hls.mainForwardBufferInfo,v=p?p.end-p.len:0,m=Wi(r,1e3*(r.edge-v));if(r.requestScheduled+m<s?r.requestScheduled=s:r.requestScheduled+=m,this.log("live playlist "+e+" "+(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;var y=void 0,E=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){var S=this.hls.config.lowLatencyMode,T=r.lastPartSn,L=r.endSN,_=r.lastPartIndex,b=T===L;-1!==_?b?(y=L+1,E=S?0:_):(y=T,E=S?_+1:r.maxPartIndex):y=L+1;var A=r.age,k=A+r.ageHeader,D=Math.min(k-r.partTarget,1.5*r.targetduration);if(D>0){if(k>3*r.targetduration)this.log("Playlist last advanced "+A.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=i&&i.tuneInGoal&&k-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+i.tuneInGoal+" to: "+D+" with playlist age: "+r.age),D=0;else{var w=Math.floor(D/r.targetduration);y+=w,void 0!==E&&(E+=Math.round(D%r.targetduration/r.partTarget)),this.log("CDN Tune-in age: "+r.ageHeader+"s last advanced "+A.toFixed(2)+"s goal: "+D+" skip sn "+w+" to part "+E)}r.tuneInGoal=D}if(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E),S||!b)return r.requestScheduled=s,void this.loadingPlaylist(h,g)}else(r.canBlockReload||r.canSkipUntil)&&(g=this.getDeliveryDirectives(r,t.deliveryDirectives,y,E));g&&void 0!==y&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-2*a,m/2)),this.scheduleLoading(h,g,r)}else this.clearTimer()},i.scheduleLoading=function(e,t,i){var r=this,n=i||e.details;if(n){var s=self.performance.now(),a=n.requestScheduled;if(s>=a)this.loadingPlaylist(e,t);else{var o=a-s;this.log("reload live playlist "+(e.name||e.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return r.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},i.getDeliveryDirectives=function(e,t,i,r){var n=Je(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=""),new Ze(i,r,n)},i.checkRetry=function(e){var t=this,i=e.details,r=mt(e),n=e.errorAction,s=n||{},a=s.action,o=s.retryCount,l=void 0===o?0:o,h=s.retryConfig,u=!!n&&!!h&&(5===a||!n.resolved&&2===a);if(u){var d;if(l>=h.maxNumRetry)return!1;if(r&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" without delivery-directives'),this.loadPlaylist();else{var c=Et(h,l);this.clearTimer(),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" in '+c+"ms")}e.levelRetry=!0,n.resolved=!0}return u},t}(B);function Hn(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(!Vn(e[i].attrs,t[i].attrs))return!1;return!0}function Vn(e,t,i){var r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((function(i){return e[i]!==t[i]}))}function Kn(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var Wn=function(e){function t(t){var i;return(i=e.call(this,t,"audio-track-controller")||this).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.registerListeners(),i}h(t,e);var i=t.prototype;return i.registerListeners=function(){var e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(P.ERROR,this.onError,this)},i.unregisterListeners=function(){var e=this.hls;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(P.ERROR,this.onError,this)},i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,e.prototype.destroy.call(this)},i.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.audioTracks||[]},i.onAudioTrackLoaded=function(e,t){var i=t.id,r=t.groupId,n=t.details,s=this.tracksInGroup[i];if(s&&s.groupId===r){var a=s.details;s.details=t.details,this.log("Audio track "+i+' "'+s.name+'" lang:'+s.lang+" group:"+r+" loaded ["+n.startSN+"-"+n.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Audio track with id:"+i+" and group:"+r+" not found in active group "+(null==s?void 0:s.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var s=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(s.length)this.selectDefaultTrack&&!s.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),s.forEach((function(e,t){e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=s;var a=this.hls.config.audioPreference;if(!n&&a){var o=at(a,s,lt);if(o>-1)n=s[o];else{var l=at(a,this.tracks);n=this.tracks[l]}}var h=this.findTrackId(n);-1===h&&n&&(h=this.findTrackId(null));var u={audioTracks:s};this.log("Updating audio tracks, "+s.length+" track(s) found in group(s): "+(null==i?void 0:i.join(","))),this.hls.trigger(P.AUDIO_TRACKS_UPDATED,u);var d=this.trackId;if(-1!==h&&-1===d)this.setAudioTrack(h);else if(s.length&&-1===d){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+s.length);this.warn(f.message),this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==w||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&ot(e,r,lt))return r;var n=at(e,this.tracksInGroup,lt);if(n>-1){var s=this.tracksInGroup[n];return this.setAudioTrack(n),s}if(r){var a=t.loadLevel;-1===a&&(a=t.firstAutoLevel);var o=function(e,t,i,r,n){var s=t[r],a=t.reduce((function(e,t,i){var r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[s.uri];a.length>1&&(r=Math.max.apply(Math,a));var o=s.videoRange,l=s.frameRate,h=s.codecSet.substring(0,4),u=ht(t,r,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;var r=t.audioGroups,s=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return at(e,s,n)>-1}));return u>-1?u:ht(t,r,(function(t){var r=t.audioGroups,s=i.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));return at(e,s,n)>-1}))}(e,t.levels,i,a,lt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=at(e,i);if(l>-1)return i[l]}}}return null},i.setAudioTrack=function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(!(e===this.trackId&&r===i&&n||(this.log("Switching to audio-track "+e+' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId+" channels:"+r.channels),this.trackId=e,this.currentTrack=r,this.hls.trigger(P.AUDIO_TRACK_SWITCHING,c({},r)),n))){var s=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(s)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=0;i<t.length;i++){var r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||ot(e,r,lt)))return i}if(e){for(var n=e.name,s=e.lang,a=e.assocLang,o=e.characteristics,l=e.audioCodec,h=e.channels,u=0;u<t.length;u++)if(ot({name:n,lang:s,assocLang:a,characteristics:o,audioCodec:l,channels:h},t[u],lt))return u;for(var d=0;d<t.length;d++){var c=t[d];if(Vn(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var g=t[f];if(Vn(e.attrs,g.attrs,["LANGUAGE"]))return f}}return-1},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var i=this.currentTrack;this.shouldLoadPlaylist(i)&&ut(i.url,this.hls)&&this.scheduleLoading(i,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,n=t.groupId,s=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading audio-track "+r+' "'+t.name+'" lang:'+t.lang+" group:"+n+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+s),this.hls.trigger(P.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:i||null,track:t})},n(t,[{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}}])}(Gn),$n=function(){function e(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}var t=e.prototype;return t.destroy=function(){this.tracks=this.queues=null},t.append=function(e,t,i){if(null!==this.queues&&null!==this.tracks){var r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}},t.appendBlocker=function(e){var t=this;return new Promise((function(i){var r={label:"async-blocker",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(r,e)}))},t.prependBlocker=function(e){var t=this;return new Promise((function(i){if(t.queues){var r={label:"async-blocker-prepend",execute:i,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(r)}}))},t.removeBlockers=function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((function(e){var t,i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))}))},t.unblockAudio=function(e){null!==this.queues&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")},t.executeNext=function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var i=t[0];try{i.execute()}catch(t){var r;if(i.onError(t),null===this.queues||null===this.tracks)return;var n=null==(r=this.tracks[e])?void 0:r.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}},t.shiftAndExecuteNext=function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))},t.current=function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null},t.toString=function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},t.list=function(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?"SourceBuffer"+(r.updating?" updating":"")+(i.ended?" ended":"")+(i.ending?" ending":""):"none"},t.listOps=function(e){var t;return(null==(t=this.queues)?void 0:t[e].map((function(e){return e.label})).join(", "))||""},e}(),qn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,jn="HlsJsTrackRemovedError",Yn=function(e){function t(t){var i;return(i=e.call(this,t)||this).name=jn,i}return h(t,e),t}(p(Error)),zn=function(e){function t(t,i){var r,n;return(r=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,r.fragmentTracker=void 0,r.details=null,r._objectUrl=null,r.operationQueue=null,r.bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.lastMpegAudioChunk=null,r.blockedAudioAppend=null,r.lastVideoAppendEnd=0,r.appendSource=void 0,r.transferData=void 0,r.overrides=void 0,r.appendErrors={audio:0,video:0,audiovideo:0},r.tracks={},r.sourceBuffers=[[null,null],[null,null]],r._onEndStreaming=function(e){var t;r.hls&&"open"===(null==(t=r.mediaSource)?void 0:t.readyState)&&r.hls.pauseBuffering()},r._onStartStreaming=function(e){r.hls&&r.hls.resumeBuffering()},r._onMediaSourceOpen=function(e){var t=r,i=t.media,n=t.mediaSource;e&&r.log("Media source opened"),i&&n&&(n.removeEventListener("sourceopen",r._onMediaSourceOpen),i.removeEventListener("emptied",r._onMediaEmptied),r.updateDuration(),r.hls.trigger(P.MEDIA_ATTACHED,{media:i,mediaSource:n}),null!==r.mediaSource&&r.checkPendingTracks())},r._onMediaSourceClose=function(){r.log("Media source closed")},r._onMediaSourceEnded=function(){r.log("Media source ended")},r._onMediaEmptied=function(){var e=r,t=e.mediaSrc,i=e._objectUrl;t!==i&&r.error("Media element src was set while attaching MediaSource ("+i+" > "+t+")")},r.hls=t,r.fragmentTracker=i,r.appendSource=(n=q(t.config.preferManagedMediaSource),"undefined"!=typeof self&&n===self.ManagedMediaSource),r.initTracks(),r.registerListeners(),r}h(t,e);var i=t.prototype;return i.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},i.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null},i.registerListeners=function(){var e=this.hls;e.on(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)},i.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)},i.transferMedia=function(){var e=this,t=this.media,i=this.mediaSource;if(!t)return null;var r={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var s=this.isQueued();(n||s)&&this.warn("Transfering MediaSource with"+(s?" operations in queue":"")+(n?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var a=this.transferData;return!this.sourceBufferCount&&a&&a.mediaSource===i?o(r,a.tracks):this.sourceBuffers.forEach((function(t){var i=t[0];i&&(r[i]=o({},e.tracks[i]),e.removeBuffer(i)),t[0]=t[1]=null})),{media:t,mediaSource:i,tracks:r}},i.initTracks=function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},i.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},i.onManifestParsed=function(e,t){var i,r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(r+" bufferCodec event(s) expected."),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()},i.onMediaAttaching=function(e,t){var i=this.media=t.media,r=q(this.appendSource);if(this.transferData=this.overrides=void 0,i&&r){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var s=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(s),n)this._objectUrl=i.src,this.attachTransferred();else{var a=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&s instanceof o,Xn(i),function(e,t){var i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,a),i.load()}catch(e){i.src=a}else i.src=a}i.addEventListener("emptied",this._onMediaEmptied)}},i.assignMediaSource=function(e){var t,i;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(i=e.constructor)?void 0:i.name)),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))},i.attachTransferred=function(){var e=this,t=this.media,i=this.transferData;if(i&&t){var r=this.tracks,n=i.tracks,s=n?Object.keys(n):null,a=s?s.length:0,o=function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()};if(n&&s&&a){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+it(r,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+it(n,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!j(n,r)){i.mediaSource=null,i.tracks=void 0;var l=t.currentTime,h=this.details,u=Math.max(l,(null==h?void 0:h.fragments[0].start)||0);return u-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+u):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(n)+'"->"'+Object.keys(r)+'") start time: '+u+" currentTime: "+l),this.onMediaDetaching(P.MEDIA_DETACHING,{}),this.onMediaAttaching(P.MEDIA_ATTACHING,i),void(t.currentTime=u))}this.transferData=void 0,s.forEach((function(t){var i=t,r=n[i];if(r){var s=r.buffer;if(s){var a=e.fragmentTracker,o=r.id;if(a.hasFragments(o)||a.hasParts(o)){var l=Wt.getBuffered(s);a.detectEvictedFragments(i,l,o,null,!0)}var h=Qn(i),u=[i,s];e.sourceBuffers[h]=u,s.updating&&e.operationQueue&&e.operationQueue.prependBlocker(i),e.trackSourceBuffer(i,r)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},i.onMediaDetaching=function(e,t){var i=this,r=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,s=this.mediaSource,a=this._objectUrl;if(s){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===s.readyState;try{for(var l=s.sourceBuffers,h=l.length;h--;)o&&l[h].abort(),s.removeSourceBuffer(l[h]);o&&s.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(n.removeAttribute("src"),this.appendSource&&Xn(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(P.MEDIA_DETACHED,t)},i.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];i&&e.resetBuffer(i)})),this.initTracks()},i.resetBuffer=function(e){var t,i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},i.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[Qn(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)},i.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new $n(this.tracks)},i.onBufferCodecs=function(e,t){var i=this,r=this.tracks,n=Object.keys(t);this.log('BUFFER_CODECS: "'+n+'" (current SB count '+this.sourceBufferCount+")");var s="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),a=!s&&this.sourceBufferCount&&this.media&&n.some((function(e){return!r[e]}));s||a?this.warn('Unsupported transition between "'+Object.keys(r)+'" and "'+n+'" SourceBuffers'):(n.forEach((function(e){var n,s,a,o=t[e],l=o.id,h=o.codec,u=o.levelCodec,d=o.container,c=o.metadata,f=o.supplemental,g=r[e],p=null==(n=i.transferData)||null==(s=n.tracks)?void 0:s[e],v=null!=p&&p.buffer?p:g,m=(null==v?void 0:v.pendingCodec)||(null==v?void 0:v.codec),y=null==v?void 0:v.levelCodec;g||(g=r[e]={buffer:void 0,listeners:[],codec:h,supplemental:f,container:d,levelCodec:u,metadata:c,id:l});var E=Ve(m,y),S=null==E?void 0:E.replace(qn,"$1"),T=Ve(h,u),L=null==(a=T)?void 0:a.replace(qn,"$1");T&&E&&S!==L&&("audio"===e.slice(0,5)&&(T=He(T,i.appendSource)),i.log("switching codec "+m+" to "+T),T!==(g.pendingCodec||g.codec)&&(g.pendingCodec=T),g.container=d,i.appendChangeType(e,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())},i.appendChangeType=function(e,t,i){var r=this,n=t+";codecs="+i,s={label:"change-type="+n,execute:function(){var s=r.tracks[e];if(s){var a=s.buffer;null!=a&&a.changeType&&(r.log("changing "+e+" sourceBuffer type to "+n),a.changeType(n),s.codec=i,s.container=t)}r.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(s,e,this.isPending(this.tracks[e]))},i.blockAudio=function(e){var t,i=this,r=e.start,n=r+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(r,M))?void 0:t.gap)){var s={label:"block-audio",execute:function(){var e,t=i.tracks.video;(i.lastVideoAppendEnd>n||null!=t&&t.buffer&&Wt.isBuffered(t.buffer,n)||!0===(null==(e=i.fragmentTracker.getAppendedFrag(n,M))?void 0:e.gap))&&(i.blockedAudioAppend=null,i.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){i.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:s,frag:e},this.append(s,"audio",!0)}},i.unblockAudio=function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))},i.onBufferAppending=function(e,t){var i=this,r=this.tracks,n=t.data,s=t.type,a=t.parent,o=t.frag,l=t.part,h=t.chunkMeta,u=h.buffering[s],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=r.audio,v=!1;"audio"===s&&"audio/mpeg"===(null==p?void 0:p.container)&&(v=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var m=this.tracks.video,y=null==m?void 0:m.buffer;if(y&&"initSegment"!==d){var E=l||o,S=this.blockedAudioAppend;if("audio"!==s||"main"===a||this.blockedAudioAppend){if("video"===s){var T=E.end;if(S){var L=S.frag.start;(T>L||T<this.lastVideoAppendEnd||Wt.isBuffered(y,L))&&this.unblockAudio()}this.lastVideoAppendEnd=T}}else{var _=E.start+.05*E.duration,b=y.buffered,A=this.currentOp("video");b.length||A?!A&&!Wt.isBuffered(y,_)&&this.lastVideoAppendEnd<_&&this.blockAudio(E):this.blockAudio(E)}}var k=(l||o).start,D={label:"append-"+s,execute:function(){if(u.executeStart=self.performance.now(),v){var e=i.tracks[s];if(e){var t=e.buffer;if(t){var r=k-t.timestampOffset;Math.abs(r)>=.1&&(i.log("Updating audio SourceBuffer timestampOffset to "+k+" (delta: "+r+") sn: "+d+")"),t.timestampOffset=k)}}}i.appendExecutor(n,s)},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={};i.sourceBuffers.forEach((function(e){var i=e[0],r=e[1];i&&(t[i]=Wt.getBuffered(r))})),i.appendErrors[s]=0,"audio"===s||"video"===s?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(P.BUFFER_APPENDED,{type:s,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:t})},onError:function(e){var t,r={type:I.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1},n=null==(t=i.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR)r.details=R.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&i.mediaSourceOpenOrEnded&&!n)r.errorAction=_t(!0);else if(e.name===jn&&0===i.sourceBufferCount)r.errorAction=_t(!0);else{var a=++i.appendErrors[s];i.warn("Failed "+a+"/"+i.hls.config.appendErrorMaxRetry+' times to append segment in "'+s+'" sourceBuffer ('+(n||"no media error")+")"),(a>=i.hls.config.appendErrorMaxRetry||n)&&(r.fatal=!0)}i.hls.trigger(P.ERROR,r)}};this.append(D,s,this.isPending(this.tracks[s]))},i.getFlushOp=function(e,t,i){var r=this;return this.log('queuing "'+e+'" remove '+t+"-"+i),{label:"remove",execute:function(){r.removeExecutor(e,t,i)},onStart:function(){},onComplete:function(){r.hls.trigger(P.BUFFER_FLUSHED,{type:e})},onError:function(n){r.warn("Failed to remove "+t+"-"+i+' from "'+e+'" SourceBuffer',n)}}},i.onBufferFlushing=function(e,t){var i=this,r=t.type,n=t.startOffset,s=t.endOffset;r?this.append(this.getFlushOp(r,n,s),r):this.sourceBuffers.forEach((function(e){var t=e[0];t&&i.append(i.getFlushOp(t,n,s),t)}))},i.onFragParsed=function(e,t){var i=this,r=t.frag,n=t.part,s=[],a=n?n.elementaryStreams:r.elementaryStreams;a[Z]?s.push("audiovideo"):(a[Q]&&s.push("audio"),a[J]&&s.push("video")),0===s.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+r.type+" level: "+r.level+" sn: "+r.sn),this.blockBuffers((function(){var e=self.performance.now();r.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:r.stats;i.hls.trigger(P.FRAG_BUFFERED,{frag:r,part:n,stats:t,id:r.type})}),s).catch((function(e){i.warn("Fragment buffered callback "+e),i.stepOperationQueue(i.sourceBufferTypes)}))},i.onFragChanged=function(e,t){this.trimBuffers()},i.onBufferEos=function(e,t){var i,r=this;this.sourceBuffers.forEach((function(e){var i=e[0];if(i){var n=r.tracks[i];t.type&&t.type!==i||(n.ending=!0,n.ended||(n.ended=!0,r.log(i+" buffer reached EOS")))}}));var n=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,i=e[0];return i&&!(null!=(t=r.tracks[i])&&t.ended)}))&&(n?(this.log("Queueing EOS"),this.blockUntilOpen((function(){r.tracksEnded();var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream(),r.hls.trigger(P.BUFFERED_TO_END,void 0)):e&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(P.BUFFERED_TO_END,void 0)))},i.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var i=t[0];if(null!==i){var r=e.tracks[i];r&&(r.ending=!1)}}))},i.onLevelUpdated=function(e,t){var i=t.details;i.fragments.length&&(this.details=i,this.updateDuration())},i.updateDuration=function(){var e=this,t=this.getDurationAndRange();t&&this.blockUntilOpen((function(){return e.updateMediaSource(t)}))},i.onError=function(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var i,r=null==(i=t.errorAction)?void 0:i.nextAutoLevel;_(r)&&r!==t.frag.level&&this.resetAppendErrors()}},i.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},i.trimBuffers=function(){var e=this.hls,t=this.details,i=this.media;if(i&&null!==t&&this.sourceBufferCount){var r=e.config,n=i.currentTime,s=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(_(a)&&a>=0){var o=Math.max(a,s),l=Math.floor(n/s)*s-o;this.flushBackBuffer(n,s,l)}if(_(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){var h=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),u=Math.max(h,s),d=Math.floor(n/s)*s+u;this.flushFrontBuffer(n,s,d)}}},i.flushBackBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(e){var t=e[0],n=e[1];if(n){var s=Wt.getBuffered(n);if(s.length>0&&i>s.start(0)){var a;r.hls.trigger(P.BACK_BUFFER_REACHED,{bufferEnd:i});var o=r.tracks[t];if(null!=(a=r.details)&&a.live)r.hls.trigger(P.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=o&&o.ended)return void r.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");r.hls.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}}))},i.flushFrontBuffer=function(e,t,i){var r=this;this.sourceBuffers.forEach((function(t){var n=t[0],s=t[1];if(s){var a=Wt.getBuffered(s),o=a.length;if(o<2)return;var l=a.start(o-1),h=a.end(o-1);if(i>l||e>=l&&e<=h)return;r.hls.trigger(P.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}}))},i.getDurationAndRange=function(){var e,t=this.details,i=this.mediaSource;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;var r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&t.live&&i.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,r)}}return{duration:1/0}}var s=null==(e=this.overrides)?void 0:e.duration;if(s)return _(s)?{duration:s}:null;var a=this.media.duration;return r>(_(i.duration)?i.duration:0)&&r>a||!_(a)?{duration:r}:null},i.updateMediaSource=function(e){var t=e.duration,i=e.start,r=e.end,n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==t&&(_(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),n.duration=t),void 0!==i&&void 0!==r&&(this.log("MediaSource duration is set to "+n.duration+". Setting seekable range to "+i+"-"+r+"."),n.setLiveSeekableRange(i,r)))},i.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,i=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+it(i)),this.tracksReady){var r,n=null==(r=this.transferData)?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}},i.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(i){var r=i[0],n=i[1];if(r){var s=e.tracks[r];t[r]={buffer:n,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}})),this.hls.trigger(P.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var i=t[0];e.executeNext(i)}))}else{var i=new Error("could not create source buffer for media codec(s)");this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:i,reason:i.message})}},i.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,i=this.mediaSource;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(var r in e){var n=r,s=e[n];if(this.isPending(s)){var a=this.getTrackCodec(s,n),o=s.container+";codecs="+a;s.codec=a,this.log("creating sourceBuffer("+o+")"+(this.currentOp(n)?" Queued":"")+" "+it(s));try{var l=i.addSourceBuffer(o),h=Qn(n),u=[n,l];t[h]=u,s.buffer=l}catch(e){var d;return this.error("error while trying to add sourceBuffer: "+e.message),this.shiftAndExecuteNext(n),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[n],void this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:s.id})}this.trackSourceBuffer(n,s)}}this.bufferCreated()},i.getTrackCodec=function(e,t){var i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&Oe(i,"video")&&(r=function(e,t){var i=[];if(e)for(var r=e.split(","),n=0;n<r.length;n++)Me(r[n],"video")||i.push(r[n]);return t&&i.push(t),i.join(",")}(r,i));var n=Ve(r,e.levelCodec);return n?"audio"===t.slice(0,5)?He(n,this.appendSource):n:""},i.trackSourceBuffer=function(e,t){var i=this,r=t.buffer;if(r){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(function(e,t){var r=t.removedRanges;null!=r&&r.length&&i.hls.trigger(P.BUFFER_FLUSHED,{type:e})}))}},i.onSBUpdateStart=function(e){var t=this.currentOp(e);t&&t.onStart()},i.onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)},i.onSBUpdateError=function(e,t){var i,r=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(i=this.mediaSource)?void 0:i.readyState));this.error(""+r,t),this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});var n=this.currentOp(e);n&&n.onError(r)},i.removeExecutor=function(e,t,i){var r=this.media,n=this.mediaSource,s=this.tracks[e],a=null==s?void 0:s.buffer;if(!r||!n||!a)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(e);var o=_(r.duration)?r.duration:1/0,l=_(n.duration)?n.duration:1/0,h=Math.max(0,t),u=Math.min(i,o,l);u>h&&(!s.ending||s.ended)?(s.ended=!1,this.log("Removing ["+h+","+u+"] from the "+e+" SourceBuffer"),a.remove(h,u)):this.shiftAndExecuteNext(e)},i.appendExecutor=function(e,t){var i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new Yn("Attempting to append to the "+t+" SourceBuffer, but it does not exist");i.ending=!1,i.ended=!1,r.appendBuffer(e)},i.blockUntilOpen=function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((function(e){t.warn("SourceBuffer blocked callback "+e),t.stepOperationQueue(t.sourceBufferTypes)}));else try{e()}catch(e){this.warn("Callback run without blocking "+this.operationQueue+" "+e)}},i.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],i=e[1];return t&&i.updating}))},i.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var i=t[0];return i&&!!e.currentOp(i)}))},i.isPending=function(e){return!!e&&!e.buffer},i.blockBuffers=function(e,t){var i=this;if(void 0===t&&(t=this.sourceBufferTypes),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var r=this.operationQueue,n=t.map((function(e){return i.appendBlocker(e)}));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then((function(t){r===i.operationQueue&&(e(),i.stepOperationQueue(i.sourceBufferTypes))}))},i.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var i,r=null==(i=t.tracks[e])?void 0:i.buffer;r&&!r.updating&&t.shiftAndExecuteNext(e)}))},i.append=function(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)},i.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},i.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},i.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},i.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},i.addBufferListener=function(e,t,i){var r=this.tracks[e];if(r){var n=r.buffer;if(n){var s=i.bind(this,e);r.listeners.push({event:t,listener:s}),n.addEventListener(t,s)}}},i.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var i=t.buffer;i&&(t.listeners.forEach((function(e){i.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},n(t,[{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){var r=e.tracks[i];return t[i]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var i,r,n=t[0];return n&&(!(null!=(i=e.tracks[n])&&i.ended)||(null==(r=e.tracks[n])?void 0:r.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,i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,i){return t+(e.isPending(e.tracks[i])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(e,t){return e+(t[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(e){return e[0]})).filter((function(e){return!!e}))}}])}(B);function Xn(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function Qn(e){return"audio"===e?1:0}var Jn,Zn=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 i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})},t.onMediaAttaching=function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},t.onManifestParsed=function(e,t){var i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&_(this.autoLevelCapping)&&this.detectPlayerSize()},t.onBufferCodecs=function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping(),this.media=null},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+i+": "+e[i].height+"p@"+e[i].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var i=this,r=this.hls.levels;if(!r.length)return-1;var n=r.filter((function(e,r){return i.isLevelAllowed(e)&&r<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},t.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,i){if(null==e||!e.length)return-1;for(var r,n,s=e.length-1,a=Math.max(t,i),o=0;o<e.length;o+=1){var l=e[o];if((l.width>=a||l.height>=a)&&(r=l,!(n=e[o+1])||r.width!==n.width||r.height!==n.height)){s=o;break}}return s},n(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)}}])}(),es="m",ts="a",is="v",rs="av",ns="i",ss="tt",as="h",os="CMCD-Request",ls="CMCD-Session",hs="CMCD-Status",us=((Jn={})["CMCD-Object"]=["br","d","ot","tb"],Jn[os]=["bl","dl","mtp","nor","nrr","su"],Jn[ls]=["cid","pr","sf","sid","st","v"],Jn[hs]=["bs","rtp"],Jn),ds=function e(t,i){Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=i},cs="Dict";function fs(e,t,i){return function(e,t,i,r){return new Error("failed to "+e+' "'+(n=t,(Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n))+'" as ')+i,{cause:r});var n}("serialize",e,t,i)}var gs=function(e){this.description=e},ps="Bare Item",vs="Boolean",ms="Byte Sequence";var ys="Integer";function Es(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw fs(e,ys);return e.toString()}var Ss="Decimal";function Ts(e){var t=mr(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw fs(e,Ss);var i=t.toString();return i.includes(".")?i:i+".0"}var Ls="String",_s=/[\x00-\x1f\x7f]+/,bs="Token";function As(e){var t,i=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(i))throw fs(i,bs);return i}function Is(e){switch(typeof e){case"number":if(!_(e))throw fs(e,ps);return Number.isInteger(e)?Es(e):Ts(e);case"string":return function(e){if(_s.test(e))throw fs(e,Ls);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(e);case"symbol":return As(e);case"boolean":return function(e){if("boolean"!=typeof e)throw fs(e,vs);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@"+Es(e.getTime()/1e3)}(e);if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw fs(e,ms);return":"+(t=e,btoa(String.fromCharCode.apply(String,t))+":");var t}(e);if(e instanceof gs)return As(e);default:throw fs(e,ps)}}var Rs="Key";function Ps(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw fs(e,Rs);return e}function ks(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],i=e[1];return!0===i?";"+Ps(t):";"+Ps(t)+"="+Is(i)})).join("")}function Ds(e){return e instanceof ds?""+Is(e.value)+ks(e.params):Is(e)}var ws=function(e){return Math.round(e)},Cs=function(e){return 100*ws(e/100)},Ms={br:ws,d:ws,bl:Cs,dl:Cs,mtp:Cs,nor:function(e,t){return(null==t?void 0:t.baseUrl)&&(e=function(e,t){var i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;for(var n=i.pathname.split("/").slice(1),s=r.pathname.split("/").slice(1,-1);n[0]===s[0];)n.shift(),s.shift();for(;s.length;)s.shift(),n.unshift("..");return n.join("/")}(e,t.baseUrl)),encodeURIComponent(e)},rtp:Cs,tb:ws};function Os(e,t){return void 0===t&&(t={}),e?function(e,t){return function(e,t){if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e)throw fs(e,cs);var i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map((function(e){var t=e[0],i=e[1];i instanceof ds==0&&(i=new ds(i));var r,n=Ps(t);return!0===i.value?n+=ks(i.params):(n+="=",Array.isArray(i.value)?n+="("+(r=i).value.map(Ds).join(" ")+")"+ks(r.params):n+=Ds(i)),n})).join(","+r)}(e,t)}(function(e,t){var i={};if(null==e||"object"!=typeof e)return i;var r=Object.keys(e).sort(),n=o({},Ms,null==t?void 0:t.formatters),s=null==t?void 0:t.filter;return r.forEach((function(r){if(!(null==s?void 0:s(r))){var a=e[r],o=n[r];o&&(a=o(a,t)),"v"===r&&1===a||"pr"==r&&1===a||function(e){return"number"==typeof e?_(e):null!=e&&""!==e&&!1!==e}(a)&&(function(e){return"ot"===e||"sf"===e||"st"===e}(r)&&"string"==typeof a&&(a=new gs(a)),i[r]=a)}})),i}(e,t),o({whitespace:!1},t)):""}var xs=/CMCD=[^&#]+/;var Fs=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){t.initialized&&(t.starved=!0),t.buffering=!0},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1},this.applyPlaylistData=function(e){try{t.apply(e,{ot:es,su:!t.initialized})}catch(e){t.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var i=e.frag,r=e.part,n=t.hls.levels[i.level],s=t.getObjectType(i),a={d:1e3*(r||i).duration,ot:s};s!==is&&s!==ts&&s!=rs||(a.br=n.bitrate/1e3,a.tb=t.getTopBandwidth(s)/1e3,a.bl=t.getBufferLength(s));var o=r?t.getNextPart(r):t.getNextFrag(i);null!=o&&o.url&&o.url!==i.url&&(a.nor=o.url),t.apply(e,a)}catch(e){t.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;var i=this.config=e.config,r=i.cmcd;null!=r&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHED,this.onMediaDetached,this),e.on(P.BUFFER_CREATED,this.onBufferCreated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHED,this.onMediaDetached,this),e.off(P.BUFFER_CREATED,this.onBufferCreated,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},t.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},t.onBufferCreated=function(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer},t.createData=function(){var e;return{v:1,sf:as,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},t.apply=function(e,t){void 0===t&&(t={}),o(t,this.createData());var i=t.ot===ns||t.ot===is||t.ot===rs;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var r=this.includeKeys;r&&(t=Object.keys(t).reduce((function(e,i){return r.includes(i)&&(e[i]=t[i]),e}),{}));var n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),function(e,t,i){o(e,function(e,t){void 0===t&&(t={});var i={};if(!e)return i;var r=Object.entries(e),n=Object.entries(us).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),s=r.reduce((function(e,t){var i,r,s=t[0],a=t[1],o=(null===(i=n.find((function(e){return e[1].includes(s)})))||void 0===i?void 0:i[0])||os;return null!==(r=e[o])&&void 0!==r||(e[o]={}),e[o][s]=a,e}),{});return Object.entries(s).reduce((function(e,i){var r=i[0],n=i[1];return e[r]=Os(n,t),e}),i)}(t,i))}(e.headers,t,n)):e.url=function(e,t,i){var r=function(e,t){if(void 0===t&&(t={}),!e)return"";var i=Os(e,t);return"CMCD="+encodeURIComponent(i)}(t,i);if(!r)return e;if(xs.test(e))return e.replace(xs,r);var n=e.includes("?")?"&":"?";return""+e+n+r}(e.url,t,n)},t.getNextFrag=function(e){var t,i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){var r=e.sn-i.startSN;return i.fragments[r+1]}},t.getNextPart=function(e){var t,i,r=e.index,n=e.fragment,s=null==(t=this.hls.levels[n.level])||null==(i=t.details)?void 0:i.partList;if(s)for(var a=n.sn,o=s.length-1;o>=0;o--){var l=s[o];if(l.index===r&&l.fragment.sn===a)return s[o+1]}},t.getObjectType=function(e){var t=e.type;return"subtitle"===t?ss:"initSegment"===e.sn?ns:"audio"===t?ts:"main"===t?this.hls.audioTracks.length?is:rs:void 0},t.getTopBandwidth=function(e){var t,i=0,r=this.hls;if(e===ts)t=r.audioTracks;else{var n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;t=r.levels.slice(0,a)}for(var o,l=s(t);!(o=l()).done;){var h=o.value;h.bitrate>i&&(i=h.bitrate)}return i>0?i:NaN},t.getBufferLength=function(e){var t=this.media,i=e===ts?this.audioBuffer:this.videoBuffer;return i&&t?1e3*Wt.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var r=e.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(e,i,r){t(e),this.loader.load(e,i,r)},n(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,i=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new i(e)}var r=e.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(e,i,r){t(e),this.loader.load(e,i,r)},n(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},e}(),Ns=function(e){function t(t){var i;return(i=e.call(this,"content-steering",t.logger)||this).hls=void 0,i.loader=null,i.uri=null,i.pathwayId=".",i._pathwayPriority=null,i.timeToLoad=300,i.reloadTimer=-1,i.updated=0,i.started=!1,i.enabled=!0,i.levels=null,i.audioTracks=null,i.subtitleTracks=null,i.penalizedPathways={},i.hls=t,i.registerListeners(),i}h(t,e);var i=t.prototype;return i.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)},i.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))},i.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},i.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},i.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},i.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},i.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},i.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},i.onManifestLoaded=function(e,t){var i=t.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())},i.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},i.onError=function(e,t){var i=t.errorAction;if(2===(null==i?void 0:i.action)&&1===i.flags){var r=this.levels,n=this._pathwayPriority,s=this.pathwayId;if(t.context){var a=t.context,o=a.groupId,l=a.pathwayId,h=a.type;o&&r?s=this.getPathwayForGroupId(o,h,s):l&&(s=l)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==s),i.resolved||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+s+" levels: "+(r?r.length:r)+" priorities: "+it(n)+" penalized: "+it(this.penalizedPathways))}},i.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var i=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+i+'"'),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t},i.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},i.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((function(e){r-i[e]>3e5&&delete i[e]}));for(var n=0;n<e.length;n++){var s=e[n];if(!(s in i)){if(s===this.pathwayId)return;var a=this.hls.nextLoadLevel,o=this.hls.levels[a];if((t=this.getLevelsForPathway(s)).length>0){this.log('Setting Pathway to "'+s+'"'),this.pathwayId=s,Yi(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}}}},i.getPathwayForGroupId=function(e,t,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),n=0;n<r.length;n++)if(t===w&&r[n].hasAudioGroup(e)||t===C&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i},i.clonePathways=function(e){var t=this,i=this.levels;if(i){var r={},n={};e.forEach((function(e){var s=e.ID,a=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!i.some((function(e){return e.pathwayId===s}))){var l=t.getLevelsForPathway(a).map((function(e){var t=new Jt(e.attrs);t["PATHWAY-ID"]=s;var i=t.AUDIO&&t.AUDIO+"_clone_"+s,a=t.SUBTITLES&&t.SUBTITLES+"_clone_"+s;i&&(r[t.AUDIO]=i,t.AUDIO=i),a&&(n[t.SUBTITLES]=a,t.SUBTITLES=a);var l=Us(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new et({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var u=1;u<e.audioGroups.length;u++)h.addGroupId("audio",e.audioGroups[u]+"_clone_"+s);if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)h.addGroupId("text",e.subtitleGroups[d]+"_clone_"+s);return h}));i.push.apply(i,l),Bs(t.audioTracks,r,o,s),Bs(t.subtitleTracks,n,o,s)}}))}},i.loadSteeringManifest=function(e){var t,i=this,r=this.hls.config,n=r.loader;this.loader&&this.loader.destroy(),this.loader=new n(r);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+e)}if("data:"!==t.protocol){var s=0|(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+s)}var a={responseType:"json",url:t.href},o=r.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},u={onSuccess:function(e,r,n,s){i.log('Loaded steering manifest: "'+t+'"');var a=e.data;if(1===(null==a?void 0:a.VERSION)){i.updated=performance.now(),i.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,t).href}catch(e){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}i.scheduleRefresh(i.uri||n.url),l&&i.clonePathways(l);var u={steeringManifest:a,url:t.toString()};i.hls.trigger(P.STEERING_MANIFEST_LOADED,u),h&&i.updatePathwayPriority(h)}else i.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(e,t,r,n){if(i.log("Error loading steering manifest: "+e.code+" "+e.text+" ("+t.url+")"),i.stopLoad(),410===e.code)return i.enabled=!1,void i.log("Steering manifest "+t.url+" no longer available");var s=1e3*i.timeToLoad;if(429!==e.code)i.scheduleRefresh(i.uri||t.url,s);else{var a=i.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(s=1e3*parseFloat(o))}i.log("Steering manifest "+t.url+" rate limited")}},onTimeout:function(e,t,r){i.log("Timeout loading steering manifest ("+t.url+")"),i.scheduleRefresh(i.uri||t.url)}};this.log("Requesting steering manifest: "+t),this.loader.load(a,h,u)},i.scheduleRefresh=function(e,t){var i=this;void 0===t&&(t=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var t,r=null==(t=i.hls)?void 0:t.media;!r||r.ended?i.scheduleRefresh(e,1e3*i.timeToLoad):i.loadSteeringManifest(e)}),t)},n(t,[{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}}])}(B);function Bs(e,t,i,r){e&&Object.keys(t).forEach((function(n){var s=e.filter((function(e){return e.groupId===n})).map((function(e){var s=o({},e);return s.details=void 0,s.attrs=new Jt(s.attrs),s.url=s.attrs.URI=Us(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),s.groupId=s.attrs["GROUP-ID"]=t[n],s.attrs["PATHWAY-ID"]=r,s}));e.push.apply(e,s)}))}function Us(e,t,i,r){var n,s=r.HOST,a=r.PARAMS,o=r[i];t&&(n=null==o?void 0:o[t])&&(e=n);var l=new self.URL(e);return s&&!n&&(l.host=s),a&&Object.keys(a).sort().forEach((function(e){e&&l.searchParams.set(e,a[e])})),l.href}var Gs=function(e){function t(i){var r;return(r=e.call(this,"eme",i.logger)||this).hls=void 0,r.config=void 0,r.media=null,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,n='"'+e.type+'" event: init data type: "'+t+'"';if(r.debug(n),null!==i){if(!r.keyFormatPromise){var s=Object.keys(r.keySystemAccessPromises);s.length||(s=pi(r.config));var a=s.map(gi).filter((function(e){return!!e}));r.keyFormatPromise=r.getKeyFormatPromise(a)}r.keyFormatPromise.then((function(s){var a,o,l=ci(s);if("sinf"===t){if(l!==oi.FAIRPLAY)return void r.warn('Ignoring unexpected "'+e.type+'" event with init data type: "'+t+'" for selected key-system '+l);var h=le(new Uint8Array(i));try{var u=Le(ni(JSON.parse(h).sinf));if(!u)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(u.subarray(8,24)),o=oi.FAIRPLAY}catch(e){return void r.warn(n+" Failed to parse sinf: "+e)}}else{if(l!==oi.WIDEVINE&&l!==oi.PLAYREADY)return void r.warn('Ignoring unexpected "'+e.type+'" event with init data type: "'+t+'" for selected key-system '+l);var d=function(e){var t=[];if(e instanceof ArrayBuffer)for(var i=e.byteLength,r=0;r+32<i;){var n=De(new DataView(e,r));t.push(n),r+=n.size}return t}(i),c=d.filter((function(e){return!!e.systemId&&fi(e.systemId)===l}));c.length>1&&r.warn(n+" Using first of "+c.length+" pssh found for selected key-system "+l);var f=c[0];if(!f)return void(0===d.length||d.some((function(e){return!e.systemId}))?r.warn(n+" contains incomplete or invalid pssh data"):r.log("ignoring "+n+" for "+d.map((function(e){return fi(e.systemId)})).join(",")+" pssh data in favor of playlist keys"));if(o=fi(f.systemId),0===f.version&&f.data)if(o===oi.WIDEVINE){var g=f.data.length-22;a=new Uint8Array(f.data.subarray(g,g+16))}else o===oi.PLAYREADY&&(a=yi(f.data))}if(o&&a){for(var p,v=z(a),m=r,y=m.keyIdToKeySessionPromise,E=m.mediaKeySessions,S=y[v],T=function(){var e=E[L],n=e.decryptdata;if(!n.keyId)return 0;var s=z(n.keyId);return v===s||-1!==n.uri.replace(/-/g,"").indexOf(v)?(S=y[s],n.pssh||(delete y[s],n.pssh=new Uint8Array(i),n.keyId=a,(S=y[v]=S.then((function(){return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-key-match")}))).catch((function(e){return r.handleError(e)}))),1):void 0},L=0;L<E.length&&(0===(p=T())||1!==p);L++);if(!S){if(o!==l)return void r.log('Ignoring "'+e.type+'" event with '+o+" init data for selected key-system "+l);S=y[v]=r.getKeySystemSelectionPromise([o]).then((function(e){var n,s=e.keySystem,o=e.mediaKeys;r.throwIfDestroyed();var l=new Si("ISO-23001-7",v,null!=(n=gi(s))?n:"");return l.pssh=new Uint8Array(i),l.keyId=a,r.attemptSetMediaKeys(s,o).then((function(){r.throwIfDestroyed();var e=r.createMediaKeySessionContext({decryptdata:l,keySystem:s,mediaKeys:o});return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-no-match")}))})),S.catch((function(e){return r.handleError(e)}))}}}))}},r.onWaitingForKey=function(e){r.log('"'+e.type+'" event')},r.hls=i,r.config=i.config,r.registerListeners(),r}h(t,e);var i=t.prototype;return i.destroy=function(){var e=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(e);var t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null},i.registerListeners=function(){this.hls.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(P.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(P.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(P.MANIFEST_LOADED,this.onManifestLoaded,this)},i.unregisterListeners=function(){this.hls.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(P.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(P.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(P.MANIFEST_LOADED,this.onManifestLoaded,this)},i.getLicenseServerUrl=function(e){var t=this.config,i=t.drmSystems,r=t.widevineLicenseUrl,n=i[e];return n?n.licenseUrl:e===oi.WIDEVINE&&r?r:void 0},i.getLicenseServerUrlOrThrow=function(e){var t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error('no license server URL configured for key-system "'+e+'"');return t},i.getServerCertificateUrl=function(e){var t=this.config.drmSystems[e];if(t)return t.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+e+'"]')},i.attemptKeySystemAccess=function(e){var t=this,i=this.hls.levels,r=function(e,t,i){return!!e&&i.indexOf(e)===t},n=i.map((function(e){return e.audioCodec})).filter(r),s=i.map((function(e){return e.videoCodec})).filter(r);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((function(i,r){var a=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,s).then((function(e){return i({keySystem:o,mediaKeys:e})})).catch((function(t){e.length?a(e):r(t instanceof Hs?t:new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};a(e)}))},i.requestMediaKeySystemAccess=function(e,t){var i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function "+i;return null===mi&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(r))}return i(e,t)},i.getMediaKeysPromise=function(e,t,i){var r=this,n=function(e,t,i,r){var n;switch(e){case oi.FAIRPLAY:n=["cenc","sinf"];break;case oi.WIDEVINE:case oi.PLAYREADY:n=["cenc"];break;case oi.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+e)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((function(e){return{contentType:"audio/mp4; codecs="+e,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}})),videoCapabilities:i.map((function(e){return{contentType:"video/mp4; codecs="+e,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}}))}]}(n,t,i,r)}(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e],a=null==s?void 0:s.keySystemAccess;if(!a){this.log('Requesting encrypted media "'+e+'" key-system access with config: '+it(n)),a=this.requestMediaKeySystemAccess(e,n);var o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch((function(t){r.log('Failed to obtain access to key-system "'+e+'": '+t)})),a.then((function(t){r.log('Access for key-system "'+t.keySystem+'" obtained');var i=r.fetchServerCertificate(e);return r.log('Create media-keys for "'+e+'"'),o.mediaKeys=t.createMediaKeys().then((function(t){return r.log('Media-keys created for "'+e+'"'),i.then((function(i){return i?r.setMediaKeysServerCertificate(t,e,i):t}))})),o.mediaKeys.catch((function(t){r.error('Failed to create media-keys for "'+e+'"}: '+t)})),o.mediaKeys}))}return a.then((function(){return s.mediaKeys}))},i.createMediaKeySessionContext=function(e){var t=e.decryptdata,i=e.keySystem,r=e.mediaKeys;this.log('Creating key-system session "'+i+'" keyId: '+z(t.keyId||[]));var n=r.createSession(),s={decryptdata:t,keySystem:i,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s},i.renewKeySession=function(e){var t=e.decryptdata;if(t.pssh){var i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)},i.getKeyIdString=function(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return z(e.keyId)},i.updateKeySession=function(e,t){var i,r=e.mediaKeysSession;return this.log('Updating key-session "'+r.sessionId+'" for keyID '+z((null==(i=e.decryptdata)?void 0:i.keyId)||[])+"\n } (data length: "+(t?t.byteLength:t)+")"),r.update(t)},i.selectKeySystemFormat=function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: "+e.sn+" "+e.type+": "+e.level+") key formats "+t.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise},i.getKeyFormatPromise=function(e){var t=this;return new Promise((function(i,r){var n=pi(t.config),s=e.map(ci).filter((function(e){return!!e&&-1!==n.indexOf(e)}));return t.getKeySystemSelectionPromise(s).then((function(e){var t=e.keySystem,n=gi(t);n?i(n):r(new Error('Unable to find format for key-system "'+t+'"'))})).catch(r)}))},i.loadKey=function(e){var t=this,i=e.keyInfo.decryptdata,r=this.getKeyIdString(i),n="(keyId: "+r+' format: "'+i.keyFormat+'" method: '+i.method+" uri: "+i.uri+")";this.log("Starting session for key "+n);var s=this.keyIdToKeySessionPromise[r];return s||(s=this.getKeySystemForKeyPromise(i).then((function(r){var s=r.keySystem,a=r.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: "+e.frag.sn+" "+e.frag.type+": "+e.frag.level+" using key "+n),t.attemptSetMediaKeys(s,a).then((function(){return t.throwIfDestroyed(),t.createMediaKeySessionContext({keySystem:s,mediaKeys:a,decryptdata:i})}))})),(this.keyIdToKeySessionPromise[r]=s.then((function(e){var r=i.pssh?i.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",r,"playlist-key")}))).catch((function(e){return t.handleError(e)}))),s},i.throwIfDestroyed=function(e){if(!this.hls)throw new Error("invalid state")},i.handleError=function(e){this.hls&&(this.error(e.message),e instanceof Hs?this.hls.trigger(P.ERROR,e.data):this.hls.trigger(P.ERROR,{type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))},i.getKeySystemForKeyPromise=function(e){var t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){var r=ci(e.keyFormat),n=r?[r]:pi(this.config);return this.attemptKeySystemAccess(n)}return i},i.getKeySystemSelectionPromise=function(e){if(e.length||(e=pi(this.config)),0===e.length)throw new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+it({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(e)},i.attemptSetMediaKeys=function(e,t){var i=this,r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+e+'"');var n=Promise.all(r).then((function(){if(!i.media)throw new Error("Attempted to set mediaKeys without media element attached");return i.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(n),n.then((function(){i.log('Media-keys set for "'+e+'"'),r.push(n),i.setMediaKeysQueue=i.setMediaKeysQueue.filter((function(e){return-1===r.indexOf(e)}))}))},i.generateRequestWithPreferredKeySession=function(e,t,i,r){var n,s,a=this,o=null==(n=this.config.drmSystems)||null==(s=n[e.keySystem])?void 0:s.generateRequest;if(o)try{var l=o.call(this.hls,t,i,e);if(!l)throw new Error("Invalid response from configured generateRequest filter");t=l.initDataType,i=l.initData?l.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){var h;if(this.warn(e.message),null!=(h=this.hls)&&h.config.debug)throw e}if(null===i)return this.log('Skipping key-session request for "'+r+'" (no initData)'),Promise.resolve(e);var u=this.getKeyIdString(e.decryptdata);this.log('Generating key-session request for "'+r+'": '+u+" (init data type: "+t+" length: "+(i?i.byteLength:null)+")");var d=new S,c=e._onmessage=function(t){var i=e.mediaKeysSession;if(i){var r=t.messageType,n=t.message;a.log('"'+r+'" message event for session "'+i.sessionId+'" message size: '+n.byteLength),"license-request"===r||"license-renewal"===r?a.renewLicense(e,n).catch((function(e){d.eventNames().length?d.emit("error",e):a.handleError(e)})):"license-release"===r?e.keySystem===oi.FAIRPLAY&&(a.updateKeySession(e,si("acknowledged")),a.removeSession(e)):a.warn('unhandled media key message type "'+r+'"')}else d.emit("error",new Error("invalid state"))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){a.onKeyStatusChange(e);var i=e.keyStatus;d.emit("keyStatus",i),"expired"===i&&(a.warn(e.keySystem+" expired for key "+u),a.renewKeySession(e))}else d.emit("error",new Error("invalid state"))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",f);var g=new Promise((function(e,t){d.on("error",t),d.on("keyStatus",(function(i){i.startsWith("usable")?e():"output-restricted"===i?t(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},'key status changed to "'+i+'"')):"expired"===i?t(new Error("key expired while generating request")):a.warn('unhandled key status change "'+i+'"')}))}));return e.mediaKeysSession.generateRequest(t,i).then((function(){var t;a.log('Request generated for key-session "'+(null==(t=e.mediaKeysSession)?void 0:t.sessionId)+'" keyId: '+u)})).catch((function(e){throw new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},"Error generating key-session request: "+e)})).then((function(){return g})).catch((function(t){throw d.removeAllListeners(),a.removeSession(e),t})).then((function(){return d.removeAllListeners(),e}))},i.onKeyStatusChange=function(e){var t=this;e.mediaKeysSession.keyStatuses.forEach((function(i,r){if("string"==typeof r&&"object"==typeof i){var n=r;r=i,i=n}t.log('key status change "'+i+'" for keyStatuses keyId: '+z("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))+" session keyId: "+z(new Uint8Array(e.decryptdata.keyId||[]))+" uri: "+e.decryptdata.uri),e.keyStatus=i}))},i.fetchServerCertificate=function(e){var t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log('Fetching server certificate for "'+e+'"'),new Promise((function(n,s){var a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(e,t,i,r){n(e.data)},onError:function(t,i,n,o){s(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:c({url:a.url,data:void 0},t)},'"'+e+'" certificate request failed ('+r+"). Status: "+t.code+" ("+t.text+")"))},onTimeout:function(t,i,n){s(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:a.url,data:void 0}},'"'+e+'" certificate request timed out ('+r+")"))},onAbort:function(e,t,i){s(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()},i.setMediaKeysServerCertificate=function(e,t,i){var r=this;return new Promise((function(n,s){e.setServerCertificate(i).then((function(s){r.log("setServerCertificate "+(s?"success":"not supported by CDM")+" ("+(null==i?void 0:i.byteLength)+') on "'+t+'"'),n(e)})).catch((function(e){s(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))},i.renewLicense=function(e,t){var i=this;return this.requestLicense(e,new Uint8Array(t)).then((function(t){return i.updateKeySession(e,new Uint8Array(t)).catch((function(e){throw new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))}))},i.unpackPlayReadyKeyMessage=function(e,t){var i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var r=(new DOMParser).parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0)for(var s,a=0,o=n.length;a<o;a++){var l,h,u=null==(l=(s=n[a]).querySelector("name"))?void 0:l.textContent,d=null==(h=s.querySelector("value"))?void 0:h.textContent;u&&d&&e.setRequestHeader(u,d)}var c=r.querySelector("Challenge"),f=null==c?void 0:c.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return si(atob(f))},i.setupLicenseXHR=function(e,t,i,r){var n=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then((function(){if(!i.decryptdata)throw new Error("Key removed");return s.call(n.hls,e,t,i,r)})).catch((function(a){if(!i.decryptdata)throw a;return e.open("POST",t,!0),s.call(n.hls,e,t,i,r)})).then((function(i){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))},i.requestLicense=function(e,t){var i=this,r=this.config.keyLoadPolicy.default;return new Promise((function(n,s){var a=i.getLicenseServerUrlOrThrow(e.keySystem);i.log("Sending license request to URL: "+a);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var h=i.config.licenseResponseCallback;if(h)try{l=h.call(i.hls,o,a,e)}catch(e){i.error(e)}n(l)}else{var u=r.errorRetry,d=u?u.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>d||o.status>=400&&o.status<500)s(new Hs({type:I.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+a+"). Status: "+o.status+" ("+o.statusText+")"));else{var c=d-i._requestLicenseFailureCount+1;i.warn("Retrying license request, "+c+" attempts left"),i.requestLicense(e,t).then(n,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,i.setupLicenseXHR(o,a,e,t).then((function(t){var r=t.xhr,n=t.licenseChallenge;e.keySystem==oi.PLAYREADY&&(n=i.unpackPlayReadyKeyMessage(r,n)),r.send(n)}))}))},i.onMediaAttached=function(e,t){if(this.config.emeEnabled){var i=t.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}},i.onMediaDetached=function(){var e=this.media;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)},i._clear=function(e){var i,r=this,n=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Si.clearKeyUriToKeyIdMap();var s=n.length;t.CDMCleanupPromise=Promise.all(n.map((function(e){return r.removeSession(e)})).concat(null==e||null==(i=e.setMediaKeys(null))?void 0:i.catch((function(e){var t;r.log("Could not clear media keys: "+e),null==(t=r.hls)||t.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+e)})})))).then((function(){s&&(r.log("finished closing key sessions and clearing media keys"),n.length=0)})).catch((function(e){var t;r.log("Could not close sessions and clear media keys: "+e),null==(t=r.hls)||t.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+e)})}))},i.onManifestLoading=function(){this.keyFormatPromise=null},i.onManifestLoaded=function(e,t){var i=t.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+r.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(r)}},i.removeSession=function(e){var t=this,i=e.mediaKeysSession,r=e.licenseXhr;if(i){this.log("Remove licenses and keys and close session "+i.sessionId),e._onmessage&&(i.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);var s=function(e){var t;return"persistent-license"===e.sessionType||!(null==(t=e.sessionTypes)||!t.some((function(e){return"persistent-license"===e})))}(this.config.drmSystemOptions)?new Promise((function(e,t){self.setTimeout((function(){return t(new Error("MediaKeySession.remove() timeout"))}),8e3),i.remove().then(e)})):Promise.resolve();return s.catch((function(e){var i;t.log("Could not remove session: "+e),null==(i=t.hls)||i.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+e)})})).then((function(){return i.close()})).catch((function(e){var i;t.log("Could not close session: "+e),null==(i=t.hls)||i.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+e)})}))}},t}(B);Gs.CDMCleanupPromise=void 0;var Hs=function(e){function t(t,i){var r;return(r=e.call(this,i)||this).data=void 0,t.error||(t.error=new Error(i)),r.data=t,t.err=t.error,r}return h(t,e),t}(p(Error)),Vs=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 i=this.hls.config;if(i.capLevelOnFPSDrop){var r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,i){var r=performance.now();if(t){if(this.lastTime){var n=r-this.lastTime,s=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*s/n,l=this.hls;if(l.trigger(P.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:i}),o>0&&s>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=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}();function Ks(e){for(var t=5381,i=e.length;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}var Ws=.025,$s=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function qs(e,t,i){return e.identifier+"-"+(i+1)+"-"+Ks(t)}var js=function(){function e(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}var t=e.prototype;return t.setDateRange=function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)},t.reset=function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)},t.isAssetPastPlayoutLimit=function(e){if(e>=this.assetList.length)return!0;var t=this.playoutLimit;return!(e<=0||isNaN(t))&&this.assetList[e].startOffset>t},t.findAssetIndex=function(e){return this.assetList.indexOf(e)},t.toString=function(){return'["'+(e=this).identifier+'" '+(e.cue.pre?"<pre>":e.cue.post?"<post>":"")+e.timelineStart.toFixed(2)+"-"+e.resumeTime.toFixed(2)+"]";var e},n(e,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return Ys(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-Ys(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=_(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return Ys(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Ws))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?$s.Range:$s.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}}])}();function Ys(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Ws)?t.start:t.start+t.duration}function zs(e,t,i){var r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function Xs(e){var t=e.timelineStart,i=e.duration||0;return'["'+e.identifier+'" '+t.toFixed(2)+"-"+(t+i).toFixed(2)+"]"}var Qs=function(){function e(e,t,i,r){var n=this;this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){var e=n.interstitial.playoutLimit,t=n.currentTime;n.startOffset+t>=e&&n.hls.trigger(P.PLAYOUT_LIMIT_REACHED,{})};var s=this.hls=new e(t);this.interstitial=i,this.assetItem=r;var a=r.uri;try{a=zs(a,s.sessionId).href}catch(e){}s.loadSource(a);var o=function(){n.hasDetails=!0};s.once(P.LEVEL_LOADED,o),s.once(P.AUDIO_TRACK_LOADED,o),s.once(P.SUBTITLE_TRACK_LOADED,o),s.on(P.MEDIA_ATTACHING,(function(e,t){var i=t.media;n.removeMediaListeners(),n.mediaAttached=i,n.interstitial.playoutLimit&&i.addEventListener("timeupdate",n.checkPlayout)}))}var t=e.prototype;return t.bufferedInPlaceToEnd=function(e){var t;if(!this.interstitial.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e||!this._bufferedEosTime)return!1;var i=this.timelineOffset,r=Wt.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=this._bufferedEosTime-.02},t.getAssetTime=function(e){var t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)},t.removeMediaListeners=function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))},t.bufferSnapShot=function(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},t.destroy=function(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null},t.attachMedia=function(e){this.hls.attachMedia(e)},t.detachMedia=function(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()},t.resumeBuffering=function(){this.hls.resumeBuffering()},t.pauseBuffering=function(){this.hls.pauseBuffering()},t.transferMedia=function(){return this.bufferSnapShot(),this.hls.transferMedia()},t.on=function(e,t,i){this.hls.on(e,t)},t.once=function(e,t,i){this.hls.once(e,t)},t.off=function(e,t,i){this.hls.off(e,t)},t.toString=function(){var e,t;return"HlsAssetPlayer: "+Xs(this.assetItem)+" "+(null==(e=this.hls)?void 0:e.sessionId)+" "+(null!=(t=this.interstitial)&&t.appendInPlace?"append-in-place":"")},n(e,[{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=Wt.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){return this.assetItem.duration||0}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var i=e-t;if(Math.abs(i)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}}])}(),Js=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials-sched",i)||this).onScheduleUpdate=void 0,r.eventMap={},r.events=null,r.items=null,r.durations={primary:0,playout:0,integrated:0},r.onScheduleUpdate=t,r}h(t,e);var i=t.prototype;return i.destroy=function(){this.reset(),this.onScheduleUpdate=null},i.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(e){return e.reset()})),this.events=this.items=null},i.resetErrorsInRange=function(e,t){return this.events?this.events.reduce((function(i,r){return e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i}),0):0},i.getEvent=function(e){return e&&this.eventMap[e]||null},i.hasEvent=function(e){return e in this.eventMap},i.findItemIndex=function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);var r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(n=r[i])&&n.event;){var n;i--}return i},i.findItemIndexAtTime=function(e,t){var i=this.items;if(i)for(var r=0;r<i.length;r++){var n=i[r];if(t&&"primary"!==t&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1},i.findJumpRestrictedIndex=function(e,t){var i=this.items;if(i)for(var r=e;r<=t&&i[r];r++){var n=i[r].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return r}return-1},i.findEventIndex=function(e){var t=this.items;if(t)for(var i=t.length;i--;){var r;if((null==(r=t[i].event)?void 0:r.identifier)===e)return i}return-1},i.findAssetIndex=function(e,t){var i=e.assetList,r=i.length;if(r>1)for(var n=0;n<r;n++){var s=i[n];if(!s.error){var a=s.timelineStart;if(t===a||t>a&&t<a+(s.duration||0))return n}}return 0},i.parseInterstitialDateRanges=function(e,t){var i=this,r=e.main.details,n=r.dateRanges,s=this.events,a=this.parseDateRanges(n,{url:r.url},t),o=Object.keys(n),l=s?s.filter((function(e){return!o.includes(e.identifier)})):[];a.length&&a.sort((function(e,t){var i=e.cue.pre,r=e.cue.post,n=t.cue.pre,s=t.cue.post;if(i&&!n)return-1;if(n&&!i)return 1;if(r&&!s)return 1;if(s&&!r)return-1;if(!(i||n||r||s)){var a=e.startTime,o=t.startTime;if(a!==o)return a-o}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=a,l.forEach((function(e){i.removeEvent(e)})),this.updateSchedule(e,l)},i.updateSchedule=function(e,t){void 0===t&&(t=[]);var i=this.events||[];if(i.length||t.length||this.length<2){var r=this.items,n=this.parseSchedule(i,e);(t.length||(null==r?void 0:r.length)!==n.length||n.some((function(e,t){return Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005})))&&(this.items=n,this.onScheduleUpdate(t,r))}},i.parseDateRanges=function(e,t,i){for(var r=[],n=Object.keys(e),s=0;s<n.length;s++){var a=n[s],o=e[a];if(o.isInterstitial){var l=this.eventMap[a];l?l.setDateRange(o):(l=new js(o,t),this.eventMap[a]=l,!1===i&&(l.appendInPlace=i)),r.push(l)}}return r},i.parseSchedule=function(e,t){var i=[],r=t.main.details,n=r.live?1/0:r.edge,s=0;if((e=e.filter((function(e){return!(e.error||e.cue.once&&e.hasPlayed)}))).length){this.resolveOffsets(e,t);var a=0,o=0;if(e.forEach((function(t,r){var l=t.cue.pre,h=t.cue.post,u=e[r-1]||null,d=t.appendInPlace,c=h?n:t.startOffset,f=t.duration,g=t.timelineOccupancy===$s.Range?f:0,p=t.resumptionOffset,v=(null==u?void 0:u.startTime)===c,m=c+t.cumulativeDuration,y=d?m+f:c+p;if(l||!h&&c<=0){var E=o;o+=g,t.timelineStart=m;var S=s;s+=f,i.push({event:t,start:m,end:y,playout:{start:S,end:s},integrated:{start:E,end:o}})}else{if(!(c<=n))return;if(!v){var T=c-a;if(T>.033){var L=a,_=o;o+=T;var b=s;s+=T;var A={previousEvent:e[r-1]||null,nextEvent:t,start:L,end:L+T,playout:{start:b,end:s},integrated:{start:_,end:o}};i.push(A)}else T>0&&u&&(u.cumulativeDuration+=T,i[i.length-1].end=c)}h&&(y=m),t.timelineStart=m;var I=o;o+=g;var R=s;s+=f,i.push({event:t,start:m,end:y,playout:{start:R,end:s},integrated:{start:I,end:o}})}var P=t.resumeTime;a=h||P>n?n:P})),a<n){var l,h=a,u=o,d=n-a;o+=d;var c=s;s+=d,i.push({previousEvent:(null==(l=i[i.length-1])?void 0:l.event)||null,nextEvent:null,start:a,end:h+d,playout:{start:c,end:s},integrated:{start:u,end:o}})}this.setDurations(n,s,o)}else i.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return i},i.setDurations=function(e,t,i){this.durations={primary:e,playout:t,integrated:i}},i.resolveOffsets=function(e,t){var i=this,r=t.main.details,n=r.live?1/0:r.edge,s=0,a=-1;e.forEach((function(o,l){var h=o.cue.pre,u=o.cue.post,d=h?0:u?n:o.startTime;i.updateAssetDurations(o),a===d?o.cumulativeDuration=s:(s=0,a=d),!u&&o.snapOptions.in&&(o.resumeAnchor=ft(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(i.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&i.warn("Could not change append strategy for abutting event "+o));var c=_(o.resumeOffset)?o.resumeOffset:o.duration;s+=c}))},i.primaryCanResumeInPlaceAt=function(e,t){var i=this,r=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(r-n)>Ws?(this.log('"'+e.identifier+'" resumption '+r+" not aligned with estimated timeline end "+n),!1):t?!Object.keys(t).some((function(n){var s=t[n].details,a=s.edge;if(r>=a)return i.log('"'+e.identifier+'" resumption '+r+" past "+n+" playlist end "+a),!1;var o=ft(null,s.fragments,r);if(!o)return i.log('"'+e.identifier+'" resumption '+r+" does not align with any fragments in "+n+" playlist ("+s.fragStart+"-"+s.fragmentEnd+")"),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-r)<Ws+l||Math.abs(o.end-r)<Ws+l||(i.log('"'+e.identifier+'" resumption '+r+" not aligned with "+n+" fragment bounds ("+o.start+"-"+o.end+" sn: "+o.sn+" cc: "+o.cc+")"),0))})):(this.log('"'+e.identifier+'" resumption '+r+" can not be aligned with media (none selected)"),!1)},i.updateAssetDurations=function(e){if(e.assetListLoaded){var t=e.timelineStart,i=0,r=!1,n=!1;e.assetList.forEach((function(e,s){var a=t+i;e.startOffset=i,e.timelineStart=a,r||(r=null===e.duration),n||(n=!!e.error);var o=e.error?0:e.duration||0;i+=o})),e.duration=r&&!n?Math.max(i,e.duration):i}},i.removeEvent=function(e){e.reset(),delete this.eventMap[e.identifier]},n(t,[{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"assetIdAtEnd",get:function(){var e,t,i=null==(e=this.items)||null==(t=e[this.length-1])?void 0:t.event;if(i){var r=i.assetList,n=r[r.length-1];if(n)return n.identifier}return null}}])}(B);function Zs(e){return"["+(e.event?'"'+e.event.identifier+'"':"primary")+": "+e.start.toFixed(2)+"-"+e.end.toFixed(2)+"]"}var ea=function(){function e(e){this.hls=void 0,this.hls=e}var t=e.prototype;return t.destroy=function(){this.hls=null},t.loadAssetList=function(e,t){var i,r=this,n=e.assetListUrl;try{i=zs(n,this.hls.sessionId,e.baseUrl)}catch(t){var s=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,t,n);return void this.hls.trigger(P.ERROR,s)}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);var a=this.hls.config,o=new(0,a.loader)(a),l={responseType:"json",url:i.href},h=a.interstitialAssetListLoadPolicy.default,u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,i,n,s){var a=t.data,o=null==a?void 0:a.ASSETS;if(Array.isArray(o))e.assetListResponse=a,r.hls.trigger(P.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:s});else{var l=r.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,i,s);r.hls.trigger(P.ERROR,l)}},onError:function(t,i,n,s){var a=r.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status "+t.code+" "+t.text+" ("+i.url+")"),i.url,s,n);r.hls.trigger(P.ERROR,a)},onTimeout:function(t,i,n){var s=r.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST ("+i.url+")"),i.url,t,n);r.hls.trigger(P.ERROR,s)}};return o.load(l,u,d),this.hls.trigger(P.ASSET_LIST_LOADING,{event:e}),o},t.assignAssetListError=function(e,t,i,r,n,s){return e.error=i,{type:I.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:s,stats:n}},e}();function ta(e,t,i){ia(e,t,i),e.addEventListener(t,i)}function ia(e,t,i){e.removeEventListener(t,i)}function ra(e){null==e||e.play().catch((function(){}))}var na=function(e){function t(t,i){var r;return(r=e.call(this,"interstitials",t.logger)||this).HlsPlayerClass=void 0,r.hls=void 0,r.assetListLoader=void 0,r.mediaSelection=null,r.altSelection=null,r.media=null,r.detachedData=null,r.requiredTracks=null,r.manager=null,r.playerQueue=[],r.bufferedPos=-1,r.timelinePos=-1,r.schedule=void 0,r.playingItem=null,r.bufferingItem=null,r.waitingItem=null,r.endedItem=null,r.playingAsset=null,r.endedAsset=null,r.bufferingAsset=null,r.shouldPlay=!1,r.onPlay=function(){r.shouldPlay=!0},r.onPause=function(){r.shouldPlay=!1},r.onSeeking=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled){var t=e-r.timelinePos;if(!(Math.abs(t)<1/7056e5)){var i=t<=-.01;r.timelinePos=e,r.bufferedPos=e;var n=r.playingItem;if(n)if(i&&r.schedule.resetErrorsInRange(e,e-t)&&r.updateSchedule(),r.checkBuffer(),i&&e<n.start||e>=n.end){var s,a=r.schedule.findItemIndexAtTime(r.timelinePos);if(!r.isInterstitial(n)&&null!=(s=r.media)&&s.paused&&(r.shouldPlay=!1),!i){var o=r.findItemIndex(n);if(a>o){var l=r.schedule.findJumpRestrictedIndex(o+1,a);if(l>o)return void r.setSchedulePosition(l)}}r.setSchedulePosition(a)}else{var h=r.playingAsset;if(h){var u=h.timelineStart,d=h.duration||0;(i&&e<u||e>=u+d)&&r.setScheduleToAssetAtTime(e,h)}else if(r.playingLastItem&&r.isInterstitial(n)){var c=n.event.assetList[0];c&&(r.endedItem=r.playingItem,r.playingItem=null,r.setScheduleToAssetAtTime(e,c))}}else r.checkBuffer()}}},r.onTimeupdate=function(){var e=r.currentTime;if(void 0!==e&&!r.playbackDisabled&&e>r.timelinePos){r.timelinePos=e,e>r.bufferedPos&&r.checkBuffer();var t=r.playingItem;if(t&&!r.playingLastItem){if(e>=t.end){r.timelinePos=t.end;var i=r.findItemIndex(t);r.setSchedulePosition(i+1)}var n=r.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&r.setScheduleToAssetAtTime(e,n)}}},r.onScheduleUpdate=function(e,t){var i=r.schedule,n=r.playingItem,s=i.events||[],a=i.items||[],o=i.durations,l=e.map((function(e){return e.identifier})),h=!(!s.length&&!l.length);if(h&&r.log("INTERSTITIALS_UPDATED ("+s.length+"): "+s+"\nSchedule: "+a.map((function(e){return Zs(e)}))),l.length&&r.log("Removed events "+l),r.playerQueue.forEach((function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(n){Math.abs(i)>Ws&&r.warn(n+' ("'+e.assetId+'" '+e.timelineOffset+"->"+t+")")}}})),n){var u=r.updateItem(n,r.timelinePos);r.itemsMatch(n,u)&&(r.playingItem=u,r.waitingItem=r.endedItem=null)}else r.waitingItem=r.updateItem(r.waitingItem),r.endedItem=r.updateItem(r.endedItem);var d=r.bufferingItem;if(d){var c=r.updateItem(d,r.bufferedPos);r.itemsMatch(d,c)?r.bufferingItem=c:d.event&&(r.bufferingItem=r.playingItem,r.clearInterstitial(d.event,null))}if(e.forEach((function(e){e.assetList.forEach((function(e){r.clearAssetPlayer(e.identifier,null)}))})),h||t){if(r.hls.trigger(P.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:a.slice(0),durations:o,removedIds:l}),r.isInterstitial(n)&&l.includes(n.event.identifier))return r.warn('Interstitial "'+n.event.identifier+'" removed while playing'),void r.primaryFallback(n.event);r.checkBuffer()}},r.hls=t,r.HlsPlayerClass=i,r.assetListLoader=new ea(t),r.schedule=new Js(r.onScheduleUpdate,t.logger),r.registerListeners(),r}h(t,e);var i=t.prototype;return i.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.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(P.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(P.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(P.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(P.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this),e.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(P.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(P.MEDIA_ENDED,this.onMediaEnded,this),e.on(P.ERROR,this.onError,this),e.on(P.DESTROYING,this.onDestroying,this)},i.unregisterListeners=function(){var e=this.hls;e&&(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.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(P.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(P.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(P.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(P.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this),e.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(P.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(P.MEDIA_ENDED,this.onMediaEnded,this),e.off(P.ERROR,this.onError,this),e.off(P.DESTROYING,this.onDestroying,this))},i.startLoad=function(){this.resumeBuffering()},i.stopLoad=function(){this.pauseBuffering()},i.resumeBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()},i.pauseBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()},i.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},i.onDestroying=function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)},i.removeMediaListeners=function(e){ia(e,"play",this.onPlay),ia(e,"pause",this.onPause),ia(e,"seeking",this.onSeeking),ia(e,"timeupdate",this.onTimeupdate)},i.onMediaAttaching=function(e,t){var i=this.media=t.media;ta(i,"seeking",this.onSeeking),ta(i,"timeupdate",this.onTimeupdate),ta(i,"play",this.onPlay),ta(i,"pause",this.onPause)},i.onMediaAttached=function(e,t){var i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();var n=this.findItemIndex(i);this.setSchedulePosition(n)}},i.clearScheduleState=function(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},i.onMediaDetaching=function(e,t){var i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}},i.isInterstitial=function(e){return!(null==e||!e.event)},i.retreiveMediaSource=function(e,t){var i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)},i.transferMediaFromPlayer=function(e,t){var i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});var n=e.transferMedia();this.log("transfer MediaSource from "+e+" "+it(n)),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))},i.transferMediaTo=function(e,t){var i,r,n=this;if(e.media!==t){var s,a=null,o=this.hls,l=e!==o,h=l&&e.interstitial.appendInPlace,u=null==(i=this.detachedData)?void 0:i.mediaSource;if(o.media)h&&(a=o.transferMedia(),this.detachedData=a),s="Primary";else if(u){var d=this.getBufferingPlayer();d?(a=d.transferMedia(),s=""+d):s="detached MediaSource"}else s="detached media";if(!a)if(u)a=this.detachedData,this.log("using detachedData: MediaSource "+it(a));else if(!this.detachedData||o.media===t){var c=this.playerQueue;c.length>1&&c.forEach((function(e){if(l&&e.interstitial.appendInPlace!==h){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets "+t)}})),this.hls.detachMedia(),this.detachedData={media:t}}var f=a&&"mediaSource"in a&&"closed"!==(null==(r=a.mediaSource)?void 0:r.readyState),g=f&&a?a:t;if(this.log((f?"transfering MediaSource":"attaching media")+" to "+(l?e:"Primary")+" from "+s),g===a){var p=l&&e.assetId===this.schedule.assetIdAtEnd;g.overrides={duration:this.schedule.duration,endOfStream:!l||p,cueRemoval:!l}}e.attachMedia(g)}},i.onInterstitialCueEnter=function(){this.onTimeupdate()},i.checkStart=function(){var e=this.schedule,t=e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){var n=this.hls.startPosition;if(this.timelinePos=n,t.length&&t[0].cue.pre){var s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(n>=0||!this.primaryLive){var a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){var l=e.findItemIndex(r);this.setSchedulePosition(l)}}},i.advanceAfterAssetEnded=function(e,t,i){var r=i+1;if(e.isAssetPastPlayoutLimit(r)||e.assetList[r].error){var n=this.schedule.items;if(n){var s=t+1;if(s>=n.length)return void this.setSchedulePosition(-1);var a=e.resumeTime;this.timelinePos<a&&(this.timelinePos=a,this.checkBuffer()),this.setSchedulePosition(s)}}else this.setSchedulePosition(t,r)},i.setScheduleToAssetAtTime=function(e,t){var i=this.schedule,r=t.parentIdentifier,n=i.getEvent(r);if(n){var s=i.findEventIndex(r),a=i.findAssetIndex(n,e);this.setSchedulePosition(s,a)}},i.setSchedulePosition=function(e,t){var i=this.schedule.items;if(i&&!this.playbackDisabled){this.log("setSchedulePosition "+e+", "+t);var r=e>=0?i[e]:null,n=this.playingItem,s=this.playingLastItem;if(this.isInterstitial(n)){var a,o=n.event,l=this.playingAsset,h=null==l?void 0:l.identifier,u=h?this.getAssetPlayer(h):null;if(u&&h&&(!this.eventItemsMatch(n,r)||void 0!==t&&h!==(null==(a=o.assetList)?void 0:a[t].identifier))){var d,c=o.findAssetIndex(l);this.log("INTERSTITIAL_ASSET_ENDED "+(c+1)+"/"+o.assetList.length+" "+Xs(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(P.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:c,event:o,schedule:i.slice(0),scheduleIndex:e,player:u}),this.retreiveMediaSource(h,r),!u.media||null!=(d=this.detachedData)&&d.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+Zs(n)),o.hasPlayed=!0,this.hls.trigger(P.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once)){this.updateSchedule();var f=this.schedule.items;if(r&&f){var g=this.schedule.findItemIndex(r);this.advanceSchedule(g,f,t,n,s)}return}}this.advanceSchedule(e,i,t,n,s)}},i.advanceSchedule=function(e,t,i,r,n){var s=this,a=e>=0?t[e]:null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach((function(t){var i=t.interstitial,r=s.schedule.findEventIndex(i.identifier);(r<e||r>e+1)&&s.clearInterstitial(i,a)})),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);var h=a.event;void 0===i&&(i=this.schedule.findAssetIndex(h,this.timelinePos));var u=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);var d=this.preloadAssets(h,i);if(this.eventItemsMatch(a,u||r)||(this.waitingItem=a,this.log("INTERSTITIAL_STARTED "+Zs(a)+" "+(h.appendInPlace?"append in place":"")),this.hls.trigger(P.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+h);if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!o)return void this.log("Waiting for attachMedia to start Interstitial "+h);this.waitingItem=this.endedItem=null,this.playingItem=a;var c=h.assetList[i];if(!c){var f=t[e+1],g=this.media;return f&&g&&!this.isInterstitial(f)&&g.currentTime<f.start&&(g.currentTime=this.timelinePos=f.start),void this.advanceAfterAssetEnded(h,e,i||0)}if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){var p=h.assetList.length;this.warn("asset "+(i+1)+"/"+p+" player destroyed "+h),d=this.createAssetPlayer(h,c,i)}if(!this.eventItemsMatch(a,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,i,t,e,o),this.shouldPlay&&ra(d.media)}else null!==a?(this.resumePrimary(a,e,r),this.shouldPlay&&ra(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))},i.resumePrimary=function(e,t,i){var r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming "+Zs(e)),null==(r=this.detachedData)||!r.mediaSource){var n=this.timelinePos;(n<e.start||n>=e.end)&&(n=this.getPrimaryResumption(e,t),this.timelinePos=n),this.attachPrimary(n,e)}if(i){var s=this.schedule.items;s&&(this.log("resumed "+Zs(e)),this.hls.trigger(P.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}},i.getPrimaryResumption=function(e,t){var i=e.start;if(this.primaryLive){var r=this.primaryDetails;if(0===t)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i},i.isAssetBuffered=function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:Wt.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)},i.attachPrimary=function(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var r=this.primaryMedia;if(r){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}},i.startLoadingPrimaryAt=function(e,t){var i,r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()},i.onManifestLoading=function(){this.stopLoad(),this.schedule.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(P.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(P.BUFFER_CODECS,this.onBufferCodecs,this)},i.onLevelUpdated=function(e,t){if(-1!==t.level){var i=this.hls.levels[t.level],r=c(c({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}},i.onAudioTrackUpdated=function(e,t){var i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(r){var n=c(c({},r),{},{audio:i});this.mediaSelection=n}else this.altSelection=c(c({},this.altSelection),{},{audio:i})},i.onSubtitleTrackUpdated=function(e,t){var i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(r){var n=c(c({},r),{},{subtitles:i});this.mediaSelection=n}else this.altSelection=c(c({},this.altSelection),{},{subtitles:i})},i.onAudioTrackSwitching=function(e,t){var i=st(t);this.playerQueue.forEach((function(e){return e.hls.setAudioOption(t)||e.hls.setAudioOption(i)}))},i.onSubtitleTrackSwitch=function(e,t){var i=st(t);this.playerQueue.forEach((function(e){return e.hls.setSubtitleOption(t)||-1!==t.id&&e.hls.setSubtitleOption(i)}))},i.onBufferCodecs=function(e,t){var i=t.tracks;i&&(this.requiredTracks=i)},i.onBufferAppended=function(e,t){this.checkBuffer()},i.onBufferFlushed=function(e,t){var i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){var r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}},i.onBufferedToEnd=function(e){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var i=0;i<t.length;i++){var r=t[i];if(r.cue.post){var n,s=this.schedule.findEventIndex(r.identifier),a=null==(n=this.schedule.items)?void 0:n[s];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}},i.onMediaEnded=function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1},i.updateItem=function(e,t){var i=this.schedule.items;return e&&i&&i[this.findItemIndex(e,t)]||null},i.itemsMatch=function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))},i.eventItemsMatch=function(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))},i.findItemIndex=function(e,t){return e?this.schedule.findItemIndex(e,t):-1},i.updateSchedule=function(){var e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])},i.checkBuffer=function(e){var t=this.schedule.items;if(t){var i=Wt.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,t,e)}},i.updateBufferedPos=function(e,t,i){var r=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e))if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var s=this.playingItem,a=this.findItemIndex(s),o=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,h,u=this.findItemIndex(n),d=Math.min(u+1,t.length-1),c=t[d];if((-1===o&&n&&e>=n.end||null!=(l=c.event)&&l.appendInPlace&&e+.01>=c.start)&&(o=d),d-a>1&&!1===(null==n||null==(h=n.event)?void 0:h.appendInPlace))return;if(this.bufferedPos=e,o>u&&o>a)this.bufferedToItem(c);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&c.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(c)&&this.preloadAssets(c.event,0)}}else i&&s&&!this.itemsMatch(s,n)&&(o===a?this.bufferedToItem(s):o===a+1&&this.bufferedToItem(t[o]))}},i.assetsBuffered=function(e,t){var i=this;return 0!==e.event.assetList.length&&!e.event.assetList.some((function(e){var r=i.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))}))},i.setBufferingItem=function(e){var t=this,i=this.bufferingItem,r=this.schedule;if(this.itemsMatch(e,i))this.bufferingItem!==e&&(this.bufferingItem=e);else{var n=r.items,s=r.events;if(!n||!s)return i;var a=this.isInterstitial(e),o=this.getBufferingPlayer();if(this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos)),!this.playbackDisabled){var l=o?o.remaining:i?i.end-this.timelinePos:0;this.log("buffered to boundary "+Zs(e)+(i?" ("+l.toFixed(2)+" remaining)":"")),a?e.event.assetList.forEach((function(e){var i=t.getAssetPlayer(e.identifier);i&&i.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((function(e){return e.pauseBuffering()})))}this.hls.trigger(P.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return i},i.bufferedToItem=function(e,t){void 0===t&&(t=0);var i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;var r=this.detachedData;r&&r.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}},i.preloadPrimary=function(e){var t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)},i.bufferedToEvent=function(e,t){var i=e.event,r=0===i.assetList.length&&!i.assetListLoader,n=i.cue.once;if(r||!n){var s=this.preloadAssets(i,t);if(null!=s&&s.interstitial.appendInPlace){var a=i.assetList[t],o=this.primaryMedia;a&&o&&this.bufferAssetPlayer(s,o)}}},i.preloadAssets=function(e,t){var i=e.assetUrl,r=e.assetList.length,n=0===r&&!e.assetListLoader,s=e.cue.once;if(n){var a,o=e.timelineStart;if(e.appendInPlace){var l,h=this.playingItem;this.isInterstitial(h)||(null==h||null==(l=h.nextEvent)?void 0:l.identifier)!==e.identifier||this.flushFrontBuffer(o+.25)}var u=0;if(!this.playingItem&&this.primaryLive&&-1===(u=this.hls.startPosition)&&(u=this.hls.liveSyncPosition||0),u&&!e.cue.pre&&!e.cue.post){var d=u-o;d>0&&(a=Math.round(1e3*d)/1e3)}if(this.log("Load interstitial asset "+(t+1)+"/"+(i?1:r)+" "+e+(a?" live-start: "+u+" start-offset: "+a:"")),i)return this.createAsset(e,0,0,o,e.duration,i);var c=this.assetListLoader.loadAssetList(e,a);c&&(e.assetListLoader=c)}else if(!s&&r){for(var f=t;f<r;f++){var g=e.assetList[f],p=this.getAssetPlayerQueueIndex(g.identifier);-1!==p&&!this.playerQueue[p].destroyed||g.error||this.createAssetPlayer(e,g,f)}return this.getAssetPlayer(e.assetList[t].identifier)}return null},i.flushFrontBuffer=function(e){var t=this,i=this.requiredTracks;i&&(this.log("Removing front buffer starting at "+e),Object.keys(i).forEach((function(i){t.hls.trigger(P.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})))},i.getAssetPlayerQueueIndex=function(e){for(var t=this.playerQueue,i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1},i.getAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null},i.getBufferingPlayer=function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null},i.createAsset=function(e,t,i,r,n,s){var a={parentIdentifier:e.identifier,identifier:qs(e,s,t),duration:n,startOffset:i,timelineStart:r,uri:s};return this.createAssetPlayer(e,a,t)},i.createAssetPlayer=function(e,t,i){var r=this;this.log("create HLSAssetPlayer for "+Xs(t));var n=this.hls,s=n.userConfig,a=s.videoPreference,l=n.loadLevelObj||n.levels[n.currentLevel];(a||l)&&(a=o({},a),l.videoCodec&&(a.videoCodec=l.videoCodec),l.videoRange&&(a.allowedVideoRanges=[l.videoRange]));var h=n.audioTracks[n.audioTrack],u=n.subtitleTracks[n.subtitleTrack],d=0;if(this.primaryLive||e.appendInPlace){var f=this.timelinePos-t.timelineStart;if(f>1){var g=t.duration;g&&f<g&&(d=f)}}var p=t.identifier,v=c(c({},s),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:p,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:h||s.audioPreference,subtitlePreference:u||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(v.timelineOffset=t.timelineStart));var m=v.cmcd;null!=m&&m.sessionId&&m.contentId&&(v.cmcd=o({},m,{contentId:Ks(t.uri)})),this.getAssetPlayer(p)&&this.warn("Duplicate date range identifier "+e+" and asset "+p);var y=new Qs(this.HlsPlayerClass,v,e,t);this.playerQueue.push(y),e.assetList[i]=t;var E=function(n){if(n.live){var s=new Error("Interstitials MUST be VOD assets "+e),a={fatal:!0,type:I.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:s};r.handleAssetItemError(a,e,r.schedule.findEventIndex(e.identifier),i,s.message)}else{var o=n.edge-n.fragmentStart,l=t.duration;(null===l||o>l)&&(r.log('Interstitial asset "'+p+'" duration change '+l+" > "+o),t.duration=o,r.updateSchedule())}};y.on(P.LEVEL_UPDATED,(function(e,t){var i=t.details;return E(i)})),y.on(P.LEVEL_PTS_UPDATED,(function(e,t){var i=t.details;return E(i)}));var S=function(e,t){var i=r.getAssetPlayer(p);if(i&&t.tracks){i.off(P.BUFFER_CODECS,S),i.tracks=t.tracks;var n=r.primaryMedia;r.bufferingAsset===i.assetItem&&n&&!i.media&&r.bufferAssetPlayer(i,n)}};y.on(P.BUFFER_CODECS,S);var T=function(){var i,n=r.getAssetPlayer(p);if(r.log("buffered to end of asset "+n),n){var s=r.schedule.findEventIndex(e.identifier),a=e.findAssetIndex(t),o=a+1,l=null==(i=r.schedule.items)?void 0:i[s];if(r.isInterstitial(l))if(-1===a||e.isAssetPastPlayoutLimit(o)||e.assetList[o].error){var h,u=null==(h=r.schedule.items)?void 0:h[s+1];u&&r.bufferedToItem(u)}else r.bufferedToItem(l,o)}};y.on(P.BUFFERED_TO_END,T);var L=function(t){return function(){if(r.getAssetPlayer(p)){r.shouldPlay=!0;var i=r.schedule.findEventIndex(e.identifier);r.advanceAfterAssetEnded(e,i,t)}}};return y.once(P.MEDIA_ENDED,L(i)),y.once(P.PLAYOUT_LIMIT_REACHED,L(1/0)),y.on(P.ERROR,(function(t,n){var s=r.getAssetPlayer(p);if(n.details!==R.BUFFER_STALLED_ERROR)r.handleAssetItemError(n,e,r.schedule.findEventIndex(e.identifier),i,"Asset player error "+n.error+" "+e);else if(null!=s&&s.media){var a=s.currentTime,o=s.duration-a;a&&e.appendInPlace&&o/s.media.playbackRate<.5?(r.log("Advancing buffer past end of asset "+p+" "+e+" at "+s.media.currentTime),T()):(r.warn("Stalled at "+a+" of "+(a+o)+" in asset "+p+" "+e),r.onTimeupdate(),r.checkBuffer(!0))}})),y.on(P.DESTROYING,(function(){if(r.getAssetPlayer(p)){var t=new Error("Asset player destroyed unexpectedly "+p),n={fatal:!0,type:I.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};r.handleAssetItemError(n,e,r.schedule.findEventIndex(e.identifier),i,t.message)}})),this.hls.trigger(P.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:y}),y},i.clearInterstitial=function(e,t){var i=this;e.assetList.forEach((function(e){i.clearAssetPlayer(e.identifier,t)})),e.reset()},i.clearAssetPlayer=function(e,t){var i=this.getAssetPlayerQueueIndex(e);if(-1!==i){this.log('clearAssetPlayer "'+e+'" toSegment: '+(t?Zs(t):t));var r=this.playerQueue[i];this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy()}},i.emptyPlayerQueue=function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]},i.startAssetPlayer=function(e,t,i,r,n){var s=e.interstitial,a=e.assetItem,o=e.assetId,l=s.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log("INTERSTITIAL_ASSET_STARTED "+(t+1)+"/"+l+" "+e),this.hls.trigger(P.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:s,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)},i.bufferAssetPlayer=function(e,t){var i,r,n=e.interstitial,s=e.assetItem,a=e.assetId,o=this.schedule.findEventIndex(n.identifier),l=null==(i=this.schedule.items)?void 0:i[o];if(l){this.setBufferingItem(l),this.bufferingAsset=s;var h=this.getBufferingPlayer();if(h!==e){var u=n.appendInPlace;if(!u||!1!==(null==h?void 0:h.interstitial.appendInPlace)){var d=(null==h?void 0:h.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(u&&s!==this.playingAsset){if(!e.tracks)return;if(d&&!j(d,e.tracks)){var c=new Error('Asset "'+a+"\" SourceBuffer tracks ('"+Object.keys(e.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(d)+"')"),f={fatal:!0,type:I.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:c},g=n.findAssetIndex(s);return void this.handleAssetItemError(f,n,o,g,c.message)}}this.transferMediaTo(e,t)}}}},i.handleAssetItemError=function(e,t,i,r,n){if(e.details!==R.BUFFER_STALLED_ERROR){var s=t.assetList[r]||null,a=null;if(s){var l=this.getAssetPlayerQueueIndex(s.identifier);a=this.playerQueue[l]||null}var h=this.schedule.items,u=o({},e,{fatal:!1,errorAction:_t(!0),asset:s,assetListIndex:r,event:t,schedule:h,scheduleIndex:i,player:a});if(this.warn("Asset item error: "+e.error),this.hls.trigger(P.INTERSTITIAL_ASSET_ERROR,u),e.fatal){var d=new Error(n);s&&(this.playingAsset!==s&&this.clearAssetPlayer(s.identifier,null),s.error=d),t.assetList.some((function(e){return!e.error}))?t.appendInPlace&&(t.error=d):t.error=d,this.primaryFallback(t)}}},i.primaryFallback=function(e){var t=e.timelineStart,i=this.effectivePlayingItem;if(this.updateSchedule(),i){this.log('Fallback to primary from event "'+e.identifier+'" start: '+t+" pos: "+this.timelinePos+" playing: "+(i?Zs(i):"<none>")+" error: "+e.error),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));var r=this.timelinePos;-1===r&&(r=this.hls.startPosition);var n=this.updateItem(i,r);if(this.itemsMatch(i,n))this.clearInterstitial(e,null);else{var s=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(s)}}else this.checkStart()},i.onAssetListLoaded=function(e,t){var i,r=this,n=t.event,s=n.identifier,a=t.assetListResponse.ASSETS;if(this.schedule.hasEvent(s)){var o=n.timelineStart,l=n.duration,h=0;a.forEach((function(e,t){var i=parseFloat(e.DURATION);r.createAsset(n,t,h,o+h,i,e.URI),h+=i})),n.duration=h,this.log("Loaded asset-list with duration: "+h+" (was: "+l+") "+n);var u=this.waitingItem,d=(null==u?void 0:u.event.identifier)===s;this.updateSchedule();var c=null==(i=this.bufferingItem)?void 0:i.event;if(d){var f,g=this.schedule.findEventIndex(s),p=null==(f=this.schedule.items)?void 0:f[g];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return n.error=new Error("Interstitial no longer within playback range "+this.timelinePos+" "+n),void this.primaryFallback(n);this.setBufferingItem(p)}this.setSchedulePosition(g)}else if((null==c?void 0:c.identifier)===s&&c.appendInPlace){var v=n.assetList[0],m=this.getAssetPlayer(v.identifier),y=this.primaryMedia;v&&m&&y&&this.bufferAssetPlayer(m,y)}}},i.onError=function(e,t){switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:var i=t.interstitial;i&&this.primaryFallback(i);break;case R.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}},n(t,[{key:"interstitialsManager",get:function(){if(!this.manager){if(!this.hls)return null;var e=this,t=function(){return e.bufferingItem||e.waitingItem},i=function(t){return t?e.getAssetPlayer(t.identifier):t},r=function(t,r,s,a,o){if(t){var l=t[r].start,h=t.event;if(h){if("playout"===r||h.timelineOccupancy!==$s.Point){var u=i(s);(null==u?void 0:u.interstitial)===h&&(l+=u.assetItem.startOffset+u[o])}}else l+=("bufferedPos"===a?n():e[a])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?s("primary"):Math.max(t,0)},s=function(t){var i;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:e.schedule.durations[t]},a=function(t,n){var s,a,o=e.effectivePlayingItem;if(null==o||null==(s=o.event)||!s.restrictions.skip){e.log("seek to "+t+' "'+n+'"');var l=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,n),u=null==(a=e.schedule.items)?void 0:a[h],d=e.getBufferingPlayer(),c=null==d?void 0:d.interstitial,f=null==c?void 0:c.appendInPlace,g=l&&e.itemsMatch(l,u);if(l&&(f||g)){var p=i(e.playingAsset),v=(null==p?void 0:p.media)||e.primaryMedia;if(v){var m="primary"===n?v.currentTime:r(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-m,E=(f?m:v.currentTime)+y;if(E>=0&&(!p||f||E<=p.duration))return void(v.currentTime=E)}}if(u){var S=t;if("primary"!==n){var T=t-u[n].start;S=u.start+T}var L=!e.isInterstitial(u);if(e.isInterstitial(l)&&!l.event.appendInPlace||!L&&!u.event.appendInPlace){if(l){var _=e.findItemIndex(l);if(h>_){var b=e.schedule.findJumpRestrictedIndex(_+1,h);if(b>_)return void e.setSchedulePosition(b)}var A=0;if(L)e.timelinePos=S,e.checkBuffer();else{var I,R=null==u||null==(I=u.event)?void 0:I.assetList;if(R)for(var P=t-(u[n]||u).start,k=R.length;k--;){var D=R[k];if(D.duration&&P>=D.startOffset&&P<D.startOffset+D.duration){A=k;break}}}e.setSchedulePosition(h,A)}}else{var w=e.media||(f?null==d?void 0:d.media:null);w&&(w.currentTime=S)}}}},o=function(){var i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;var r=t();return e.isInterstitial(r)?r:null},l={get currentTime(){var t=o(),i=e.effectivePlayingItem;return i&&i===t?r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){var i=o(),r=e.effectivePlayingItem;r&&r===i&&a(t+r.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,i=null==(t=o())?void 0:t.event.assetList;return i?i.map((function(t){return e.getAssetPlayer(t.identifier)})):[]},get playingIndex(){var t,i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};this.manager={get events(){var t,i;return(null==(t=e.schedule)||null==(i=t.events)?void 0:i.slice(0))||[]},get schedule(){var t,i;return(null==(t=e.schedule)||null==(i=t.items)?void 0:i.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return s("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return s("integrated")},get seekableStart(){var t;return function(t,i){if(0!==t&&e.schedule.length){var r,n=e.schedule.findItemIndexAtTime(t),s=null==(r=e.schedule.items)?void 0:r[n];if(s)return t+(s[i].start-s.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){var r=e.findItemIndex(t);if(i.appendInPlace){var n=t.playout.start+t.event.duration;a(n+.001,"playout")}else e.advanceAfterAssetEnded(i,r,1/0)}}}}return this.manager}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t,i;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var n=this.media;!n&&null!=(e=this.bufferingItem)&&null!=(t=e.event)&&t.appendInPlace&&(n=this.primaryMedia);var s=null==(i=n)?void 0:i.currentTime;if(void 0!==s&&_(s))return s}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e,t;return null==(e=this.mediaSelection)||null==(t=e.main)?void 0:t.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}}])}(B),sa=function(e){function t(t,i,r){var n;return(n=e.call(this,t,i,r,"subtitle-stream-controller",x)||this).currentTrackId=-1,n.tracksBuffered=[],n.mainDetails=null,n.registerListeners(),n}h(t,e);var i=t.prototype;return i.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.mainDetails=null},i.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(P.LEVEL_LOADED,this.onLevelLoaded,this),t.on(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(P.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(P.LEVEL_LOADED,this.onLevelLoaded,this),t.off(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(P.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this)},i.startLoad=function(e,t){this.stopLoad(),this.state=er.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.mainDetails=null},i.onMediaDetaching=function(t,i){this.tracksBuffered=[],e.prototype.onMediaDetaching.call(this,t,i)},i.onLevelLoaded=function(e,t){this.mainDetails=t.details},i.onSubtitleFragProcessed=function(e,t){var i=t.frag,r=t.success;if(te(i)&&(this.fragPrevious=i),this.state=er.IDLE,r){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var s,a=i.start,o=0;o<n.length;o++)if(a>=n[o].start&&a<=n[o].end){s=n[o];break}var l=i.start+i.duration;s?s.end=l:(s={start:a,end:l},n.push(s)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}}},i.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach((function(e){for(var t=0;t<e.length;)if(e[t].end<=n)e.shift();else{if(!(e[t].start<n))break;e[t].start=n,t++}})),this.fragmentTracker.removeFragmentsInRange(i,n,x)}},i.onError=function(e,t){var i=t.frag;(null==i?void 0:i.type)===x&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==er.STOPPED&&(this.state=er.IDLE))},i.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks;this.levels&&Hn(this.levels,r)?this.levels=r.map((function(e){return new et(e)})):(this.tracksBuffered=[],this.levels=r.map((function(e){var t=new et(e);return i.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,x),this.fragPrevious=null,this.mediaBuffer=null)},i.onSubtitleTrackSwitch=function(e,t){var i;if(this.currentTrackId=t.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==er.STOPPED&&this.setInterval(500)}else this.clearInterval()},i.onSubtitleTrackLoaded=function(e,t){var i,r=this.currentTrackId,n=this.levels,s=t.details,a=t.id;if(n){var o=n[a];if(!(a>=n.length)&&o){if(this.log("Subtitle track "+a+" loaded ["+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+",duration:"+s.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges,s.live||null!=(i=o.details)&&i.live){var l=this.mainDetails;if(s.deltaUpdateFailed||!l)return;var h,u=l.fragments[0];o.details?0===this.alignPlaylists(s,o.details,null==(h=this.levelLastLoaded)?void 0:h.details)&&u&&Ki(s,u.start):s.hasProgramDateTime&&l.hasProgramDateTime?(Zi(s,l),s.fragmentStart):u&&Ki(s,u.start)}o.details=s,this.levelLastLoaded=o,a===r&&(this.hls.trigger(P.SUBTITLE_TRACK_UPDATED,{details:s,id:a,groupId:t.groupId}),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===er.IDLE&&(ft(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+a)},i._handleFragmentLoadComplete=function(e){var t=this,i=e.frag,r=e.payload,n=i.decryptdata,s=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=n&&n.key&&n.iv&&ii(n.method)){var a=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,ri(n.method)).catch((function(e){throw s.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((function(e){var t=performance.now();s.trigger(P.FRAG_DECRYPTED,{frag:i,payload:e,stats:{tstart:a,tdecrypt:t}})})).catch((function(e){t.warn(e.name+": "+e.message),t.state=er.IDLE}))}},i.doTick=function(){if(this.media){if(this.state===er.IDLE){var e=this.currentTrackId,t=this.levels,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;var r=this.config,n=this.getLoadPosition(),s=Wt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),a=s.end,o=s.len,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var h=l.fragments,u=h.length,d=l.edge,c=null,f=this.fragPrevious;if(a<d){var g=r.maxFragLookUpTolerance,p=a>d-g?0:g;!(c=ft(f,h,Math.max(h[0].start,a),p))&&f&&f.start<h[0].start&&(c=h[0])}else c=h[u-1];if(!(c=this.filterReplacedPrimary(c,i.details)))return;var v=h[c.sn-l.startSN-1];if(v&&v.cc===c.cc&&this.fragmentTracker.getState(v)===bt&&(c=v),this.fragmentTracker.getState(c)===bt){var m=this.mapToInitFragWhenRequired(c);m&&this.loadFragment(m,i,a)}}}else this.state=er.IDLE},i.loadFragment=function(t,i,r){te(t)?e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i)},n(t,[{key:"mediaBufferTimeRanges",get:function(){return new aa(this.tracksBuffered[this.currentTrackId]||[])}}])}(tr),aa=function(e){this.buffered=void 0;var t=function(t,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+i+") is greater than the maximum bound ("+r+")");return e[i][t]};this.buffered={get length(){return e.length},end:function(i){return t("end",i,e.length)},start:function(i){return t("start",i,e.length)}}};function oa(e,t){var i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function la(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(i){$.debug("[texttrack-utils]: "+i);try{var r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){$.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===i&&(e.mode=i)}function ha(e,t){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===i&&(e.mode=i)}function ua(e,t,i,r){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var s=function(e,t,i){var r=[],n=function(e,t){if(t<=e[0].startTime)return 0;var i=e.length-1;if(t>e[i].endTime)return-1;for(var r,n=0,s=i;n<=s;)if(t<e[r=Math.floor((s+n)/2)].startTime)s=r-1;else{if(!(t>e[r].startTime&&n<i))return r;n=r+1}return e[n].startTime-t<t-e[s].startTime?n:s}(e,t);if(n>-1)for(var s=n,a=e.length;s<a;s++){var o=e[s];if(o.startTime>=t&&o.endTime<=i)r.push(o);else if(o.startTime>i)return r}return r}(e.cues,t,i),a=0;a<s.length;a++)r&&!r(s[a])||e.removeCue(s[a]);"disabled"===n&&(e.mode=n)}function da(e){for(var t=[],i=0;i<e.length;i++){var r=e[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[i])}return t}var ca=function(e){function t(t){var i;return(i=e.call(this,t,"subtitle-track-controller")||this).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var e=null,t=da(i.media.textTracks),r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}var n=i.findTrackForTextTrack(e);i.subtitleTrack!==n&&i.setSubtitleTrack(n)}},i.registerListeners(),i}h(t,e);var i=t.prototype;return i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,e.prototype.destroy.call(this)},i.registerListeners=function(){var e=this.hls;e.on(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_PARSED,this.onManifestParsed,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(P.ERROR,this.onError,this)},i.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_PARSED,this.onManifestParsed,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(P.ERROR,this.onError,this)},i.onMediaAttached=function(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},i.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},i.onMediaDetaching=function(e,t){var i=this.media;if(i){var r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r||da(i.textTracks).forEach((function(e){ha(e)}))}},i.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},i.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},i.onSubtitleTrackLoaded=function(e,t){var i=t.id,r=t.groupId,n=t.details,s=this.tracksInGroup[i];if(s&&s.groupId===r){var a=s.details;s.details=t.details,this.log("Subtitle track "+i+' "'+s.name+'" lang:'+s.lang+" group:"+r+" loaded ["+n.startSN+"-"+n.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,t,a)}else this.warn("Subtitle track with id:"+i+" and group:"+r+" not found in active group "+(null==s?void 0:s.groupId))},i.onLevelLoading=function(e,t){this.switchLevel(t.level)},i.onLevelSwitching=function(e,t){this.switchLevel(t.level)},i.switchLevel=function(e){var t=this.hls.levels[e];if(t){var i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==r?void 0:r.indexOf(e))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var s=this.tracks.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));if(s.length)this.selectDefaultTrack&&!s.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),s.forEach((function(e,t){e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=s;var a=this.hls.config.subtitlePreference;if(!n&&a){this.selectDefaultTrack=!1;var o=at(a,s);if(o>-1)n=s[o];else{var l=at(a,this.tracks);n=this.tracks[l]}}var h=this.findTrackId(n);-1===h&&n&&(h=this.findTrackId(null));var u={subtitleTracks:s};this.log("Updating subtitle tracks, "+s.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(P.SUBTITLE_TRACKS_UPDATED,u),-1!==h&&-1===this.trackId&&this.setSubtitleTrack(h)}}},i.findTrackId=function(e){for(var t=this.tracksInGroup,i=this.selectDefaultTrack,r=0;r<t.length;r++){var n=t[r];if((!i||n.default)&&(i||e)&&(!e||ot(n,e)))return r}if(e){for(var s=0;s<t.length;s++){var a=t[s];if(Vn(e.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(var o=0;o<t.length;o++){var l=t[o];if(Vn(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1},i.findTrackForTextTrack=function(e){if(e)for(var t=this.tracksInGroup,i=0;i<t.length;i++)if(Kn(t[i],e))return i;return-1},i.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==C||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},i.setSubtitleOption=function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var i=this.currentTrack;if(i&&ot(e,i))return i;var r=at(e,this.tracksInGroup);if(r>-1){var n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}if(i)return null;var s=at(e,t);if(s>-1)return t[s]}}return null},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=t.id,n=t.groupId,s=this.getUrlWithDirectives(t.url,i),a=t.details,o=null==a?void 0:a.age;this.log("Loading subtitle "+r+' "'+t.name+'" lang:'+t.lang+" group:"+n+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+s),this.hls.trigger(P.SUBTITLE_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:i||null,track:t})},i.toggleTrackModes=function(){var e=this.media;if(e){var t,i=da(e.textTracks),r=this.currentTrack;if(r&&((t=i.filter((function(e){return Kn(r,e)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+r.name+'" and language "'+r.lang+'"')),[].slice.call(i).forEach((function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")})),t){var n=this.subtitleDisplay?"showing":"hidden";t.mode!==n&&(t.mode=n)}}},i.setSubtitleTrack=function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!_(e))this.warn("Invalid subtitle track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),r){var n=!!r.details&&!r.details.live;if(e!==this.trackId||r!==i||!n){this.log("Switching to subtitle-track "+e+(r?' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId:""));var s=r.id,a=r.groupId,o=void 0===a?"":a,l=r.name,h=r.type,u=r.url;this.hls.trigger(P.SUBTITLE_TRACK_SWITCH,{id:s,groupId:o,name:l,type:h,url:u});var d=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(d)}}else this.hls.trigger(P.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e},n(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}}])}(Gn),fa={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},ga=function(e){return String.fromCharCode(fa[e]||e)},pa=15,va=100,ma={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ya={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ea={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Sa={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ta=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],La=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var i="function"==typeof t?t():t;$.log(this.time+" ["+e+"] "+i)}},e}(),_a=function(e){for(var t=[],i=0;i<e.length;i++)t.push(e[i].toString(16));return t},ba=function(){function e(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}var t=e.prototype;return t.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},t.setStyles=function(e){for(var t=["foreground","underline","italics","background","flash"],i=0;i<t.length;i++){var r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}},t.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},t.equals=function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash},t.copy=function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash},t.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},e}(),Aa=function(){function e(){this.uchar=" ",this.penState=new ba}var t=e.prototype;return t.reset=function(){this.uchar=" ",this.penState.reset()},t.setChar=function(e,t){this.uchar=e,this.penState.copy(t)},t.setPenState=function(e){this.penState.copy(e)},t.equals=function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)},t.copy=function(e){this.uchar=e.uchar,this.penState.copy(e.penState)},t.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},e}(),Ia=function(){function e(e){this.chars=[],this.pos=0,this.currPenState=new ba,this.cueStartTime=null,this.logger=void 0;for(var t=0;t<va;t++)this.chars.push(new Aa);this.logger=e}var t=e.prototype;return t.equals=function(e){for(var t=0;t<va;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0},t.copy=function(e){for(var t=0;t<va;t++)this.chars[t].copy(e.chars[t])},t.isEmpty=function(){for(var e=!0,t=0;t<va;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e},t.setCursor=function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>va&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=va)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)},t.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},t.insertChar=function(e){var t=this;e>=144&&this.backSpace();var i=ga(e);this.pos>=va?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+i+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t<va;t++)this.chars[t].reset()},t.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},t.clearToEndOfRow=function(){this.clearFromPos(this.pos)},t.getTextString=function(){for(var e=[],t=!0,i=0;i<va;i++){var r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")},t.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),Ra=function(){function e(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var t=0;t<pa;t++)this.rows.push(new Ia(e));this.logger=e}var t=e.prototype;return t.reset=function(){for(var e=0;e<pa;e++)this.rows[e].clear();this.currRow=14},t.equals=function(e){for(var t=!0,i=0;i<pa;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t},t.copy=function(e){for(var t=0;t<pa;t++)this.rows[t].copy(e.rows[t])},t.isEmpty=function(){for(var e=!0,t=0;t<pa;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},t.backSpace=function(){this.rows[this.currRow].backSpace()},t.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},t.insertChar=function(e){this.rows[this.currRow].insertChar(e)},t.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},t.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},t.setCursor=function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)},t.setPAC=function(e){this.logger.log(2,(function(){return"pacData = "+it(e)}));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var i=0;i<pa;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var s=n.rows[r].cueStartTime,a=this.logger.time;if(null!==s&&null!==a&&s<a)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[r+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var h=e.indent,u=Math.max(h-1,0);l.setCursor(e.indent),e.color=l.chars[u].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)},t.setBkgData=function(e){this.logger.log(2,(function(){return"bkgData = "+it(e)})),this.backSpace(),this.setPen(e),this.insertChar(32)},t.setRollUpRows=function(e){this.nrRollUpRows=e},t.rollUp=function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return e.getDisplayText()}));var t=this.currRow+1-this.nrRollUpRows,i=this.rows.splice(t,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")},t.getDisplayText=function(e){e=e||!1;for(var t=[],i="",r=-1,n=0;n<pa;n++){var s=this.rows[n].getTextString();s&&(r=n+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i},t.getTextAndFormat=function(){return this.rows},e}(),Pa=function(){function e(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Ra(i),this.nonDisplayedMemory=new Ra(i),this.lastOutputScreen=new Ra(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(function(){return"MODE="+e})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},t.insertChars=function(e){for(var t=this,i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return r+": "+t.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())},t.ccRCL=function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},t.ccBS=function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},t.ccAOF=function(){},t.ccAON=function(){},t.ccDER=function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},t.ccRU=function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},t.ccFON=function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},t.ccRDC=function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},t.ccTR=function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")},t.ccRTD=function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")},t.ccEDM=function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},t.ccCR=function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},t.ccENM=function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},t.ccEOC=function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+e.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)},t.ccTO=function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},t.ccMIDROW=function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var i=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][i]}this.logger.log(2,"MIDROW: "+it(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),ka=function(){function e(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var r=this.logger=new La;this.channels=[null,new Pa(e,t,r),new Pa(e+1,i,r)]}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var i=this;this.logger.time=e;for(var r=function(e){var r=127&t[e],n=127&t[e+1],s=!1,a=null;if(0===r&&0===n)return 0;i.logger.log(3,(function(){return"["+_a([t[e],t[e+1]])+"] -> ("+_a([r,n])+")"}));var o=i.cmdHistory;if(r>=16&&r<=31){if(function(e,t,i){return i.a===e&&i.b===t}(r,n,o))return Da(null,null,o),i.logger.log(3,(function(){return"Repeated command ("+_a([r,n])+") is dropped"})),0;Da(r,n,i.cmdHistory),(s=i.parseCmd(r,n))||(s=i.parseMidrow(r,n)),s||(s=i.parsePAC(r,n)),s||(s=i.parseBackgroundAttributes(r,n))}else Da(null,null,o);if(!s&&(a=i.parseChars(r,n))){var l=i.currentChannel;l&&l>0?i.channels[l].insertChars(a):i.logger.log(2,"No channel found yet. TEXT-MODE?")}s||a||i.logger.log(2,(function(){return"Couldn't parse cleaned data "+_a([r,n])+" orig: "+_a([t[e],t[e+1]])}))},n=0;n<t.length;n+=2)r(n)},t.parseCmd=function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0},t.parseMidrow=function(e,t){var i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+_a([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var r=e<=23?1:2;i=t>=64&&t<=95?1===r?ma[e]:Ea[e]:1===r?ya[e]:Sa[e];var n=this.channels[r];return!!n&&(n.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)},t.interpretPAC=function(e,t){var i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r},t.parseChars=function(e,t){var i,r,n=null,s=null;return e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19?(r=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+ga(r)+"' in channel "+i})),n=[r]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]),n&&this.logger.log(3,(function(){return"Char codes = "+_a(n).join(",")})),n},t.parseBackgroundAttributes=function(e,t){var i;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;var r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=Ta[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(r),!0},t.reset=function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}Da(null,null,this.cmdHistory)},t.cueSplitAtTime=function(e){for(var t=0;t<this.channels.length;t++){var i=this.channels[t];i&&i.cueSplitAtTime(e)}},e}();function Da(e,t,i){i.a=e,i.b=t}var wa=function(){if(null!=ai&&ai.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function n(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];for(var n=1;n<arguments.length;n++){var s=arguments[n];for(var a in s)e[a]=s[a]}return e}function s(t,s,a){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var h="",u=!1,d=t,c=s,f=a,g=null,p="",v=!0,m="auto",y="start",E=50,S="middle",T=50,L="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return u},set:function(e){u=!!e}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return p},set:function(t){var r=function(t){return i(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");p=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return v},set:function(e){v=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return S},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return L},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");L=t,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}(),Ca=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function Ma(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}var i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}var Oa=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,i){for(var r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}},t.integer=function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},t.percent=function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1},e}();function xa(e,t,i,r){var n=r?e.split(r):[e];for(var s in n)if("string"==typeof n[s]){var a=n[s].split(i);2===a.length&&t(a[0],a[1])}}var Fa=new wa(0,0,""),Na="middle"===Fa.align?"middle":"center";function Ba(e,t,i){var r=e;function n(){var t=Ma(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function s(){e=e.replace(/^\s+/,"")}if(s(),t.startTime=n(),s(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),s(),t.endTime=n(),s(),function(e,t){var r=new Oa;xa(e,(function(e,t){var n;switch(e){case"region":for(var s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),r.integer(e,n[0]),r.percent(e,n[0])&&r.set("snapToLines",!1),r.alt(e,n[0],["auto"]),2===n.length&&r.alt("lineAlign",n[1],["start",Na,"end"]);break;case"position":n=t.split(","),r.percent(e,n[0]),2===n.length&&r.alt("positionAlign",n[1],["start",Na,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",Na,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");var n=r.get("line","auto");"auto"===n&&-1===Fa.line&&(n=-1),t.line=n,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",Na);var s=r.get("position","auto");"auto"===s&&50===Fa.position&&(s="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=s}(e,t)}function Ua(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var Ga=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new Ca,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function i(){var e=t.buffer,i=0;for(e=Ua(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;var r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var r="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var n=(r=i()).match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var s=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:r=i(),t.state){case"HEADER":/:/.test(r)?xa(r,(function(e,t){}),/:/):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new wa(0,0,""),t.state="CUE",-1===r.indexOf("--\x3e")){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Ba(r,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var a=-1!==r.indexOf("--\x3e");if(!r||a&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=r;continue;case"BADCUE":r||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},t.flush=function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this},e}(),Ha=/\r\n|\n\r|\n|\r/g,Va=function(e,t,i){return void 0===i&&(i=0),e.slice(i,i+t.length)===t};function Ka(e,t,i){return Ks(e.toString())+Ks(t.toString())+Ks(i)}var Wa="stpp.ttml.im1t",$a=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,qa=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ja={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ya(e,t,i,r){var n=ge(new Uint8Array(e),["mdat"]);if(0!==n.length){var s,a,l,h=n.map((function(e){return Y(e)})),u=(s=t.baseTime,1,void 0===(a=t.timescale)&&(a=1),void 0===l&&(l=!1),cn(s,1,1/a,l));try{h.forEach((function(e){return i(function(e,t){var i=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((function(e,t){return e[t]=i.getAttribute("ttp:"+t)||r[t],e}),{}),s="preserve"!==i.getAttribute("xml:space"),a=Xa(za(i,"styling","style")),l=Xa(za(i,"layout","region")),h=za(i,"body","[begin]");return[].map.call(h,(function(e){var i=Qa(e,s);if(!i||!e.hasAttribute("begin"))return null;var r=eo(e.getAttribute("begin"),n),h=eo(e.getAttribute("dur"),n),u=eo(e.getAttribute("end"),n);if(null===r)throw Za(e);if(null===u){if(null===h)throw Za(e);u=r+h}var d=new wa(r-t,u-t,i);d.id=Ka(d.startTime,d.endTime,d.text);var c=function(e,t,i){var r="http://www.w3.org/ns/ttml#styling",n=null,s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return s&&i.hasOwnProperty(s)&&(n=i[s]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((function(i,s){var a=Ja(t,r,s)||Ja(e,r,s)||Ja(n,r,s);return a&&(i[s]=a),i}),{})}(l[e.getAttribute("region")],a[e.getAttribute("style")],a),f=c.textAlign;if(f){var g=ja[f];g&&(d.lineAlign=g),d.align=f}return o(d,c),d})).filter((function(e){return null!==e}))}(e,u))}))}catch(e){r(e)}}else r(new Error("Could not parse IMSC1 mdat"))}function za(e,t,i){var r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Xa(e){return e.reduce((function(e,t){var i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function Qa(e,t){return[].slice.call(e.childNodes).reduce((function(e,i,r){var n;return"br"===i.nodeName&&r?e+"\n":null!=(n=i.childNodes)&&n.length?Qa(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function Ja(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Za(e){return new Error("Could not parse ttml timestamp "+e)}function eo(e,t){if(!e)return null;var i=Ma(e);return null===i&&($a.test(e)?i=function(e,t){var i=$a.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):qa.test(e)&&(i=function(e,t){var i=qa.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}var to=function(){function e(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}var t=e.prototype;return t.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},t.newCue=function(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}(),io=function(){function e(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(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_LOADED,this.onManifestLoaded,this),e.on(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(P.FRAG_LOADING,this.onFragLoading,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this),e.on(P.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(P.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(P.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(P.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=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_LOADED,this.onManifestLoaded,this),e.off(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(P.FRAG_LOADING,this.onFragLoading,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this),e.off(P.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(P.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(P.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(P.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){var e=new to(this,"textTrack1"),t=new to(this,"textTrack2"),i=new to(this,"textTrack3"),r=new to(this,"textTrack4");this.cea608Parser1=new ka(1,e,t),this.cea608Parser2=new ka(3,i,r)},t.addCues=function(e,t,i,r,n){for(var s,a,o,l,h=!1,u=n.length;u--;){var d=n[u],c=(s=d[0],a=d[1],o=t,l=i,Math.min(a,l)-Math.max(s,o));if(c>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],i),h=!0,c/(i-t)>.5))return}if(h||n.push([t,i]),this.config.renderTextTracksNatively){var f=this.captionsTracks[e];this.Cues.newCue(f,t,i,r)}else{var g=this.Cues.newCue(null,t,i,r);this.hls.trigger(P.CUES_PARSED,{type:"captions",cues:g,track:e})}},t.onInitPtsFound=function(e,t){var i=this,r=t.frag,n=t.id,s=t.initPTS,a=t.timescale,o=this.unparsedVttFrags;n===M&&(this.initPTS[r.cc]={baseTime:s,timescale:a}),o.length&&(this.unparsedVttFrags=[],o.forEach((function(e){i.onFragLoaded(P.FRAG_LOADED,e)})))},t.getExistingTrack=function(e,t){var i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var n=i.textTracks[r];if(no(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null},t.createCaptionsTrack=function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)},t.createNativeTrack=function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,i=this.captionsTracks,r=this.media,n=t[e],s=n.label,a=n.languageCode,o=this.getExistingTrack(s,a);if(o)i[e]=o,ha(i[e]),oa(i[e],r);else{var l=this.createTextTrack("captions",s,a);l&&(l[e]=!0,i[e]=l)}}},t.createNonNativeTrack=function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(P.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}},t.createTextTrack=function(e,t,i){var r=this.media;if(r)return r.addTextTrack(e,t,i)},t.onMediaAttaching=function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()},t.onMediaDetaching=function(e,t){var i=!!t.transferMedia;if(this.media=null,!i){var r=this.captionsTracks;Object.keys(r).forEach((function(e){ha(r[e]),delete r[e]})),this.nonNativeCaptionsTracks={}}},t.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},t._cleanTracks=function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var i=0;i<t.length;i++)ha(t[i])}},t.onSubtitleTracksUpdated=function(e,t){var i=this,r=t.subtitleTracks||[],n=r.some((function(e){return e.textCodec===Wa}));if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Hn(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var s=this.media,a=s?da(s.textTracks):null;if(this.tracks.forEach((function(e,t){var r;if(a){for(var n=null,s=0;s<a.length;s++)if(a[s]&&no(a[s],e)){n=a[s],a[s]=null;break}n&&(r=n)}if(r)ha(r);else{var o=ro(e);(r=i.createTextTrack(o,e.name,e.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)})),null!=a&&a.length){var o=a.filter((function(e){return null!==e})).map((function(e){return e.label}));o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: "+o.join(", ")+". Replace media element for each source to clear TextTracks and captions menu.")}}else if(this.tracks.length){var l=this.tracks.map((function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}}));this.hls.trigger(P.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}},t.onManifestLoaded=function(e,t){var i=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var r="textTrack"+t[1],n=i.captionsProperties[r];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}}))},t.closedCaptionsForLevel=function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]},t.onFragLoading=function(e,t){if(this.enabled&&t.frag.type===M){var i,r,n=this.cea608Parser1,s=this.cea608Parser2,a=this.lastSn,o=t.frag,l=o.cc,h=o.sn,u=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;n&&s&&(h!==a+1||h===a&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),s.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=u}},t.onFragLoaded=function(e,t){var i=t.frag,r=t.payload;if(i.type===x)if(r.byteLength){var n=i.decryptdata,s="stats"in t;if(null==n||!n.encrypted||s){var a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===Wa?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})},t._parseIMSC1=function(e,t){var i=this,r=this.hls;Ya(t,this.initPTS[e.cc],(function(t){i._appendCues(t,e.level),r.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(function(t){r.logger.log("Failed to parse IMSC1: "+t),r.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))},t._parseVTTs=function(e){var t,i=this,r=e.frag,n=e.payload,s=this.initPTS,a=this.unparsedVttFrags,o=s.length-1;if(s[r.cc]||-1!==o){var l=this.hls;!function(e,t,i,r,n,s,a){var o,l,h,u=new Ga,d=Y(new Uint8Array(e)).trim().replace(Ha,"\n").split("\n"),c=[],f=t?(o=t.baseTime,void 0===(l=t.timescale)&&(l=1),cn(o,9e4,1/l)):0,g="00:00.000",p=0,v=0,m=!0;u.oncue=function(e){var s=i[r],a=i.ccOffset,o=(p-f)/9e4;if(null!=s&&s.new&&(void 0!==v?a=i.ccOffset=s.start:function(e,t,i){var r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(s=n)&&s.new;){var s;e.ccOffset+=r.start-n.start,r.new=!1,n=e[(r=n).prevCC]}e.presentationOffset=i}(i,r,o)),o){if(!t)return void(h=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}var l=e.endTime-e.startTime,u=yn(9e4*(e.startTime+a-v),9e4*n)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);var d=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(d)),e.id||(e.id=Ka(e.startTime,e.endTime,d)),e.endTime>0&&c.push(e)},u.onparsingerror=function(e){h=e},u.onflush=function(){h?a(h):s(c)},d.forEach((function(e){if(m){if(Va(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((function(e){Va(e,"LOCAL:")?g=e.slice(6):Va(e,"MPEGTS:")&&(p=parseInt(e.slice(7)))}));try{v=function(e){var t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(_(t)&&_(i)&&_(r)&&_(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*i,(t+=6e4*r)+36e5*n}(g)/1e3}catch(e){h=e}return}""===e&&(m=!1)}u.parse(e+"\n")})),u.flush()}(null!=(t=r.initSegment)&&t.data?be(r.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(function(e){i._appendCues(e,r.level),l.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(function(t){var s="Missing initPTS for VTT MPEGTS"===t.message;s?a.push(e):i._fallbackToIMSC1(r,n),l.logger.log("Failed to parse VTT cue: "+t),s&&o>r.cc||l.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}else a.push(e)},t._fallbackToIMSC1=function(e,t){var i=this,r=this.tracks[e.level];r.textCodec||Ya(t,this.initPTS[e.cc],(function(){r.textCodec=Wa,i._parseIMSC1(e,t)}),(function(){r.textCodec="wvtt"}))},t._appendCues=function(e,t){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach((function(e){return la(r,e)}))}else{var n=this.tracks[t];if(!n)return;var s=n.default?"default":"subtitles"+t;i.trigger(P.CUES_PARSED,{type:"subtitles",cues:e,track:s})}},t.onFragDecrypted=function(e,t){t.frag.type===x&&this.onFragLoaded(P.FRAG_LOADED,t)},t.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},t.onFragParsingUserdata=function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var i=t.frag,r=t.samples;if(i.type!==M||"NONE"!==this.closedCaptionsForLevel(i))for(var n=0;n<r.length;n++){var s=r[n].bytes;if(s){this.cea608Parser1||this.initCea608Parsers();var a=this.extractCea608Data(s);this.cea608Parser1.addData(r[n].pts,a[0]),this.cea608Parser2.addData(r[n].pts,a[1])}}}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,n=t.endOffsetSubtitles,s=t.type,a=this.media;if(a&&!(a.currentTime<r)){if(!s||"video"===s){var o=this.captionsTracks;Object.keys(o).forEach((function(e){return ua(o[e],i,r)}))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==n){var l=this.textTracks;Object.keys(l).forEach((function(e){return ua(l[e],i,n)}))}}},t.extractCea608Data=function(e){for(var t=[[],[]],i=31&e[0],r=2,n=0;n<i;n++){var s=e[r++],a=127&e[r++],o=127&e[r++];if((0!==a||0!==o)&&4&s){var l=3&s;0!==l&&1!==l||(t[l].push(a),t[l].push(o))}}return t},e}();function ro(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function no(e,t){return!!e&&e.kind===ro(t)&&Kn(t,e)}var so=/\s/,ao={newCue:function(e,t,i,r){for(var n,s,a,o,l,h=[],u=self.VTTCue||self.TextTrackCue,d=0;d<r.rows.length;d++)if(a=!0,o=0,l="",!(n=r.rows[d]).isEmpty()){for(var c,f=0;f<n.chars.length;f++)so.test(n.chars[f].uchar)&&a?o++:(l+=n.chars[f].uchar,a=!1);n.cueStartTime=t,t===i&&(i+=1e-4),o>=16?o--:o++;var g=Ua(l.trim()),p=Ka(t,i,g);null!=e&&null!=(c=e.cues)&&c.getCueById(p)||((s=new u(t,i,g)).id=p,s.line=d+1,s.align="left",s.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(s))}return e&&h.length&&(h.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),h.forEach((function(t){return la(e,t)}))),h}},oo=/(\d+)-(\d+)\/(\d+)/,lo=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||ho,this.controller=new self.AbortController,this.stats=new X}var t=e.prototype;return t.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},t.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},t.load=function(e,t,i){var r=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var s=function(e,t){var i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(o({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(e,this.controller.signal),a="arraybuffer"===e.responseType,l=a?"byteLength":"length",h=t.loadPolicy,u=h.maxTimeToFirstByteMs,d=h.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=u&&_(u)?u:d,this.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(n,e,r.response))}),t.timeout),(Rn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(i){var s;r.response=r.loader=i;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(r.requestTimeout),t.timeout=d,r.requestTimeout=self.setTimeout((function(){r.callbacks&&(r.abortInternal(),r.callbacks.onTimeout(n,e,r.response))}),d-(o-n.loading.start)),!i.ok){var l=i.status,h=i.statusText;throw new uo(h||"fetch, bad network response",l,i)}n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var i=function(e){var t=oo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(_(i))return i}var r=e.get("Content-Length");if(r)return parseInt(r)}(i.headers)||n.total;var u=null==(s=r.callbacks)?void 0:s.onProgress;return u&&_(t.highWaterMark)?r.loadProgressively(i,n,e,t.highWaterMark,u):a?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((function(i){var s,a,o=r.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var h=i[l];h&&(n.loaded=n.total=h);var u={url:o.url,data:i,code:o.status},d=null==(s=r.callbacks)?void 0:s.onProgress;d&&!_(t.highWaterMark)&&d(n,e,i,o),null==(a=r.callbacks)||a.onSuccess(u,n,e,o)})).catch((function(t){var i;if(self.clearTimeout(r.requestTimeout),!n.aborted){var s=t&&t.code||0,a=t?t.message:null;null==(i=r.callbacks)||i.onError({code:s,text:a},e,t?t.details:null,n)}}))},t.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},t.loadProgressively=function(e,t,i,r,n){void 0===r&&(r=0);var s=new rr,a=e.body.getReader(),o=function(){return a.read().then((function(a){if(a.done)return s.dataLength&&n(t,i,s.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return t.loaded+=h,h<r||s.dataLength?(s.push(l),s.dataLength>=r&&n(t,i,s.flush().buffer,e)):n(t,i,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},e}();function ho(e,t){return new self.Request(e.url,t)}var uo=function(e){function t(t,i,r){var n;return(n=e.call(this,t)||this).code=void 0,n.details=void 0,n.code=i,n.details=r,n}return h(t,e),t}(p(Error)),co=/^age:\s*[\d.]+\s*$/im,fo=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 X,this.retryDelay=0}var t=e.prototype;return t.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},t.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},t.load=function(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()},t.loadInternal=function(){var e=this,t=this.config,i=this.context;if(t&&i){var r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var s=this.xhrSetup;s?Promise.resolve().then((function(){if(e.loader===r&&!e.stats.aborted)return s(r,i.url)})).catch((function(t){if(e.loader===r&&!e.stats.aborted)return r.open("GET",i.url,!0),s(r,i.url)})).then((function(){e.loader!==r||e.stats.aborted||e.openAndSendXhr(r,i,t)})).catch((function(t){var s;null==(s=e.callbacks)||s.onError({code:r.status,text:t.message},i,r,n)})):this.openAndSendXhr(r,i,t)}},t.openAndSendXhr=function(e,t,i){e.readyState||e.open("GET",t.url,!0);var r=t.headers,n=i.loadPolicy,s=n.maxTimeToFirstByteMs,a=n.maxLoadTimeMs;if(r)for(var o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&_(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()},t.readystatechange=function(){var e=this.context,t=this.loader,i=this.stats;if(e&&t){var r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var s=t.status,a="text"===t.responseType?t.responseText:null;if(s>=200&&s<300){var o=null!=a?a:t.response;if(null!=o){var l,h;i.loading.end=Math.max(self.performance.now(),i.loading.first);var u="arraybuffer"===t.responseType?o.byteLength:o.length;i.loaded=i.total=u,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(i,e,o,t);var c={url:t.responseURL,data:o,code:s};return void(null==(h=this.callbacks)||h.onSuccess(c,i,e,t))}}var f,g=n.loadPolicy.errorRetry;Tt(g,i.retry,!1,{url:e.url,data:void 0,code:s})?this.retry(g):($.error(s+" while loading "+e.url),null==(f=this.callbacks)||f.onError({code:s,text:t.statusText},e,t,i))}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(Tt(e,this.stats.retry,!0))this.retry(e);else{var t;$.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,i=this.stats;this.retryDelay=Et(e,i.retry),i.retry++,$.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?void 0:t.url)+", retrying "+i.retry+"/"+e.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&co.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}(),go=c(c({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:fo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:dt,bufferController:zn,capLevelController:Zn,errorController:Lt,fpsController:Vs,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:mi,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:ao,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:sa,subtitleTrackController:ca,timelineController:io,audioStreamController:Un,audioTrackController:Wn,emeController:Gs,cmcdController:Fs,contentSteeringController:Ns,interstitialsController:na});function po(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(po):Object.keys(e).reduce((function(t,i){return t[i]=po(e[i]),t}),{}):e}var vo=function(e){function t(t,i){var r;return(r=e.call(this,"gap-controller",t.logger)||this).hls=null,r.fragmentTracker=null,r.media=null,r.mediaSource=void 0,r.nudgeRetry=0,r.stallReported=!1,r.stalled=null,r.moved=!1,r.seeking=!1,r.buffered={},r.lastCurrentTime=0,r.ended=0,r.waiting=0,r.onMediaPlaying=function(){r.ended=0,r.waiting=0},r.onMediaWaiting=function(){var e;null!=(e=r.media)&&e.seeking||(r.waiting=self.performance.now(),r.tick())},r.onMediaEnded=function(){var e;r.hls&&(r.ended=(null==(e=r.media)?void 0:e.currentTime)||1,r.hls.trigger(P.MEDIA_ENDED,{stalled:!1}))},r.hls=t,r.fragmentTracker=i,r.registerListeners(),r}h(t,e);var i=t.prototype;return i.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))},i.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))},i.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},i.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var i=this.media=t.media;ta(i,"playing",this.onMediaPlaying),ta(i,"waiting",this.onMediaWaiting),ta(i,"ended",this.onMediaEnded)},i.onMediaDetaching=function(e,t){this.clearInterval();var i=this.media;i&&(ia(i,"playing",this.onMediaPlaying),ia(i,"waiting",this.onMediaWaiting),ia(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},i.onBufferAppended=function(e,t){this.buffered=t.timeRanges},i.tick=function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}},i.poll=function(e,t){var i,r,n=null==(i=this.hls)?void 0:i.config;if(n){var s=this.media,a=this.stalled;if(s){var o=s.seeking,l=this.seeking&&!o,h=!this.seeking&&o,u=s.paused&&!o||s.ended||0===s.playbackRate;if(this.seeking=o,e!==t)return t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.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&&s.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(P.MEDIA_ENDED,{stalled:!1})));if(Wt.getBuffered(s).length){var d=Wt.bufferInfo(s,e,0),c=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){var g=mo(this.hls.inFlightFragments,e),p=d.len>2,v=!c||g||c-e>2&&!f.getPartialFragment(e);if(p||v)return;this.moved=!1}var m=null==(r=this.hls)?void 0:r.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!=m&&m.live?2*m.targetduration:2,S=f.getPartialFragment(e);if(y>0&&(y<=E||S))return void(s.paused||this._trySkipBufferHole(S))}var T=n.detectStallWithCurrentTimeMs,L=self.performance.now(),_=this.waiting;if(null!==a){var b=L-a;if(!o&&(b>=T||_)&&this.hls){var A;if("ended"===(null==(A=this.mediaSource)?void 0:A.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(d),!this.media||!this.hls)return}var I=Wt.bufferInfo(s,e,n.maxBufferHole);this._tryFixBufferStall(I,b)}else this.stalled=_>0&&L-_<T?_:L}else this.nudgeRetry=0}}}},i.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var i=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(i)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(P.STALL_RESOLVED,{})}},i.nudgeOnVideoHole=function(e,t){var i,r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){var n=Wt.bufferedInfo(Wt.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var s=Wt.timeRangesToArray(r),a=Wt.bufferedInfo(s,t,0).bufferedIndex;if(a>-1&&a<s.length-1){var o=Wt.bufferedInfo(s,e,0).bufferedIndex,l=s[a].end,h=s[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=Wt.bufferInfo(this.media,e,0);this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:c.len,bufferInfo:c})}}}}},i._tryFixBufferStall=function(e,t){var i,r,n=this.fragmentTracker,s=this.media,a=null==(i=this.hls)?void 0:i.config;if(s&&n&&a){var o=s.currentTime,l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=n.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))}},i._reportStall=function(e){var t=this.hls,i=this.media,r=this.stallReported,n=this.stalled;if(!r&&null!==n&&i&&t){this.stallReported=!0;var s=new Error("Playback stalling at @"+i.currentTime+" due to low buffer ("+it(e)+")");this.warn(s.message),t.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len,bufferInfo:e,stalled:{start:n}})}},i._trySkipBufferHole=function(e){var t,i=this.fragmentTracker,r=this.media,n=null==(t=this.hls)?void 0:t.config;if(!r||!i||!n)return 0;var s=r.currentTime,a=Wt.bufferInfo(r,s,0),o=s<a.start?a.start:a.nextStart;if(o&&this.hls){var l=a.len<=n.maxBufferHole,h=a.len>0&&a.len<1&&r.readyState<3,u=o-s;if(u>0&&(l||h)){if(u>n.maxBufferHole){var d=!1;if(0===s){var c=i.getAppendedFrag(0,M);c&&o<c.end&&(d=!0)}if(!d){var f=e||i.getAppendedFrag(s,M);if(f){var g;if(null==(g=this.hls.loadLevelObj)||!g.details)return 0;if(mo(this.hls.inFlightFragments,o))return 0;for(var p=!1,v=f.end;v<o;){var m=i.getPartialFragment(v);if(!m){p=!0;break}v+=m.duration}if(p)return 0}}}var y=Math.max(o+.05,s+.1);if(this.warn("skipping hole, adjusting currentTime from "+s+" to "+y),this.moved=!0,r.currentTime=y,null==e||!e.gap){var E=new Error("fragment loaded with buffer holes, seeking from "+s+" to "+y);this.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:E,reason:E.message,frag:e||void 0,buffer:a.len,bufferInfo:a})}return y}}return 0},i._tryNudgeBuffer=function(e){var t=this.hls,i=this.media,r=this.nudgeRetry,n=null==t?void 0:t.config;if(!i||!n)return 0;var s=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){var a=s+(r+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from "+s+" to "+a);this.warn(o.message),i.currentTime=a,t.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.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 @"+s+" after "+n.nudgeMaxRetry+" nudges");this.error(l.message),t.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}},n(t,[{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}}])}(Ht);function mo(e,t){var i=yo(e.main);if(i&&i.start<=t)return i;var r=yo(e.audio);return r&&r.start<=t?r:null}function yo(e){if(!e)return null;switch(e.state){case er.IDLE:case er.STOPPED:case er.ENDED:case er.ERROR:return null}return e.frag}function Eo(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function So(e,t,i,r,n){var s=new e(t,i,"");try{s.value=r,n&&(s.type=n)}catch(a){s=new e(t,i,it(n?c({type:n},r):r))}return s}var To=function(){var e=Eo();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),Lo=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 i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.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&&ha(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})},t.onManifestLoading=function(){this.dateRangeCuesAppended={}},t.createTrack=function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t},t.getID3Track=function(e){if(this.media){for(var t=0;t<e.length;t++){var i=e[t];if("metadata"===i.kind&&"id3"===i.label)return oa(i,this.media),i}return this.media.addTextTrack("metadata","id3")}},t.onFragParsingMetadata=function(e,t){if(this.media){var i=this.hls.config,r=i.enableEmsgMetadataCues,n=i.enableID3MetadataCues;if(r||n){var s=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=Eo();if(a)for(var o=0;o<s.length;o++){var l=s[o].type;if((l!==Rr.emsg||r)&&n){var h=_r(s[o].data);if(h){var u=s[o].pts,d=u+s[o].duration;d>To&&(d=To),d-u<=0&&(d=u+.25);for(var c=0;c<h.length;c++){var f=h[c];if(!br(f)){this.updateId3CueEnds(u,l);var g=So(a,u,d,f,l);g&&this.id3Track.addCue(g)}}}}}}}},t.updateId3CueEnds=function(e,t){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var n=r.length;n--;){var s=r[n];s.type===t&&s.startTime<e&&s.endTime===To&&(s.endTime=e)}},t.onBufferFlushing=function(e,t){var i=t.startOffset,r=t.endOffset,n=t.type,s=this.id3Track,a=this.hls;if(a){var o=a.config,l=o.enableEmsgMetadataCues,h=o.enableID3MetadataCues;s&&(l||h)&&ua(s,i,r,"audio"===n?function(e){return e.type===Rr.audioId3&&h}:"video"===n?function(e){return e.type===Rr.emsg&&l}:function(e){return e.type===Rr.audioId3&&h||e.type===Rr.emsg&&l})}},t.onLevelUpdated=function(e,t){var i=t.details;this.updateDateRangeCues(i,!0)},t.onLevelPtsUpdated=function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var i=this;if(this.media&&e.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var r,n=this.id3Track,s=e.dateRanges,a=Object.keys(s),o=this.dateRangeCuesAppended;if(n&&t)if(null!=(r=n.cues)&&r.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 r=t[e];r.removeEventListener("enter",i.onEventCueEnter),n.removeCue(r)}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=Eo(),f=function(){var e=a[g],t=s[e],r=t.startTime,n=o[e],l=(null==n?void 0:n.cues)||{},h=(null==n?void 0:n.durationKnown)||!1,u=To,d=t.duration;if(t.endDate&&null!==d)u=r+d,h=!0;else if(t.endOnNext&&!h){var f=a.reduce((function(e,i){if(i!==t.id){var r=s[i];if(r.class===t.class&&r.startDate>t.startDate&&(!e||t.startDate<e.startDate))return r}return e}),null);f&&(u=f.startTime,h=!0)}for(var p,v,m=Object.keys(t.attr),y=0;y<m.length;y++){var E=m[y];if("ID"!==(v=E)&&"CLASS"!==v&&"CUE"!==v&&"START-DATE"!==v&&"DURATION"!==v&&"END-DATE"!==v&&"END-ON-NEXT"!==v){var S=l[E];if(S)h&&!n.durationKnown?S.endTime=u:Math.abs(S.startTime-r)>.01&&(S.startTime=r,S.endTime=u);else if(c){var T=t.attr[E];Zt(E)&&(p=T,T=Uint8Array.from(p.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);var L=So(c,r,u,{key:E,data:T},Rr.dateRange);L&&(L.id=e,i.id3Track.addCue(L),l[E]=L,i.hls.config.interstitialsController&&("X-ASSET-LIST"!==E&&"X-ASSET-URL"!==E||L.addEventListener("enter",i.onEventCueEnter)))}}}o[e]={cues:l,dateRange:t,durationKnown:h}},g=0;g<a.length;g++)f()}}},e}(),_o=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e=t.media,i=t.levelDetails;if(e&&i){t.currentTime=e.currentTime;var r=t.computeLatency();if(null!==r){t._latency=r;var n=t.config,s=n.lowLatencyMode,a=n.maxLiveSyncPlaybackRate;if(s&&1!==a&&i.live){var o=t.targetLatency;if(null!==o){var l=r-o;if(l<Math.min(t.maxLatency,o+i.targetduration)&&l>.05&&t.forwardBufferLength>1){var h=Math.min(2,Math.max(1,a)),u=Math.round(2/(1+Math.exp(-.75*l-t.edgeStalled))*20)/20,d=Math.min(h,Math.max(1,u));t.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&t.changeMediaPlaybackRate(e,1)}}}}},this.hls=e,this.config=e.config,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},t.registerListeners=function(){var e=this.hls;e&&(e.on(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 i=t.details;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onError=function(e,t){var i;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(r=this.targetLatency)?void 0:r.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+e.playbackRate+" to "+t),e.playbackRate=t)},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},n(e,[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,i=e.partHoldBack,r=e.targetduration,n=this.config,s=n.liveSyncDuration,a=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,h=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==s?s:a*r);var u=r;return h+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var i=this.levelDetails;if(null===i)return null;var r=i.edge,n=e-t-this.edgeStalled,s=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(s,n),a)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}}])}(),bo=function(e){function t(t,i){var r;return(r=e.call(this,t,"level-controller")||this)._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,r._registerListeners(),r}h(t,e);var i=t.prototype;return i._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)},i._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)},i.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},i.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},i.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},i.onManifestLoading=function(e,t){this.resetLevels()},i.onManifestLoaded=function(e,t){var i=this,r=this.hls.config.preferManagedMediaSource,n=[],s={},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=He(d,r)||void 0),0===(null==(t=c)?void 0:t.indexOf("avc1"))&&(c=e.videoCodec=function(e){for(var t=e.split(","),i=0;i<t.length;i++){var r=t[i].split(".");if(r.length>2){var n=r.shift()+".";n+=parseInt(r.shift()).toString(16),n+=("000"+parseInt(r.shift()).toString(16)).slice(-4),t[i]=n}}return t.join(",")}(c));var f=e.width,g=e.height,p=e.unknownCodecs,v=p?p.length:0;if(p)for(var m=v;m--;){var y=p[m];i.isAudioSupported(y)?(e.audioCodec=d=d?d+","+y:y,v--,Ce.audio[d.substring(0,4)]=2):i.isVideoSupported(y)&&(e.videoCodec=c=c?c+","+y:y,v--,Ce.video[c.substring(0,4)]=2)}if(o||(o=!(!f||!g)),l||(l=!!c),h||(h=!!d),v||d&&!i.isAudioSupported(d)||c&&!i.isVideoSupported(c))i.log('Some or all CODECS not supported "'+u.CODECS+'"');else{var E=u.CODECS,S=u["FRAME-RATE"],T=u["HDCP-LEVEL"],L=u["PATHWAY-ID"],_=u.RESOLUTION,b=u["VIDEO-RANGE"],A=(L||".")+"-"+e.bitrate+"-"+_+"-"+S+"-"+E+"-"+b+"-"+T;if(s[A])if(s[A].uri===e.url||e.attrs["PATHWAY-ID"])s[A].addGroupId("audio",u.AUDIO),s[A].addGroupId("text",u.SUBTITLES);else{var I=a[A]+=1;e.attrs["PATHWAY-ID"]=new Array(I+1).join(".");var R=i.createLevel(e);s[A]=R,n.push(R)}else{var P=i.createLevel(e);s[A]=P,a[A]=1,n.push(P)}}})),this.filterAndSortMediaOptions(n,t,o,l,h)},i.createLevel=function(e){var t=new et(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){var r=new Error('SUPPLEMENTAL-CODECS not supported "'+i.videoCodec+'"');this.log(r.message),t.supportedResult=je(r,[])}return t},i.isAudioSupported=function(e){return Oe(e,"audio",this.hls.config.preferManagedMediaSource)},i.isVideoSupported=function(e){return Oe(e,"video",this.hls.config.preferManagedMediaSource)},i.filterAndSortMediaOptions=function(e,t,i,r,n){var s=this,a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter((function(e){var t,i=e.videoCodec,r=e.videoRange,n=e.width,s=e.height;return(!!i||!(!n||!s))&&!!(t=r)&&Qe.indexOf(t)>-1}))),0!==l.length){t.audioTracks&&Ao(a=t.audioTracks.filter((function(e){return!e.audioCodec||s.isAudioSupported(e.audioCodec)}))),t.subtitles&&Ao(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(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Qe.indexOf(e.videoRange)-Qe.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var r=Ne(e.videoCodec),n=Ne(t.videoCodec);if(r!==n)return n-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var s=Be(e.codecSet),a=Be(t.codecSet);if(s!==a)return a-s}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 v=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);v>p&&p===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}var m=n&&!r,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:n,video:r,altAudio:E&&!m&&a.some((function(e){return!!e.url}))};this.hls.trigger(P.MANIFEST_PARSED,S)}else Promise.resolve().then((function(){if(s.hls){var e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i="one or more CODECS in variant not supported: "+it(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,i){return i.indexOf(e)===t}))),s.warn(i),e+=" ("+i+")");var r=new Error(e);s.hls.trigger(P.ERROR,{type:I.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}))},i.onError=function(e,t){!t.fatal&&t.context&&t.context.type===D&&t.context.level===this.level&&this.checkRetry(t)},i.onFragBuffered=function(e,t){var i=t.frag;if(void 0!==i&&i.type===M){var r=i.elementaryStreams;if(!Object.keys(r).some((function(e){return!!r[e]})))return;var n=this._levels[i.level];null!=n&&n.loadError&&(this.log("Resetting level error count of "+n.loadError+" on frag buffered"),n.loadError=0)}},i.onLevelLoaded=function(e,t){var i,r,n=t.level,s=t.details,a=t.levelInfo;if(!a)return this.warn("Invalid level index "+n),void(null!=(r=t.deliveryDirectives)&&r.skip&&(s.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(n,t,o)}else null!=(i=t.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)},i.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},i.loadingPlaylist=function(t,i){e.prototype.loadingPlaylist.call(this,t,i);var r=this.getUrlWithDirectives(t.uri,i),n=this.currentLevelIndex,s=t.attrs["PATHWAY-ID"],a=t.details,o=null==a?void 0:a.age;this.log("Loading level index "+n+(void 0!==(null==i?void 0:i.msn)?" at sn "+i.msn+" part "+i.part:"")+(s?" Pathway "+s:"")+(o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):"")+" "+r),this.hls.trigger(P.LEVEL_LOADING,{url:r,level:n,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:i||null})},i.removeLevel=function(e){var t,i=this;if(1!==this._levels.length){var r=this._levels.filter((function(t,r){return r!==e||(i.steering&&i.steering.removeLevel(t),t===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));Yi(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=r.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(P.LEVELS_UPDATED,{levels:r})}},i.onLevelsUpdated=function(e,t){var i=t.levels;this._levels=i},i.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,i=e.maxAutoLevel,r=e.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(P.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))},n(t,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,s=this.currentLevel,a=s?s.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!s||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 "+n+(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==s?void 0:s.details,u);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),i=e.filter((function(e){return-1!==t.indexOf(e)}));if(e.length<1)return void this.warn("pathwayPriority "+e+" should contain at least one pathway from list: "+t);this.steering.pathwayPriority=i}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])}(Gn);function Ao(e){var t={};e.forEach((function(e){var i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}function Io(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ro(){if(!q())return!1;var e=Io();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var Po=function(e){function t(t,i,r){var n;return(n=e.call(this,t,i,r,"stream-controller",M)||this).audioCodecSwap=!1,n.level=-1,n._forceStartLoad=!1,n._hasEnoughToStart=!1,n.altAudio=0,n.audioOnly=!1,n.fragPlaying=null,n.fragLastKbps=0,n.couldBacktrack=!1,n.backtrackFragment=null,n.audioCodecSwitch=!1,n.videoBuffer=null,n.onMediaPlaying=function(){n.tick()},n.onMediaSeeked=function(){var e=n.media,t=e?e.currentTime:null;if(null!==t&&_(t)&&(n.log("Media seeked to "+t.toFixed(3)),n.getBufferedFrag(t))){var i=n.getFwdBufferInfoAtPos(e,t,M,0);null!==i&&0!==i.len?n.tick():n.warn("Main forward buffer length at "+t+' on "seeked" event '+(i?i.len:"empty")+")")}},n.registerListeners(),n}h(t,e);var i=t.prototype;return i.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)},i.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)},i.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},i.startLoad=function(e,t){if(this.levels){var i=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=r.startLevel;-1===n&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @"+i.toFixed(3)),e=i),this.state=er.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=er.STOPPED},i.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},i.doTick=function(){switch(this.state){case er.WAITING_LEVEL:var e=this.levels,t=this.level,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=er.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=er.IDLE;break}break;case er.FRAG_LOADING_WAITING_RETRY:var n,s=self.performance.now(),a=this.retryDate;if(!a||s>=a||null!=(n=this.media)&&n.seeking){var o=this.levels,l=this.level,h=null==o?void 0:o[l];this.resetStartWhenNotLoaded(h||null),this.state=er.IDLE}}this.state===er.IDLE&&this.doTickIdle(),this.onTickEnd()},i.onTickEnd=function(){var t;e.prototype.onTickEnd.call(this),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},i.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,i=this.levels,r=this.media;if(null!==t&&(r||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=i&&i[n]){var s=i[n],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=er.ENDED)}if(this.buffering){e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level "+n+" from level "+this.level),this.level=e.nextLoadLevel=n;var h=s.details;if(!h||this.state===er.WAITING_LEVEL||this.waitForLive(s))return this.level=n,this.state=er.WAITING_LEVEL,void(this.startFragRequested=!1);var u=a.len,d=this.getMaxBufferLength(s.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&&te(f)&&this.fragmentTracker.getState(f)!==Rt){var g,p=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,v=h.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?Q:J,y=(m===J?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m,M)}f=this.getNextFragmentLoopLoading(f,h,a,M,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,s,c))}}}}}},i.loadFragment=function(t,i,r){var n=this.fragmentTracker.getState(t);n===bt||n===It?te(t)?this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,i)):e.prototype.loadFragment.call(this,t,i,r):this._loadInitSegment(t,i):this.clearTrackerIfNeeded(t)},i.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,M)},i.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},i.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},i.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var s=this.getMainFwdBufferInfo();if(!s||s.len<2*n.targetduration)return}if(!t.paused&&e){var a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;i=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(t.currentTime+i);if(l){var h=this.followingBufferedFrag(l);if(h){this.abortCurrentFrag();var u=h.maxStartPTS?h.maxStartPTS:h.start,d=h.duration,c=Math.max(l.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},i.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case er.KEY_LOADING:case er.FRAG_LOADING:case er.FRAG_LOADING_WAITING_RETRY:case er.PARSING:case er.PARSED:this.state=er.IDLE}this.nextLoadPosition=this.getLoadPosition()},i.flushMainBuffer=function(t,i){e.prototype.flushMainBuffer.call(this,t,i,2===this.altAudio?"video":null)},i.onMediaAttached=function(t,i){e.prototype.onMediaAttached.call(this,t,i);var r=i.media;ta(r,"playing",this.onMediaPlaying),ta(r,"seeked",this.onMediaSeeked)},i.onMediaDetaching=function(t,i){var r=this.media;r&&(ia(r,"playing",this.onMediaPlaying),ia(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,e.prototype.onMediaDetaching.call(this,t,i),i.transferMedia||(this._hasEnoughToStart=!1)},i.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(P.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},i.onManifestParsed=function(e,t){var i,r,n=!1,s=!1;t.levels.forEach((function(e){var t=e.audioCodec;t&&(n=n||-1!==t.indexOf("mp4a.40.2"),s=s||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=n&&s&&!("function"==typeof(null==(r=Io())||null==(i=r.prototype)?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1},i.onLevelLoading=function(e,t){if(this.levels&&this.state===er.IDLE){var i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=er.WAITING_LEVEL)}},i.onLevelLoaded=function(e,t){var i,r=this.levels,n=this.startFragRequested,s=t.level,a=t.details,o=a.totalduration;if(r){this.log("Level "+s+" 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!==er.FRAG_LOADING&&this.state!==er.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&this.abortCurrentFrag();var u=0;if(a.live||null!=(i=l.details)&&i.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,n||this.setStartPosition(a,u),this.hls.trigger(P.LEVEL_UPDATED,{details:a,level:s}),this.state===er.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=er.IDLE}n&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}else this.warn("Levels were reset while loading level "+s)},i.synchronizeToLiveEdge=function(e){var t=this.config,i=this.media;if(i){var r=this.hls.liveSyncPosition,n=this.getLoadPosition(),s=e.fragmentStart,a=e.edge,o=n>=s-t.maxFragLookUpTolerance&&n<=a;if(null!==r&&i.duration>r&&(n<r||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&i.readyState<4||n<a-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState&&(this.warn("Playback: "+n.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+r.toFixed(3)),i.currentTime=r))}}},i._handleFragmentLoadProgress=function(e){var t,i=e.frag,r=e.part,n=e.payload,s=this.levels;if(s){var a=s[i.level];if(a){var o=a.details;if(!o)return this.warn("Dropping fragment "+i.sn+" of level "+i.level+" after level details were reset"),void this.fragmentTracker.removeFragment(i);var l=a.videoCodec,h=o.PTSKnown||!o.live,u=null==(t=i.initSegment)?void 0:t.data,d=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Bn(this.hls,M,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,p=new Vt(i.level,i.sn,i.stats.chunkCount,n.byteLength,f,g),v=this.initPTS[i.cc];c.push(n,u,d,l,i,r,o.totalduration,h,p,v)}else this.warn("Level "+i.level+" not found on progress")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i.onAudioTrackSwitching=function(e,t){var i=this,r=this.hls,n=2===this.altAudio;if(ut(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;s&&(this.log("Switching to main audio track, cancel main fragment load"),s.abortRequests(),this.fragmentTracker.removeFragment(s)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n)return this.fragmentTracker.removeAllFragments(),r.once(P.BUFFER_FLUSHED,(function(){var e;null==(e=i.hls)||e.trigger(P.AUDIO_TRACK_SWITCHED,t)})),void r.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(P.AUDIO_TRACK_SWITCHED,t)}},i.onAudioTrackSwitched=function(e,t){var i=ut(t.url,this.hls);if(i){var r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i?2:0,this.tick()},i.onBufferCreated=function(e,t){var i,r,n=t.tracks,s=!1;for(var a in n){var o=n[a];if("main"===o.id){if(r=a,i=o,"video"===a){var l=n[a];l&&(this.videoBuffer=l.buffer)}}else s=!0}s&&i?(this.log("Alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media},i.onFragBuffered=function(e,t){var i=t.frag,r=t.part,n=i.type===M;if(n){if(this.fragContextChanged(i))return this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===er.PARSED&&(this.state=er.IDLE));var s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),te(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}var a=this.media;a&&(!this._hasEnoughToStart&&Wt.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())},i.onError=function(e,t){var i;if(t.fatal)this.state=er.ERROR;else switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(M,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==er.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==D||(this.state=er.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},i.onFragLoadEmergencyAborted=function(){this.state=er.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},i.onBufferFlushed=function(e,t){var i=t.type;if(i!==Q||!this.altAudio){var r=(i===J?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,i,M),this.tick())}},i.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels},i.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},i.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log("could not seek to "+i+", already seeking at "+t);var r=this.timelineOffset;r&&i&&(i+=r);var n=this.getLevelDetails(),s=Wt.getBuffered(e),a=s.length?s.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);o>0&&(o<l||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0))&&(this.log("adjusting start position by "+o+" to match buffer start"),i+=o,this.startPosition=i),t<i&&(this.log("seek to target start position "+i+" from current time "+t+" buffer start "+a),e.currentTime=i)}}},i._getAudioCodec=function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t},i._loadBitrateTestFrag=function(e,t){var i=this;e.bitrateTest=!0,this._doFragLoad(e,t).then((function(e){var r=i.hls,n=null==e?void 0:e.frag;if(n&&!i.fragContextChanged(n)){t.fragmentError=0,i.state=er.IDLE,i.startFragRequested=!1,i.bitrateTest=!1;var s=n.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(P.FRAG_LOADED,e),n.bitrateTest=!1}}))},i._handleTransmuxComplete=function(e){var t,i=this.playlistType,r=this.hls,n=e.remuxResult,s=e.chunkMeta,a=this.getCurrentContext(s);if(a){var o=a.frag,l=a.part,h=a.level,u=n.video,d=n.text,c=n.id3,f=n.initSegment,g=h.details,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=er.PARSING,f){if(null!=f&&f.tracks){var v=o.initSegment||o;this._bufferInitSegment(h,f.tracks,v,s),r.trigger(P.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:f.tracks})}var m=f.initPTS,y=f.timescale;_(m)&&(this.initPTS[o.cc]={baseTime:m,timescale:y},r.trigger(P.INIT_PTS_FOUND,{frag:o,id:i,initPTS:m,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!==n.independent){var L=u.startPTS,b=u.endPTS,A=u.startDTS,I=u.endDTS;if(l)l.elementaryStreams[u.type]={startPTS:L,endPTS:b,startDTS:A,endDTS:I};else if(u.firstKeyFrame&&u.independent&&1===s.id&&!T&&(this.couldBacktrack=!0),u.dropped&&u.independent){var R=this.getMainFwdBufferInfo(),k=(R?R.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:L;if(!S&&k<D-this.config.maxBufferHole&&!T)return void this.backtrack(o);T&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,b,o.start,I,!0)}else S&&L-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,L,b,A,I),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,s,S||T)}else{if(!S&&!T)return void this.backtrack(o);o.gap=!0}}if(p){var w=p.startPTS,C=p.endPTS,M=p.startDTS,O=p.endDTS;l&&(l.elementaryStreams[Q]={startPTS:w,endPTS:C,startDTS:M,endDTS:O}),o.setElementaryStreamInfo(Q,w,C,M,O),this.bufferFragmentData(p,o,l,s)}if(g&&null!=c&&null!=(t=c.samples)&&t.length){var x={id:i,frag:o,details:g,samples:c.samples};r.trigger(P.FRAG_PARSING_METADATA,x)}if(g&&d){var F={id:i,frag:o,details:g,samples:d.samples};r.trigger(P.FRAG_PARSING_USERDATA,F)}}}else this.resetWhenMissingContext(s)},i.logMuxedErr=function(e){this.warn((te(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},i._bufferInitSegment=function(e,t,i,r){var n=this;if(this.state===er.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));var s=t.audio,a=t.video,o=t.audiovideo;if(s){var l=Ve(s.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=s.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"!==s.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+'"'),s.levelCodec=l,s.id=M,this.log("Init audio buffer, container:"+s.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(e.audioCodec||"")+"/"+s.codec+"]"),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=M;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 s=t[e].initSegment;null!=s&&s.byteLength&&n.hls.trigger(P.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}},i.getMainFwdBufferInfo=function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,M)},i.backtrack=function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=er.IDLE},i.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var i=e.currentTime;if(Wt.isBuffered(e,i)?t=this.getAppendedFrag(i):Wt.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;var r=this.fragPlaying,n=t.level;r&&t.sn===r.sn&&r.level===n||(this.fragPlaying=t,this.hls.trigger(P.FRAG_CHANGED,{frag:t}),r&&r.level===n||this.hls.trigger(P.LEVEL_SWITCHED,{level:n}))}}},n(t,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return _(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(_(t)){var i=this.getLevelDetails(),r=this.currentFrag||(i?ft(null,i.fragments,t):null);if(r){var n=r.programDateTime;if(null!==n){var s=n+1e3*(t-r.start);return new Date(s)}}}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}}])}(tr),ko=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 i=this.keyUriToKeyInfo[t].loader;if(i){var r;if(e&&e!==(null==(r=i.context)?void 0:r.frag.type))return;i.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,i,r,n){return void 0===t&&(t=R.KEY_LOAD_ERROR),new Gt({type:I.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})},t.loadClear=function(e,t){var i=this;if(this.emeController&&this.config.emeEnabled)for(var r=e.sn,n=e.cc,s=function(){var e=t[a];if(n<=e.cc&&("initSegment"===r||"initSegment"===e.sn||r<e.sn))return i.emeController.selectKeySystemFormat(e).then((function(t){e.setKeyFormat(t)})),1},a=0;a<t.length&&!s();a++);},t.load=function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(i){return t.loadInternal(e,i)})):this.loadInternal(e)},t.loadInternal=function(e,t){var i,r;t&&e.setKeyFormat(t);var n=e.decryptdata;if(!n){var s=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,R.KEY_LOAD_ERROR,s))}var a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+a+'"')));var o,l=this.keyUriToKeyInfo[a];if(null!=(i=l)&&i.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(null!=(r=l)&&r.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 n.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:l}}))}switch(l=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.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,R.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+n.method+'"')))}},t.loadKeyEME=function(e,t){var i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r=this.emeController.loadKey(i);if(r)return(e.keyLoadPromise=r.then((function(t){return e.mediaKeySessionContext=t,i}))).catch((function(t){throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)},t.loadKeyHTTP=function(e,t){var i=this,r=this.config,n=new(0,r.loader)(r);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((function(s,a){var o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,n){var o=r.frag,l=r.keyInfo,h=r.url;if(!o.decryptdata||l!==i.keyUriToKeyInfo[h])return a(i.createKeyLoadError(o,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,l.loader=null,s({frag:o,keyInfo:l})},onError:function(e,r,n,s){i.resetLoader(r),a(i.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error("HTTP Error "+e.code+" loading key "+e.text),n,c({url:o.url,data:void 0},e)))},onTimeout:function(e,r,n){i.resetLoader(r),a(i.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:function(e,r,n){i.resetLoader(r),a(i.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(o,h,u)}))},t.resetLoader=function(e){var t=e.frag,i=e.keyInfo,r=e.url,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy()},e}();function Do(e){switch(e.type){case w:return O;case C:return x;default:return M}}function wo(e,t){var i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}var Co=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,i=t.pLoader,r=t.loader,n=new(i||r)(t);return this.loaders[e.type]=n,n},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var i=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:k,url:i,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var i=t.id,r=t.level,n=t.pathwayId,s=t.url,a=t.deliveryDirectives,o=t.levelInfo;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:D,url:s,deliveryDirectives:a,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var i=t.id,r=t.groupId,n=t.url,s=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:w,url:n,deliveryDirectives:s,levelOrTrack:a})},t.onSubtitleTrackLoading=function(e,t){var i=t.id,r=t.groupId,n=t.url,s=t.deliveryDirectives,a=t.track;this.load({id:i,groupId:r,level:null,responseType:"text",type:C,url:n,deliveryDirectives:s,levelOrTrack:a})},t.onLevelsUpdated=function(e,t){var i=this.loaders[D];if(i){var r=i.context;r&&!t.levels.some((function(e){return e===r.levelOrTrack}))&&(i.abort(),delete this.loaders[D])}},t.load=function(e){var t,i,r,n=this,s=this.hls.config,a=this.getInternalLoader(e);if(a){var l=this.hls.logger,h=a.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),a.abort()}if(i=e.type===k?s.manifestLoadPolicy.default:o({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(e),_(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===D&&null!==e.level?r=this.hls.levels[e.level].details:e.type===w&&null!==e.id?r=this.hls.audioTracks[e.id].details:e.type===C&&null!==e.id&&(r=this.hls.subtitleTracks[e.id].details),r)){var u=r.partTarget,d=r.targetduration;if(u&&d){var c=1e3*Math.max(3*u,.8*d);i=o({},i,{maxTimeToFirstByteMs:Math.min(c,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,i.maxTimeToFirstByteMs)})}}var f=i.errorRetry||i.timeoutRetry||{},g={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},p={onSuccess:function(e,t,i,r){var s=n.getInternalLoader(i);n.resetInternalLoader(i.type);var a=e.data;0===a.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Ii.isMediaPlaylist(a)||i.type!==k?n.handleTrackOrLevelPlaylist(e,t,i,r||null,s):n.handleMasterPlaylist(e,t,i,r)):n.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),r||null,t)},onError:function(e,t,i,r){n.handleNetworkError(t,i,!1,e,r)},onTimeout:function(e,t,i){n.handleNetworkError(t,i,!0,void 0,e)}};a.load(e,g,p)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,i=t.autoStartLoad,r=t.startPosition,n=e.forceStartLoad;(i||n)&&(this.hls.logger.log((i?"auto":"force")+" startLoad with configured startPosition "+r),this.hls.startLoad(r))}},t.handleMasterPlaylist=function(e,t,i,r){var n=this.hls,s=e.data,a=wo(e,i),o=Ii.parseMasterPlaylist(s,a);if(o.playlistParsingError)this.handleManifestParsingError(e,i,o.playlistParsingError,r,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=Ii.parseMasterPlaylistMedia(s,a,o),p=g.AUDIO,v=void 0===p?[]:p,m=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];v.length&&(v.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"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Jt({}),bitrate:0,url:""}))),n.trigger(P.MANIFEST_LOADED,{levels:h,audioTracks:v,subtitles:m,captions:y,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:u,sessionKeys:d,startTimeOffset:c,variableList:f})}},t.handleTrackOrLevelPlaylist=function(e,t,i,r,n){var s=this.hls,a=i.id,o=i.level,l=i.type,h=wo(e,i),u=_(o)?o:_(a)?a:0,d=Do(i),c=Ii.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===k){var f={attrs:new Jt({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=t.loading.start+Wi(c,0),s.trigger(P.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,e,t,i,r,n)},t.handleManifestParsingError=function(e,t,i,r,n){this.hls.trigger(P.ERROR,{type:I.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===k,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n})},t.handleNetworkError=function(e,t,i,r,n){void 0===i&&(i=!1);var s="A network "+(i?"timeout":"error"+(r?" (status "+r.code+")":""))+" occurred while loading "+e.type;e.type===D?s+=": "+e.level+" id: "+e.id:e.type!==w&&e.type!==C||(s+=" id: "+e.id+' group-id: "'+e.groupId+'"');var a=new Error(s);this.hls.logger.warn("[playlist-loader]: "+s);var o=R.UNKNOWN,l=!1,h=this.getInternalLoader(e);switch(e.type){case k:o=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case D:o=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case w:o=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case C:o=i?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);var u={type:I.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:n};if(r){var d=(null==t?void 0:t.url)||e.url;u.response=c({url:d,data:void 0},r)}this.hls.trigger(P.ERROR,u)},t.handlePlaylistLoaded=function(e,t,i,r,n,s){var a=this.hls,o=r.type,l=r.level,h=r.id,u=r.groupId,d=r.deliveryDirectives,c=wo(t,r),f=Do(r),g="number"==typeof r.level&&f===M?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:I.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:p,reason:p.message,response:t,context:r,level:g,parent:f,networkDetails:n,stats:i});e.playlistParsingError=null}switch(e.live&&s&&(s.getCacheAge&&(e.ageHeader=s.getCacheAge()||0),s.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case k:case D:a.trigger(P.LEVEL_LOADED,{details:e,levelInfo:r.levelOrTrack||a.levels[0],level:g||0,id:h||0,stats:i,networkDetails:n,deliveryDirectives:d,withoutMultiVariant:o===k});break;case w:a.trigger(P.AUDIO_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:d});break;case C:a.trigger(P.SUBTITLE_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:d})}}else{var v=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(P.ERROR,{type:I.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:v,reason:v.message,response:t,context:r,level:g,parent:f,networkDetails:n,stats:i})}},e}(),Mo=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 S,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var i=this.logger=W(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=po(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var s=("level"===e?"playlist":e)+"LoadPolicy",a=void 0===t[s],o=[];n.forEach((function(i){var n=e+"Loading"+i,l=t[n];if(void 0!==l&&a){o.push(n);var h=r[s].default;switch(t[s]={default:h},i){case"TimeOut":h.maxLoadTimeMs=l,h.maxTimeToFirstByteMs=l;break;case"MaxRetry":h.errorRetry.maxNumRetry=l,h.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":h.errorRetry.retryDelayMs=l,h.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=l,h.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+s+'": '+it(t[s]))})),c(c({},r),t)}(e.DefaultConfig,t,i);this.userConfig=t,r.progressive&&function(e,t){var i=e.loader;i!==lo&&i!==fo?(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=lo,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(r,i);var n=r.abrController,s=r.bufferController,a=r.capLevelController,o=r.errorController,l=r.fpsController,h=new o(this),u=this.abrController=new n(this),d=new Pt(this),f=r.interstitialsController,g=f?this.interstitialsController=new f(this,e):null,p=this.bufferController=new s(this,d),v=this.capLevelController=new a(this),m=new l(this),y=new Co(this),E=r.contentSteeringController,T=E?new E(this):null,L=this.levelController=new bo(this,T),_=new Lo(this),b=new ko(this.config),A=this.streamController=new Po(this,d,b),I=this.gapController=new vo(this,d);v.setStreamController(A),m.setStreamController(A);var R=[y,L,A];g&&R.splice(1,0,g),T&&R.splice(1,0,T),this.networkControllers=R;var k=[u,p,I,v,m,_,d];this.audioTrackController=this.createController(r.audioTrackController,R);var D=r.audioStreamController;D&&R.push(this.audioStreamController=new D(this,d,b)),this.subtitleTrackController=this.createController(r.subtitleTrackController,R);var w=r.subtitleStreamController;w&&R.push(this.subtititleStreamController=new w(this,d,b)),this.createController(r.timelineController,k),b.emeController=this.emeController=this.createController(r.emeController,k),this.cmcdController=this.createController(r.cmcdController,k),this.latencyController=this.createController(_o,k),this.coreComponents=k,R.push(h);var C=h.onErrorOut;"function"==typeof C&&this.on(P.ERROR,C,h),this.on(P.MANIFEST_LOADED,y.onManifestLoaded,y)}e.isMSESupported=function(){return Ro()},e.isSupported=function(){return function(){if(!Ro())return!1;var e=q();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(Fe(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Fe(t,"audio"))})))}()},e.getMediaSource=function(){return q()};var t=e.prototype;return t.createController=function(e,t){if(e){var i=new e(this);return t&&t.push(i),i}return null},t.on=function(e,t,i){void 0===i&&(i=this),this._emitter.on(e,t,i)},t.once=function(e,t,i){void 0===i&&(i=this),this._emitter.once(e,t,i)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,i,r){void 0===i&&(i=this),this._emitter.off(e,t,i,r)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,i){return this._emitter.emit(e,t,i)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var i=e===P.ERROR;this.trigger(P.ERROR,{type:I.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){this.logger.log("destroy"),this.trigger(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:I.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var i="media"in e,r=i?e.media:e,n=i?e:{media:r};this._media=r,this.trigger(P.MEDIA_ATTACHING,n)}},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,i=this._url,r=this._url=L.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+r),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(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 i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);},t.stopLoad=function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);},t.resumeBuffering=function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((function(e){e.resumeBuffering&&e.resumeBuffering()})))},t.pauseBuffering=function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((function(e){e.pauseBuffering&&e.pauseBuffering()})))},t.swapAudioCodec=function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.recoverMediaError=function(){this.logger.log("recoverMediaError");var e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))},t.removeLevel=function(e){this.levelController.removeLevel(e)},t.setAudioOption=function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null},t.setSubtitleOption=function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null},t.getMediaDecodingInfo=function(e,t){return void 0===t&&(t=this.allAudioTracks),ze(e,nt(t),navigator.mediaCapabilities)},n(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={})[M]=this.streamController.inFlightFrag,e);return this.audioStreamController&&(t[O]=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(r){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(i+16*Math.random())%16|0;return i=Math.floor(i/16),("x"==e?t:3&t|8).toString(16)}))}}}()),e}},{key:"levels",get:function(){return this.levelController.levels||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return Xe.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var i=e.length,r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(var n=e;n--;){var s=t[n].attrs["HDCP-LEVEL"];if(s&&s<=r)return n}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 xn}},{key:"Events",get:function(){return P}},{key:"MetadataSchema",get:function(){return Rr}},{key:"ErrorTypes",get:function(){return I}},{key:"ErrorDetails",get:function(){return R}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:go},set:function(t){e.defaultConfig=t}}])}();return Mo.defaultConfig=void 0,Mo},e.exports=r()}(!1)},424:(e,t)=>{"use strict";t.h=n;var i=2147483647;function r(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=n.prototype,t}function n(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return s(e,t,i)}function s(e,t,i){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!n.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var i=0|u(e,t),s=r(i),a=s.write(e,t);a!==i&&(s=s.slice(0,a));return s}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(m(e,ArrayBuffer)||e&&m(e.buffer,ArrayBuffer))return function(e,t,i){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(i||0))throw new RangeError('"length" is outside of buffer bounds');var r;r=void 0===t&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,t):new Uint8Array(e,t,i);return r.__proto__=n.prototype,r}(e,t,i);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var s=e.valueOf&&e.valueOf();if(null!=s&&s!==e)return n.from(s,t,i);var a=function(e){if(n.isBuffer(e)){var t=0|h(e.length),i=r(t);return 0===i.length||e.copy(i,0,0,t),i}if(void 0!==e.length)return"number"!=typeof e.length||y(e.length)?r(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return n.from(e[Symbol.toPrimitive]("string"),t,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function a(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function o(e){return a(e),r(e<0?0:0|h(e))}function l(e){for(var t=e.length<0?0:0|h(e.length),i=r(t),n=0;n<t;n+=1)i[n]=255&e[n];return i}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function u(e,t){if(n.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||m(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var i=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===i)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return v(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;default:if(s)return r?-1:v(e).length;t=(""+t).toLowerCase(),s=!0}}function d(e,t,i,r){i=Number(i)||0;const n=e.length-i;r?(r=Number(r))>n&&(r=n):r=n;const s=t.length;let a;for(r>s/2&&(r=s/2),a=0;a<r;++a){const r=parseInt(t.substr(2*a,2),16);if(y(r))return a;e[i+a]=r}return a}function c(e,t,i,r){return p(v(t,e.length-i),e,i,r)}function f(e,t,i,r){return p(function(e){const t=[];for(let i=0;i<e.length;++i)t.push(255&e.charCodeAt(i));return t}(t),e,i,r)}function g(e,t,i,r){return p(function(e,t){let i,r,n;const s=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)i=e.charCodeAt(a),r=i>>8,n=i%256,s.push(n),s.push(r);return s}(t,e.length-i),e,i,r)}function p(e,t,i,r){let n;for(n=0;n<r&&!(n+i>=t.length||n>=e.length);++n)t[n+i]=e[n];return n}function v(e,t){var i;t=t||1/0;for(var r=e.length,n=null,s=[],a=0;a<r;++a){if((i=e.charCodeAt(a))>55295&&i<57344){if(!n){if(i>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&s.push(239,191,189);continue}n=i;continue}if(i<56320){(t-=3)>-1&&s.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(t-=3)>-1&&s.push(239,191,189);if(n=null,i<128){if((t-=1)<0)break;s.push(i)}else if(i<2048){if((t-=2)<0)break;s.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;s.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return s}function m(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&n[Symbol.species]===n&&Object.defineProperty(n,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),n.from=function(e,t,i){return s(e,t,i)},n.prototype.__proto__=Uint8Array.prototype,n.__proto__=Uint8Array,n.alloc=function(e,t,i){return function(e,t,i){return a(e),e<=0?r(e):void 0!==t?"string"==typeof i?r(e).fill(t,i):r(e).fill(t):r(e)}(e,t,i)},n.allocUnsafe=function(e){return o(e)},n.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==n.prototype},n.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}},n.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return n.alloc(0);var i;if(void 0===t)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=n.allocUnsafe(t),s=0;for(i=0;i<e.length;++i){var a=e[i];if(m(a,Uint8Array)&&(a=n.from(a)),!n.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(r,s),s+=a.length}return r},n.byteLength=u,n.prototype._isBuffer=!0,n.prototype.copy=function(e,t,i,r){if(!n.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var s=r-i;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,i,r);else if(this===e&&i<t&&t<r)for(var a=s-1;a>=0;--a)e[a+t]=this[a+i];else Uint8Array.prototype.set.call(e,this.subarray(i,r),t);return s},n.prototype.write=function(e,t,i,r){if(void 0===t)r="utf8",i=this.length,t=0;else if(void 0===i&&"string"==typeof t)r=t,i=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(i)?(i>>>=0,void 0===r&&(r="utf8")):(r=i,i=void 0)}const n=this.length-t;if((void 0===i||i>n)&&(i=n),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!1;for(;;)switch(r){case"hex":return d(this,e,t,i);case"utf8":case"utf-8":return c(this,e,t,i);case"ascii":case"latin1":case"binary":return f(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,i);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}}},832:function(e,t,i){var r;!function(n){"use strict";function s(e,t){var i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function a(e,t,i,r,n,a){return s((o=s(s(t,e),s(r,a)))<<(l=n)|o>>>32-l,i);var o,l}function o(e,t,i,r,n,s,o){return a(t&i|~t&r,e,t,n,s,o)}function l(e,t,i,r,n,s,o){return a(t&r|i&~r,e,t,n,s,o)}function h(e,t,i,r,n,s,o){return a(t^i^r,e,t,n,s,o)}function u(e,t,i,r,n,s,o){return a(i^(t|~r),e,t,n,s,o)}function d(e,t){var i,r,n,a,d;e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;var c=1732584193,f=-271733879,g=-1732584194,p=271733878;for(i=0;i<e.length;i+=16)r=c,n=f,a=g,d=p,c=o(c,f,g,p,e[i],7,-680876936),p=o(p,c,f,g,e[i+1],12,-389564586),g=o(g,p,c,f,e[i+2],17,606105819),f=o(f,g,p,c,e[i+3],22,-1044525330),c=o(c,f,g,p,e[i+4],7,-176418897),p=o(p,c,f,g,e[i+5],12,1200080426),g=o(g,p,c,f,e[i+6],17,-1473231341),f=o(f,g,p,c,e[i+7],22,-45705983),c=o(c,f,g,p,e[i+8],7,1770035416),p=o(p,c,f,g,e[i+9],12,-1958414417),g=o(g,p,c,f,e[i+10],17,-42063),f=o(f,g,p,c,e[i+11],22,-1990404162),c=o(c,f,g,p,e[i+12],7,1804603682),p=o(p,c,f,g,e[i+13],12,-40341101),g=o(g,p,c,f,e[i+14],17,-1502002290),c=l(c,f=o(f,g,p,c,e[i+15],22,1236535329),g,p,e[i+1],5,-165796510),p=l(p,c,f,g,e[i+6],9,-1069501632),g=l(g,p,c,f,e[i+11],14,643717713),f=l(f,g,p,c,e[i],20,-373897302),c=l(c,f,g,p,e[i+5],5,-701558691),p=l(p,c,f,g,e[i+10],9,38016083),g=l(g,p,c,f,e[i+15],14,-660478335),f=l(f,g,p,c,e[i+4],20,-405537848),c=l(c,f,g,p,e[i+9],5,568446438),p=l(p,c,f,g,e[i+14],9,-1019803690),g=l(g,p,c,f,e[i+3],14,-187363961),f=l(f,g,p,c,e[i+8],20,1163531501),c=l(c,f,g,p,e[i+13],5,-1444681467),p=l(p,c,f,g,e[i+2],9,-51403784),g=l(g,p,c,f,e[i+7],14,1735328473),c=h(c,f=l(f,g,p,c,e[i+12],20,-1926607734),g,p,e[i+5],4,-378558),p=h(p,c,f,g,e[i+8],11,-2022574463),g=h(g,p,c,f,e[i+11],16,1839030562),f=h(f,g,p,c,e[i+14],23,-35309556),c=h(c,f,g,p,e[i+1],4,-1530992060),p=h(p,c,f,g,e[i+4],11,1272893353),g=h(g,p,c,f,e[i+7],16,-155497632),f=h(f,g,p,c,e[i+10],23,-1094730640),c=h(c,f,g,p,e[i+13],4,681279174),p=h(p,c,f,g,e[i],11,-358537222),g=h(g,p,c,f,e[i+3],16,-722521979),f=h(f,g,p,c,e[i+6],23,76029189),c=h(c,f,g,p,e[i+9],4,-640364487),p=h(p,c,f,g,e[i+12],11,-421815835),g=h(g,p,c,f,e[i+15],16,530742520),c=u(c,f=h(f,g,p,c,e[i+2],23,-995338651),g,p,e[i],6,-198630844),p=u(p,c,f,g,e[i+7],10,1126891415),g=u(g,p,c,f,e[i+14],15,-1416354905),f=u(f,g,p,c,e[i+5],21,-57434055),c=u(c,f,g,p,e[i+12],6,1700485571),p=u(p,c,f,g,e[i+3],10,-1894986606),g=u(g,p,c,f,e[i+10],15,-1051523),f=u(f,g,p,c,e[i+1],21,-2054922799),c=u(c,f,g,p,e[i+8],6,1873313359),p=u(p,c,f,g,e[i+15],10,-30611744),g=u(g,p,c,f,e[i+6],15,-1560198380),f=u(f,g,p,c,e[i+13],21,1309151649),c=u(c,f,g,p,e[i+4],6,-145523070),p=u(p,c,f,g,e[i+11],10,-1120210379),g=u(g,p,c,f,e[i+2],15,718787259),f=u(f,g,p,c,e[i+9],21,-343485551),c=s(c,r),f=s(f,n),g=s(g,a),p=s(p,d);return[c,f,g,p]}function c(e){var t,i="",r=32*e.length;for(t=0;t<r;t+=8)i+=String.fromCharCode(e[t>>5]>>>t%32&255);return i}function f(e){var t,i=[];for(i[(e.length>>2)-1]=void 0,t=0;t<i.length;t+=1)i[t]=0;var r=8*e.length;for(t=0;t<r;t+=8)i[t>>5]|=(255&e.charCodeAt(t/8))<<t%32;return i}function g(e){var t,i,r="0123456789abcdef",n="";for(i=0;i<e.length;i+=1)t=e.charCodeAt(i),n+=r.charAt(t>>>4&15)+r.charAt(15&t);return n}function p(e){return unescape(encodeURIComponent(e))}function v(e){return function(e){return c(d(f(e),8*e.length))}(p(e))}function m(e,t){return function(e,t){var i,r,n=f(e),s=[],a=[];for(s[15]=a[15]=void 0,n.length>16&&(n=d(n,8*e.length)),i=0;i<16;i+=1)s[i]=909522486^n[i],a[i]=1549556828^n[i];return r=d(s.concat(f(t)),512+8*t.length),c(d(a.concat(r),640))}(p(e),p(t))}function y(e,t,i){return t?i?m(t,e):g(m(t,e)):i?v(e):g(v(e))}void 0===(r=function(){return y}.call(t,i,t,e))||(e.exports=r)}()},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var i={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(r())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return i.isAndroid()||i.isAndroidWebView()?t.ANDROID_WEB:i.isIOS()||i.isIpad()||i.isIOSWebView()?t.IOS_WEB:i.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(r())},isPC:function(){return!s(n("os "))&&!s(n("android[/ ]"))},isIOS:function(){return s(n("os "))},isIpad:function(){return r().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return s(n("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(r())},isMobile:function(){return i.isAndroid()||i.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(r())},isFirefox:function(){return/firefox/i.test(r())},isChrome:function(){return/chrome/i.test(r())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=r();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=r();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return i.isAndroidWebView()||i.isIOSWebView()},device:t,getBrowser:function(){return i.isX5()?"X5":i.isAndroidWebView()?"Android-WebView":i.isIOSWebView()?"iOS-WebView":i.isChrome()?"Chrome":i.isFirefox()?"Firefox":i.isIpadSafari()?"iPad-Safari":i.isIOSSafari()?"iPhone-Safari":i.isSafari()?"Mac-Safari":"Unknown"}};function r(){return navigator.userAgent.toLowerCase()}function n(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(r())||[,0])[1]||void 0}function s(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=i}},t={};function i(r){var n=t[r];if(void 0!==n)return n.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,i),s.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var r={};return(()=>{"use strict";i.d(r,{default:()=>Fi});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 n=i(415),s=i.n(n),a=i(424),o=i(558),l=i.n(o);const h="__PROXY_IDENTIFIER__";const u=64e3;function d(){return!0}function c(e){return new URL(location.href).searchParams.get(e)}function f(e,t,i){const r=new URL(e);return r.searchParams.append(t,i),r.href}function g(){return Date.parse(new Date)/1e3}function p(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function v(e){return new Promise((t=>setTimeout(t,e)))}function m(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function y(e){const t=a.h.from(e),i=new a.h(e.byteLength);return t.copy(i),i}function E(){return location.protocol.startsWith("https")}function S(e,t,i){if(e.size<=t)return;const r=[...e.keys()];do{const t=r.shift();i&&i(e.get(t)),e.delete(t)}while(e.size>t)}function T(e,t){if(e.size<=t)return;const i=[...e.values()];do{e.delete(i.shift())}while(e.size>t)}function L(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function _(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const i=Number(t[0]),r=t[1]?Number(t[1]):-1;return{rangeStart:i,rangeEnd:r>=0?r+1:void 0}}function b(e){return e.split("?")[0]}function A(){let e=new Date,t=e.getHours(),i=e.getMinutes(),r=e.getSeconds(),n=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}.${n}`}function I(e){return e&&"function"==typeof e}function R(e,t,i,r,n,s){e.sendPartialBuffer(i,r,{from:n,incompletes:s})&&(r.length<i.attachments?function(e,t,i){e.addStreamListener(i,t.remotePeerId,((e,i,r,n,s)=>{r?t.sendMsgPieceAbort(n,i,!0):t.uploading&&t.send(n),s&&(t.uploading=!1)}))}(t,e,!!i.reverse):e.uploading=!1)}const P=e=>0===p(0,1)?[null,e]:[e,null];function k(e,t,i){return 1===e.length?t.length>=1&&i.length>=1?t[0].weight>i[0].weight?[t[0],e[0]]:[e[0],i[0]]:t.length>=1?[t[0],e[0]]:i.length>=1?[e[0],i[0]]:P(e[0]):[t.length>=1?t[0]:null,i.length>=1?i[0]:null]}function D(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}class w{constructor(e,t){this.target=t,this.type=e}}class C extends w{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class M extends w{constructor(e=1e3,t="",i){super("close",i),this.code=e,this.reason=t,this.wasClean=!0}}const O=()=>{if("undefined"!=typeof WebSocket)return WebSocket},x={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,i={}){this._listeners={error:[],message:[],open:[],close:[]},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._messageQueue=[],this._closeCalled=!1,this._connectLock=!1,this._shouldReconnect=!0,this._retryCount=-1,this._binaryType="blob",this._url=e,this._protocols=t,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect(),this._handleOpen=this._handleOpen.bind(this),this._handleClose=this._handleClose.bind(this),this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this)}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return 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=x.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&this._messageQueue.push(e)}}addEventListener(e,t){this._listeners[e]&&this._listeners[e].push(t)}dispatchEvent(e){const t=this._listeners[e.type];if(t)for(const i of t)this._callEventListener(e,i);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=x.reconnectionDelayGrowFactor,minReconnectionDelay:t=x.minReconnectionDelay,maxReconnectionDelay:i=x.maxReconnectionDelay}=this._options;let r=0;return this._retryCount>0&&(r=t*Math.pow(e,this._retryCount-1),r>i&&(r=i)),r}_wait(){return new Promise((e=>{setTimeout(e,this._getNextDelay())}))}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:e=x.maxRetries,connectionTimeout:t=x.connectionTimeout,WebSocket:i=O()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(r=i)||!r||2!==r.CLOSING)throw Error("No valid WebSocket class provided");var r;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new i(e,this._protocols):new i(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout((()=>this._handleTimeout()),t))})).catch((e=>{this._connectLock=!1,this._handleError(new C(Error(e.message),this))}))}}_handleTimeout(){this._handleError(new C(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new M(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=x.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 N={debug:3,info:4,warn:5,error:6};class B{constructor(e,t,i,r){this.wsAddr=`${e}?app=${t}&id=${i}&v=${r}`,this.destroyed=!1;try{this._ws=this._init()}catch(e){console.error(e)}}_init(){const e={maxRetries:3,minReconnectionDelay:p(5e3,15e3),maxReconnectionDelay:6e5,maxEnqueuedMessages:200};return new F(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const i=N[e];this._ws.send(JSON.stringify({records:[{level:i,text:`${A()}: ${t}`}]}))}sendBatch(e){const t=[];for(let i of e)t.push({level:N[i.levelKey],text:i.message});this._ws.send(JSON.stringify({records:t}))}destroy(){this._ws&&(this._ws.close(1e3),this._ws=null,this.destroyed=!0)}}const U=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}},G=(e,t,i)=>{((e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)})(e,{value:t,duration:i,startTime:Date.now()})},H={debug:0,info:1,warn:2,error:3,none:4};const V=class{constructor(e){this.logLevel=e,this.onlineDebug=!1,this.logCache=[];try{console.debug=console.log}catch(e){console.debug=console.info}"debug"!==e&&"info"!==e||(this.logLevel="error"),U("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:`${A()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,i,r,n=5e3){this.reportUrl&&!this.reporter&&(e&&this.logCache.unshift({levelKey:"info",message:e}),this.reporter=new B(this.reportUrl,t,i,r),this.reporter._ws.addEventListener("open",(()=>{this.reportUrl=void 0,this.reporter.sendBatch(this.logCache),setTimeout((()=>{this.reporter.destroy(),this.reporter=null}),n)}),{once:!0}))}_hookLogFunc(e){for(let t in H){const i=this[t];this[t]=r=>{e(t,r),i(r)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in H)H[e]<H[this.logLevel]?this[e]=d:this[e]=console[e]}get isDebugLevel(){return H[this.logLevel]<=2||this.onlineDebug}};let K;const W="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(K||(K=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),$=65536;function q(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class j extends(s()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||j.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},j.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=m(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void W((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{e.debug=!0,this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var i;!t.address||t.address.endsWith(".local")?(i="Ignoring unsupported ICE candidate.",console.warn(i)):(e.debug=!0,this.destroy(e))}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,W((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,W((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=$),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>$}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=q(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=q(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((i=>{const r=[];i.forEach((e=>{r.push(t(e))})),e(null,r)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((i=>{if(this.destroyed)return;const r=[];i.result().forEach((e=>{const i={};e.names().forEach((t=>{i[t]=e.stat(t)})),i.id=e.id,i.type=e.type,i.timestamp=e.timestamp,r.push(t(i))})),e(null,r)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,i)=>{if(this.destroyed)return;t&&(i=[]);const r={},n={},s={};let a=!1;i.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(r[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}));const o=e=>{a=!0;let t=n[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let i=r[e.remoteCandidateId];i&&(i.ip||i.address)?(this.remoteAddress=i.ip||i.address,this.remotePort=Number(i.port)):i&&i.ipAddress?(this.remoteAddress=i.ipAddress,this.remotePort=Number(i.portNumber)):"string"==typeof e.googRemoteAddress&&(i=e.googRemoteAddress.split(":"),this.remoteAddress=i[0],this.remotePort=Number(i[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(i.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(s).length&&!Object.keys(n).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>$||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()}}j.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},j.channelConfig={};const Y=j;class z{constructor(e,t,i,r,n=0,s=void 0){this.sn=e,this.segId=t,this.data=i,this.fromPeerId=r,this.level=n||0,this.ext=s}static fromSegment(e){const t=new z(e.sn,e.segId,e.data,e.fromPeerId,e.level,e.ext);return t.from=e.from,t}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var X=i(365),Q=i.n(X);class J extends(s()){static get defaultPacketSize(){return u}static get VERSION(){return"8"}constructor(e,t,i,r,n,s={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=n,this.isInitiator=r,this.options=s,this.intermediator=s.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,i),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=u,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.useBackupSignal=!1,this.gotPeersTS=0,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.incomingSignal=[],this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,i){this.remotePeerId=i,this.channelId=this.isInitiator?`${t}-${i}`:`${i}-${t}`,i&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(e.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=g(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:t,sentSignal:i,signalName:r}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${i} signalName ${r}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:i,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,i,r){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${r} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:i,seg_id:r}))))}addStreamListener(e,t,i){this.streamListeners.push({handler:i,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_initPeerChannel(){const t=new Y({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let i=!0;(this.connected||this.notFatalClosed)&&(i=!1);let r=t.message;t.debug&&(r=`${r} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,i,r)})),t.on("signal",(t=>{t.candidate&&!t.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(t),this.sentSignal=!0,this.emit(e.DC_SIGNAL,t))}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.intermediator?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,this.incomingSignal=[],clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:i}=this;if("string"==typeof t){let r=JSON.parse(t);if(!r)return void i.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(r);let n,s=r.event;switch(n=s!==e.DC_PLAYLIST&&s!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${s}`,i.debug(`datachannel receive ${n} from ${this.remotePeerId}`),s){case e.DC_HAVE:if(this.emit(r.event,r),!r.sn)return;this.config.live||(r.sn<this.startSN&&(this.startSN=r.sn),r.sn>this.endSN&&(this.endSN=r.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=g(),this.timeReceivePiece=performance.now(),this.pieceMsg=r,this._prepareForBinary(r.attachments,r.seg_id,r.sn,r.size),this.emit(r.event,r);break;case e.DC_PIECE_CANCEL:i.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(r.event,r),this.sendMsgPieceAbort("transfer canceled",r.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(r.event,r);break;case e.DC_REQUEST:this._handleRequestMsg(r);break;case e.DC_PIECE_ACK:this._handlePieceAck(r.seg_id,r.size,r.miss);break;case e.DC_STATS:this._handleStats(r);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(r);break;case e.DC_METADATA:this._handleMetadata(r);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,r)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:i.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:i.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(r.event,r.fatal||!1);break;default:this.emit(r.event,r)}}else{if(!t)return void i.error("datachannel on data is undefined!");if(!this.downloading){const r=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return i.warn(r),void this.emit(e.DC_ERROR,!1,r)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,i)=>{this.connected&&"disconnected"===t&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(e.DC_DISCONNECT))}))}sendJson(t){if(!this.remotePeerId)return!1;t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const i=JSON.stringify(t);return i.length>u?(this.logger.error("string to send is too large"),!1):this.send(i,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();t?("string"!=typeof t&&(this.bytesUploaded+=t.byteLength),this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,void this.emit(e.DC_ERROR,!1,t.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){const i=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,i)}return!1}sendMsgHave(t,i,r={}){const n=r.reverse||void 0;delete r.reverse,this.sendJson({event:n?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:i,...r})}sendPieceNotFound(t,i,r={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:i||void 0,sn:t,...r})}sendPeers(t){this.sendJson({event:e.DC_PEERS,peers:t})}sendPeersRequest(){this.sendJson({event:e.DC_GET_PEERS})}sendMsgStats(t,i={}){const r={event:e.DC_STATS,total_conns:t,...i};this.sendJson(r)}sendMsgPlaylist(t,i,r){const n=this.playlistMap.get(t);if(n&&n.seq>=r)return;const s={event:e.DC_PLAYLIST,url:t,data:i,seq:r};this.playlistMap.set(t,{data:i,seq:r}),this.sendJson(s)}sendMsgSignal(t,i,r){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:i,data:r})}sendMsgSignalReject(t,i,r,n=!1){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:i,reason:r,fatal:n})}sendMetaData(t,i,r,n,s=!1){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!Q().isMobile(),mobile_net:s,channel:this.channel,version:"2.14.4",sequential:i,peers:r,region:n})}sendPartialBuffer(e,t,i={}){if(!this.sendMsgPiece(e,i))return!1;for(let e=0;e<t.length;e++)this.send(t[e]);return!0}sendMsgPiece(e,t={}){if(!this.uploading)return this.logger.info("not uploading, cancel send buffer"),!1;this.datasToSend=[],this.bytesUploaded=0,e.ext||(e.ext={}),e.ext.from&&t.from&&t.from.length<2500&&(t.from=`${e.ext.from}-${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const i={...e,ext:t};return this.sendJson(i)}sendBuffer(t,i,r,n={}){const s=n.reverse||void 0;if(delete n.reverse,!r)return void this.logger.error("sendBuffer payload is undefined!");let a=r.byteLength,o=0,l=0;a%this.packetSize==0?l=a/this.packetSize:(l=Math.floor(a/this.packetSize)+1,o=a%this.packetSize);let h={event:e.DC_PIECE,attachments:l,seg_id:i,sn:t,level:n.level,size:a,reverse:s};if(delete n.level,!this.sendMsgPiece(h,n))return;const u=function(e,t,i,r){let n=[];if(r){let s;for(let r=0;r<i-1;r++)s=e.slice(r*t,(r+1)*t),n.push(s);s=e.slice(e.byteLength-r,e.byteLength),n.push(s)}else{let r;for(let s=0;s<i;s++)r=e.slice(s*t,(s+1)*t),n.push(r)}return n}(r,this.packetSize,l,o);this._sendBufferArray(u,s),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}requestDataById(t,i,r=!1,n={}){const s={event:e.DC_REQUEST,seg_id:t,sn:i,...n,urgent:r};this.downloading?(this.logger.info(`${this.remotePeerId} add req ${t} in queue`),r?this.sendReqQueue.unshift(s):this.sendReqQueue.push(s)):this._realRequestData(s)}requestDataBySN(t,i=!1,r={}){const n={event:e.DC_REQUEST,sn:t,...r,urgent:i};this.downloading?(this.logger.info(`add req ${t} in queue`),i?this.sendReqQueue.unshift(n):this.sendReqQueue.push(n)):this._realRequestData(n)}_sendBufferArray(e,t=!1){const i=t?e.reverse():e;for(let e=0;e<i.length;e++)this.send(i[e])}_realRequestData(e){this.sendJson(e),this.timeSendRequest=performance.now(),this.downloading=!0,this._loadedBytes=0}shouldWaitForRemain(e){return 0!==this.bufArrSize&&(0!==this.timeReceivePiece&&this.currentLoadSpeed()>=this.minRequiredSpeed(e))}close(t){t||(this.notFatalClosed=!0),this.emit(e.DC_CLOSE,t)}receiveSignal(e,t){if("answer"===e.type){if(this.gotAnswer||this.gotOffer)return;this.gotAnswer=!0}else if("offer"===e.type){if(this.gotOffer||this.gotAnswer)return;this.gotOffer=!0}this.gotSignal=!0,t&&this.incomingSignal.push(t),e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:i}=t;i(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(t=!0){this.logger.info(`destroy datachannel ${this.channelId}`),clearTimeout(this.chokeTimer),clearTimeout(this.connTimeout),this._notifyDownloadListenersAbort("upstream peer is closed");let i={event:e.DC_CLOSE,fatal:t};this.sendJson(i),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:i,reverse:r}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let n=r?this.remainAttachments+1:i-this.remainAttachments;const s=0===this.remainAttachments;if(this.emit(e.DC_PIECE_DATA,this.bufSN,this.segId,t,n,s,this.pieceMsg),this.streamListeners.length>0)for(let e of this.streamListeners){const{handler:i}=e;i(this.bufSN,this.segId,!1,t,s)}if(s){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:e.DC_PIECE_ACK,seg_id:this.segId,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(r)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:i,seq:r}=e;this.playlistMap.set(t,{data:i,seq:r})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const i=this.playlistMap.get(e);return i.seq<=t||i.seq>t+2?null:i}_handleMetadata(t){const{logger:i}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,i.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const r=t.channel;if(this.channel!==r){const t=`peer channel ${r} not matched!`;return i.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){i.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:r}=this.config;if(r&&t.token!==r)return void this.emit(e.DC_ERROR,!0,`super peer token ${t.token} not matched!`)}t.region&&(this.region=t.region);switch(t.platform){case e.DC_PLAT_ANDROID:this.platform=e.DC_PLAT_ANDROID;break;case e.DC_PLAT_IOS:this.platform=e.DC_PLAT_IOS;break;case e.DC_PLAT_WEB:this.platform=e.DC_PLAT_WEB}if(this.mobile=t.mobile||!1,this.mobileNet=t.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===e.DC_PLAT_WEB||!1,this.sequential=t.sequential,i.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,i.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(e.DC_METADATA,t),t.field&&!this.config.live&&t.sequential){const{field:e}=t;if(Array.isArray(e))this._handleField(e);else for(let t in e)this._handleField(e[t])}}_handleField(e){e.forEach((e=>{e>=0&&(e<this.startSN&&(this.startSN=e),e>this.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=g();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPos=e.pos)}_handleRequestMsg(t){if(this.dataExchangeTs=g(),this.uploading)return this.logger.warn(`${this.remotePeerId} is uploading when receive request`),void this.sendPieceNotFound(t.sn,t.seg_id,{level:t.level});this.uploading=!0,this.emit(e.DC_REQUEST,t)}_handlePieceAck(t,i,r){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(i/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),r>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${r}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:i})}_prepareForBinary(e,t,i,r){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=i,this.expectedSize=r}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let i=a.h.concat(this.bufArr);const r=i.byteLength;if(r===this.expectedSize){let t=i.buffer;const r=new z(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,r,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${r}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,i=performance.now()-this.timeSendRequest;if((e||!(i<1e3))&&(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>=3&&!this.choked)){this.choked=!0;const e=30*this.miss;e<=150?(t.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,t.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*e)):t.warn(`datachannel ${this.channelId} is choked permanently`)}}get bufArrSize(){return this.downloading?this.pieceMsg.attachments-this.remainAttachments:0}loadtimeout(){const{logger:e,pieceMsg:t}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded`),this.checkIfNeedChoke(),!0}sendMsgPieceAbort(t,i,r=!1){const n=this.datasToSend.length;if(!r&&!this.uploading&&0===n)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(i,this.bytesUploaded,0),this.bytesUploaded=0;const s={event:e.DC_PIECE_ABORT,reason:`${t}, remains ${n}`};return this.sendJson(s)}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 Z=J,ee={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 te={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class ie extends(s()){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 ee)if(self[t]){e=ee[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,i=()=>{this.curTsUri&&function(e,t,i,r=2e3,n=!1){const s=new XMLHttpRequest;let a=e;return n&&(a=f(e,h,!0)),t=t||"bytes=0-0",new Promise(((n,o)=>{s.open("GET",a,!0),s.responseType="arraybuffer",s.timeout=r,s.onreadystatechange=e=>{if(4===s.readyState){const e=s.status;206===e||200===e&&t?n(s.response):o(`status ${e} url ${a} range ${t}`)}},s.onerror=e=>{o("request error")},s.ontimeout=e=>{o("timeout")},s.setRequestHeader("Range",t),i&&i(s,e),s.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((r=>{e.httpRangeSupported=!1,t.warn(r),this.rangeRequestTimer=setTimeout(i,6e4)})).finally((()=>{t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(i,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 V(e.logLevel);return e.logger=this.logger=t,t}getExtraForStats(){return{}}getExtraForPeersRequest(){const e={};return e.num_want=this._getNumWant(),e}_getNumWant(){const{tracker:e}=this;if(!e.scheduler)return;const t=e.scheduler.peersNum;return t>0&&e.maxConnsActive-t>0?e.maxConnsActive-t:void 0}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return I(t)?(i,r)=>`${e}-${t(i,r)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,i=`wss://${self.atob(function(e){let t="c2lnbmFsY2xvdWQuc3dhcm1jbG91ZC5vcmc=";switch(e){case"hk":t="c2lnbmFsLnN3YXJtY2xvdWQub3Jn";break;case"us":t="b3BlbnNpZ25hbC5zd2FybWNsb3VkLm9yZw==";break;case"cn":t="Z3ouc3dhcm1jbG91ZC5uZXQ="}return t}(t.trackerZone))}`;t.signalConfig&&(t.wsSignalerAddr=t.signalConfig);const{wsSignalerAddr:r}=t;if(r){let n;"object"==typeof r?(r.main||(r.main=i),n=r.main):"string"==typeof r&&(n=r,t.wsSignalerAddr={main:n}),n===i&&(n=void 0),n&&!t.wsSignalerAddr.backup&&(e=l().parseURL(n).netLoc.substring(2))}else t.wsSignalerAddr={main:i,byDefault:!0};return e}get commonBrowserInfo(){const e=Q().getPlatform(),t=Q().getNetType()||"wifi";this.netType=t;const{main:i,backup:r,byDefault:n}=this.config.wsSignalerAddr||{};return{signal:i,custom_signal:!n||void 0,signal2:r,device:e,netType:t,player:this.playerName}}get isMobileNet(){return"wifi"!==this.netType&&"ethernet"!==this.netType}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",i=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,i)};e?self.removeEventListener(t,i):self.addEventListener(t,i)}destroy(){clearTimeout(this.rangeRequestTimer),this.disableP2P(!0),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return ie.version}static isSupported(){const e=m();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,i){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${i}`);let r=4;return t<=2?r=1.5:t<=3?r=2:t<=4?r=2.5:t<=5?r=3:t<=6&&(r=3.5),r}emitEvent(e,...t){this.emit(e,...t);const i=te[e];i&&I(this.config[i])&&this.config[i](...t)}}ie.version="2.14.4",ie.protocolVersion=Z.VERSION;const re=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 se(e,t){let i;if(e&&("string"==typeof e?(i=document.querySelector(e),ae(i)||(i=function(e){const t=document.getElementById(e);if(ae(t))return t;if(!t)return null;const i=t.getElementsByTagName("*");for(let e=0;e<i.length;e++)if(ae(i[e]))return i[e];return null}(e))):e instanceof HTMLMediaElement&&(i=e)),!i){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?i=e[0]:(t&&(i=e.find((e=>e.src===t))),i||(i=e.find((e=>e.currentTime>0))))}return i}function ae(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function oe(e,t,i,r=0,n=0){const s=u;let a=r,o=n||i-1;const l=Math.floor(i/s),h=i%s>0?l+1:l;if(e>=0&&(a+=(e+1)*s),t>=0&&t<h){o-=i%s+(h-t-1)*s}return{rangeStart:a,rangeEnd:o+1}}function le(e,t){return`${e}-${t}`}function he(e,t,i,r){let n=i.split("?")[0];return n.startsWith("http")&&(n=n.split("://")[1]),r?`${n}|${r}`:`${n}`}function ue(e,t){return"number"!=typeof t&&(t=Number(t)),`${t}-${e}`}let de={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,i){},getPeerId:function(e){},getPeersInfo:function(e){}};const ce={...de,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},fe=1e3;function ge(e){const t=new Promise(((t,i)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>i(e.error)})),i=(r=fe,n="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(n)}),r))));var r,n;return Promise.race([t,i])}const pe={};async function ve(e,t,i=!0){const r=pe[e]||{};r.promise||(r.promise=new Promise((e=>r.resolve=e)),pe[e]=r,ye(e,t,r.resolve,i));const n=await r.promise;return delete r.promise,n}const me={};async function ye(e,t,i,r){if(!me[e]){const r=indexedDB.open(e);return r.onupgradeneeded=()=>{const e=r.result;t.forEach((t=>{e.createObjectStore(t)}))},void i(me[e]=await ge(r))}if(r)try{t.forEach((t=>{me[e].transaction(t)})),i(me[e])}catch(n){console.error(`Could not open a transaction on "${e}" due to ${n.name} (${n.message}). Trying to reopen the connection...`),delete me[e],ye(e,t,i,r)}else i(me[e])}let Ee;function Se(){return Ee||(Ee=createStore("keyval-store","keyval")),Ee}function Te(e,t=Se()){return t("readonly",(t=>ge(t.get(e))))}function Le(e,t,i=Se()){return i("readwrite",(i=>(i.put(t,e),ge(i.transaction))))}function _e(e,t=Se()){return t("readwrite",(t=>(t.delete(e),ge(t.transaction))))}function be(e=Se()){return e("readwrite",(e=>(e.clear(),ge(e.transaction))))}function Ae(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},ge(e.transaction)}const Ie="size";class Re extends(s()){constructor(e,t){super(),this.name="SegmentStore",this.logger=t.logger,this.logger.info(`use ${this.name}`),this.engine=e,this.channel=e.channel;const i=e.browserInfo.device;this.isPC=i===Q().device.PC_WEB||i===Q().device.PC_NATIVE,this.maxBufSize=this.isPC?t.diskCacheLimit.pc:t.diskCacheLimit.mobile,this.overflowed=!1,this.countErrors=0,this.isCleared=!0,this.destroyed=!1}async setupStore(){if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate(),t=Math.floor(e.quota-e.usage);t<this.maxBufSize&&(this.maxBufSize=t-104857600)}return new Promise((async(e,t)=>{if(this.isPC&&this.maxBufSize<419430400||!this.isPC&&this.maxBufSize<104857600)return void t("disk storage not enough");const i=this.stores;let r;try{r=function(e,t){let i=ve(e,t);return t.map((r=>(n,s)=>i.then((a=>{try{const e=a.transaction(r,n).objectStore(r);return s(e)}catch(a){i=ve(e,t),i.then((e=>s(e.transaction(r,n).objectStore(r))))}}))))}(this.channel,i)}catch(e){return void t(e)}this._createStores(r),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return Le(Ie,0,this.metaStore)}currBufSize(){return new Promise((async(t,i)=>{try{const r=await Te(Ie,this.metaStore);if(isNaN(r))return this.engine.emit(e.BM_FATAL_ERROR),void i("size is NaN");t(r)}catch(e){i(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:i}=this;if(L(t.data))return new Promise((r=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),this.countErrors=0,r()})).catch((e=>{this._handleFataError(),e&&(i.warn(`putSeg ${e}`),("QuotaExceededError"===e.name||e.inner&&"QuotaExceededError"===e.inner.name)&&this.currBufSize().then((e=>{this._trimDisk(e,!0)})).catch((e=>{this.logger.error(`trimDisk ${e}`)}))),r()}))}));i.error(`putSeg ${t.segId} is not buffer`)}_handleFataError(){this.countErrors++,this.countErrors>=3&&(this.engine.emit(e.BM_FATAL_ERROR),this.countErrors=0)}_decreaseBufSize(e){this.currBufSize().then((t=>{t&&Le(Ie,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(e){this.destroyed||this.currBufSize().then((t=>{Le(Ie,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){be(this.segmentsStore),e?this._initMetaStore():be(this.metaStore),this.overflowed=!1}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const Pe=Re;const ke=class extends Pe{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 Te(e,this.id2SnStore)}catch(e){return Promise.resolve(!1)}return new Promise((i=>{void 0!==t?Te(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?i(!0):i(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),i(!1)})):i(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let i;try{i=await Te(e,this.id2SnStore)}catch(e){return null}return new Promise((r=>{void 0!==i?Te(i,this.segmentsStore).then((i=>{if(this.countErrors=0,i&&i.length>0){const n=i.find((t=>t.segId===e));if(!n)return void r(null);if(!L(n.data))return t.error(`getSegById ${n.sn} is not buffer`),void r(null);r(z.fromSegment(n))}else r(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),r(null)})):r(null)}))}getSegIdBySN(e){return new Promise((t=>{Te(e,this.segmentsStore).then((e=>{e&&e.length>0?t(e[0].segId):t(null)})).catch((e=>{this.logger.warn(`getSegIdBySN ${e}`),t(null)}))}))}_addSeg(e){const{segId:t,sn:i,size:r}=e;return Le(t,i,this.id2SnStore),new Promise(((n,s)=>{Te(i,this.segmentsStore).then((a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(this._segmentToCache(e)),Le(i,a,this.segmentsStore).then((()=>{this._increaseBufSize(r),n(e)})).catch((e=>{s(e)}))):n(e):Le(i,[this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(r),n(e)})).catch((e=>{s(e)}))})).catch((e=>{s(e)}))}))}async _trimDisk(t,i=!1){if(this.isCleared||this.destroyed)return;let r=this.maxBufSize;const{logger:n}=this;i&&(r=t-104857600,r<0&&(r=0)),t<r||(n.warn(`_trimDisk currentSize ${t} upBound ${r}`),function(e=Se()){return e("readonly",(e=>{if(e.getAllKeys)return ge(e.getAllKeys());const t=[];return Ae(e,(e=>t.push(e.key))).then((()=>t))}))}(this.segmentsStore).then((async i=>{const s=i.sort(((e,t)=>e-t));let a=0;do{if(a++>10){n.warn("too much loops in SegmentStore");break}const i=s.shift();if(void 0===i){n.warn("lastSN not found");continue}if(i>=this.loadingSN){n.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const r=s[0],o=await Te(i,this.segmentsStore);if(!o){n.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),_e(i,this.segmentsStore).then((()=>{this._decreaseBufSize(parseInt(l))})),o.forEach((t=>{_e(t.segId,this.id2SnStore),n.info(`pop seg ${t.segId} size ${t.data.byteLength}`),this.emit(e.BM_LOST,{sn:i,segId:t.segId,next:r,level:t.level})})),t-=l,n.info(`pop sn ${i} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=r)})))}_segmentToCache(e){return{data:e.data,level:e.level,segId:e.segId,sn:e.sn,fromPeerId:e.fromPeerId}}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}be(this.id2SnStore).catch((e=>{}))}};class De extends(s()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const i=e.browserInfo.device;if(this.maxBufSize=i===Q().device.PC_WEB||i===Q().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)),L(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 we=De;const Ce=class extends we{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,i)=>{const r=this.id2Sn.get(e);this._segPool.has(r)?t(this._segPool.get(r).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((i,r)=>{if(!this._segPool.has(t))return void i(null);i(this._segPool.get(t).find((t=>t.segId===e)))}))}getSegIdBySN(e){return new Promise(((t,i)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}_addSeg(t){const{logger:i}=this,{segId:r,sn:n,size:s}=t;if(this.id2Sn.set(r,n),this._segPool.has(n)){this._segPool.get(n).push(t)}else this._segPool.set(n,[t]);this._currBufSize+=parseInt(s);const a=this._segPool.size;if(this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t),this._currBufSize<this.maxBufSize||a<=5)return;let o=Array.from(this._segPool.keys());this.isLive||(o=o.sort(((e,t)=>e-t)));let l=0;do{if(l++>10){i.error("too much loops in SegmentCache");break}const t=o.shift();if(void 0===t){i.error("lastSN not found");continue}const r=o[0],n=this._segPool.get(t);if(!n){i.error("lastSeg not found");continue}let s=0;n.forEach((e=>{s+=e.size})),this._currBufSize-=parseInt(s),this._segPool.delete(t),n.forEach((i=>{this.id2Sn.delete(i.segId),this.emit(e.BM_LOST,{sn:t,segId:i.segId,next:r,level:i.level})})),i.info(`pop sn ${t} size ${s} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>5)}clear(){super.clear(),this.id2Sn.clear()}};var Me=i(832),Oe=i.n(Me);function xe(e,t){for(const i in t)Object.defineProperty(e,i,{value:t[i],enumerable:!0,configurable:!0});return e}const Fe=function(e,t,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof t&&(i=t,t=void 0),null!=t&&(i.code=t);try{return xe(e,i)}catch(t){i.message=e.message,i.stack=e.stack;const r=function(){};return r.prototype=Object.create(Object.getPrototypeOf(e)),xe(new r,i)}};class Ne{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 Be="SW_GEOIP_KEY",Ue=2592e5,Ge=432e5,He="TRACKER_EXPT",Ve="IPAPI_ERROR",Ke="uY2R",We="LmNv",$e="uYnll",qe="bQ==",je="Z3o",Ye="aGsuc3d",ze="hcm1j",Xe="bG91ZC",Qe="5uZXQ=",Je=Symbol("httpDownloaded"),Ze=Symbol("p2pDownloaded"),et=Symbol("p2pUploaded");class tt extends(s()){constructor(e,t,i,r,n){let s;super(),this.config=e.config;let a=this.config.announceLocation;switch(this.config.trackerZone&&(a=this.config.trackerZone),a){case"hk":s=Ye+ze+Xe+Qe;break;case"us":s="dXMuaGR0dmNsb3VkLmNvbQ==";break;case"cn":s=je+Ke+$e+We+qe;break;default:s="ZXUuaGR0dmNsb3VkLmNvbQ=="}this.engine=e,this.key=t||void 0,Array.isArray(r)&&(r=r[Math.floor(Math.random()*r.length)]),this.baseUrl=r||`https://${self.atob(s)}/v1`,this.channelId=self.btoa(i),this.timestamp=g(),this.health=new Ne;const o=l().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,""),function(e,t){function i(e,t,i,r,n){return h(i-219,n)}var r,n,s=e();function a(e,t,i,r,n){return h(n- -994,e)}function o(e,t,i,r,n){return h(r-233,t)}function l(e,t,i,r,n){return h(n-305,i)}for(;;)try{if(156690===-parseInt(o(0,246,0,247))/1*(-parseInt(o(0,243,0,248))/2)+-parseInt(o(0,238,0,245))/3+parseInt(a(-1e3,0,0,0,-989))/4*(-parseInt(i(0,0,225,0,216))/5)+-parseInt((r=-180,n=-173,h(n- -181,r)))/6*(parseInt(l(0,0,324,0,324))/7)+-parseInt(a(-991,0,0,0,-990))/8*(parseInt(l(0,0,313,0,307))/9)+-parseInt(l(0,0,310,0,305))/10+-parseInt(a(-968,0,0,0,-974))/11*(-parseInt(i(0,0,226,0,216))/12))break;s.push(s.shift())}catch(e){s.push(s.shift())}}(d);function h(e,t){var i=d();return(h=function(e,t){return i[e-=0]})(e,t)}const u=function(e,t,i,r,n,s){let a=location.hostname;a===h(-922- -923,-915)&&s&&(a=s+"."+a);return 13,Oe()(a+"2.14.4"+i+r+n,e).substr(0,8)}(this.timestamp,0,this.announce,this.channelId,n.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=!(!n.bundle||!window.electron&&!navigator.userAgent.toLowerCase().includes("electron")),this.announceInfo={...n,channel:this.channelId,ts:this.timestamp,version:"2.14.4",v:u,announce:this.announce,k:st(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[Je]=0,this[Ze]=0,this[et]=0,this.speed=0,this.offline=!1,this.errsBufStalled=0,this.mediaRequests=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,i)=>{if((e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return!(!e.duration||!e.startTime)&&Date.now()-e.startTime<e.duration}catch(e){return!1}})(Be)){const i=U(Be);e.info("found local geo data"),t(i)}else fetch(self.atob("aHR0cHM6Ly9wcm8uaXAtYXBpLmNvbS9qc29uP2ZpZWxkcz0yMTgxODI2JmtleT1YT3BpYW5zUmdZeEdUaG8=")).then((e=>e.json())).then((e=>{if("success"!==e.status){const t=new Error(`preflight status ${e.status}`);throw Fe(t,Ve)}{const i=e.mobile?Ge:Ue;G(Be,e,i),t(e)}})).catch((e=>{i(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(Fe(new Error("request timeout"),Ve))}),600)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(t.code!==He){const t=U(Be);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:i,isp:r,as:n,mobile:s,countryCode:a,continentCode:o}=e;s&&(this.announceInfo.netType="cellular");const l=n.split(" ")[0].substr(2);this.announceInfo={...this.announceInfo,lat:t,lon:i,isp:r,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,i)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>{if(!e.ok){const t=e.status>=500&&e.status<600;throw 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 i=e.data;if(i.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:i}=e.data;throw Fe(new Error(i),He,{retry:t>=5e3})}if(i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),i.min_conns||(i.min_conns=8),(!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval&&i.peers){if(this.peerId=this.id=i.id,i.report_interval<20&&(i.report_interval=20),this.btStats(i.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,!this.announceInfo.asn&&i.asn){const{country:e,asn:t,mobile:r,isp:n,lat:s,lon:a}=i;this.announceInfo={...this.announceInfo,country:e,asn:t},G(Be,{countryCode:e,as:`AS${t}`,mobile:r,isp:n,lat:s,lon:a,status:"success"},r?Ge:Ue)}t(i)}else this.engine&&(this.engine.p2pEnabled=!1)})).catch((t=>{e.error(`btAnnounce error ${t}`);const r=t.code||He,n=!t.code||t.retry;i(Fe(t,r,{retry:n}))}))}))}btStats(e=10){this.heartbeater=setInterval((()=>{this.postStats()}),1e3*e)}postStatsWithBeacon(){if(this.offline)return;this.offline=!0;let e={off:!0};this.statsRequesting||(e={...e,...this._makeStatsBody()}),this.statsURL&&navigator.sendBeacon&&navigator.sendBeacon(this.statsURL,JSON.stringify(e))}postStats(){const{logger:t}=this.engine;this.statsRequesting=!0,fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.statsRequesting=!1,this.reportFails=0,e.text()))).then((i=>{let r;if(r=i?JSON.parse(i):{ret:0,data:{}},-1===r.ret)clearInterval(this.heartbeater),t.error(`${r.data.msg} code ${r.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:i=0,failConns:r=0,rebuffers:n=0,requests:s=0,errsInternalExpt:a=0}=this.lastStats||{};this[Je]>=e&&(this[Je]-=e),this[Ze]>=t&&(this[Ze]-=t),this[et]>=i&&(this[et]-=i),this.failConns>=r&&(this.failConns-=r),this.errsBufStalled>=n&&(this.errsBufStalled-=n),this.mediaRequests>=s&&(this.mediaRequests-=s),this.errsInternalExpt>=a&&(this.errsInternalExpt-=a),this.exptMsg&&(this.exptMsg=void 0)}})).catch((e=>{t.error(`btStats error ${e}`),this.statsRequesting=!1,this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e,t=!1){const{logger:i}=this.engine,{asn:r,country:n}=this.announceInfo;let s={exclusions:e,asn:r,country:n,ratio:this.health.healthRatio,urgent:t||void 0},a={};return this.engine.getExtraForPeersRequest&&(a=this.engine.getExtraForPeersRequest()),s=Object.assign({},s,a),new Promise(((e,t)=>{this.reportFails>=3?t(new Error("reportFails >= 3")):fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(s)}).then((e=>e.json())).then((i=>{-1===i.ret?t(i.data.msg):e(i.data)})).catch((e=>{i.error(`btGetPeers error ${e}`),t(e)})).finally((()=>{this.health.resetTraffic()}))}))}increFailConns(){this.failConns++}increRebuffers(){this.engine.emitEvent("bufferStalled"),this.errsBufStalled++}increMediaRequests(){this.mediaRequests++,this.engine.emit(e.MEDIA_REBUFFER,this.errsBufStalled>=2)}reportFlow(e){const t=Math.round(e/1024);this.engine.emitEvent("httpDownloaded",t),this[Je]+=t,this.totalHTTPDownloaded+=t,this.health.recordHttp(t),this._emitStats()}reportDCTraffic(e,t){const i=Math.round(e/1024);this[Ze]+=i,this.totalP2PDownloaded+=i,this.health.recordP2p(i),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",i,this.speed),this._emitStats()}reportUploaded(e=0){const t=Math.round(e/1024);this.engine.emitEvent("p2pUploaded",t),this.totalP2PUploaded+=t,this.health.recordShare(t),this[et]+=t,this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),this.removeAllListeners(),clearInterval(this.heartbeater)}_emitStats(){const{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:i}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:i,p2pDownloadSpeed:this.speed});const{getStats:r}=this.config;I(r)&&r(t,i,e,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let i={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,rebuffers:this.errsBufStalled||void 0,requests:this.mediaRequests||void 0,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[Je])||0,p2p:Math.round(this[Ze])||0,share:Math.round(this[et])||0,asn:e,country:t},r={};this.engine.getExtraForStats&&(r=this.engine.getExtraForStats()),i=Object.assign({},i,r),this.lastStats=JSON.parse(JSON.stringify(i)),Object.keys(i).forEach((e=>{0===i[e]&&delete i[e]}));const{logger:n}=this.engine;return n.isDebugLevel&&n.info(`report ${JSON.stringify(i)}`),this.exptMsg&&(i.exptMsg="2.14.4 "+this.exptMsg),i}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":st(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const it=tt;function rt(e,t){const i=nt();return(rt=function(e,t){return i[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 st(e){if(!e)return;const t=rt(-822- -830,-826);let i="".split("").reverse().join("");const r=t.length;for(let n=0;n<e.length;n++){const s=e.charCodeAt(n)^t.charCodeAt(n%r);i+=String.fromCharCode(s)}return self.btoa(i)}!function(e,t){const i=e();function r(e,t,i,r,n){return rt(e-92,n)}function n(e,t,i,r,n){return rt(n-930,i)}for(;;)try{if(377468===parseInt(n(0,0,944,0,939))/1*(parseInt(n(0,0,936,0,930))/2)+parseInt(n(0,0,929,0,935))/3+parseInt(n(0,0,939,0,941))/4+-parseInt((s=-995,a=-995,rt(s- -999,a)))/5+parseInt(r(94,0,0,0,91))/6+-parseInt(r(93,0,0,0,92))/7+-parseInt(r(102,0,0,0,107))/8)break;i.push(i.shift())}catch(e){i.push(i.shift())}var s,a}(nt);class at extends(s()){constructor(e,t){super(),this.logger=e,t.startsWith("wss")?this.addr=t.replace("wss","https"):t.startsWith("ws")&&(this.addr=t.replace("ws","http")),this.connected=!1,this.retryCount=0,this.closed=!1,this.msgQueue=[],this.posting=!1,this.pollingTs=0}start(){this.closed=!1,this._hello((()=>{this._longPolling()}))}_hello(e){fetch(this.addr+"&hello",{method:"POST"}).then((e=>{if(!e.ok)throw new Error("hello response was not ok");return e.json()})).then((t=>{this.connected=!0,e(),this.onopen&&this.onopen(t.ver)})).catch((e=>{this.closed=!0,this.onerror&&this.onerror(e)}))}send(e){this.msgQueue.push(e),this.posting||this._realSend([...this.msgQueue])}_realSend(e){0!==e.length&&(this.posting=!0,this.msgQueue=[],fetch(this.addr,{method:"POST",body:JSON.stringify(e)}).then((()=>{this.posting=!1,this.msgQueue.length>0&&this._realSend([...this.msgQueue])})).catch((e=>{this.logger.error(e),this.posting=!1})))}close(){this.connected&&(this.closed=!0,this.connected=!1,this.abortController&&(this.abortController.abort(),this.abortController=null),this.onclose&&this.onclose())}destroy(){this.close(),this.removeAllListeners()}_longPolling(){if(this.closed)return;this.pollingTs=g(),this.abortController=new AbortController;const e=this.abortController.signal;fetch(this.addr,{signal:e}).then((e=>{if(!e.ok)throw new Error("polling response was not ok");return e.text()})).then((async e=>{e&&this.onmessage&&this.onmessage(JSON.parse(e)),this.retryCount=0;const t=g()-this.pollingTs;JSON.stringify(e)===JSON.stringify(this.lastData)&&t<10&&(this.logger.warn(`wait ${10-t}s for next polling`),await v(1e3*(10-t))),this.lastData=e,this._longPolling()})).catch((e=>{this.connected&&(this.retryCount<=3?(this.retryCount++,this._longPolling()):(this.connected=!1,this.onerror&&this.onerror(e)))}))}}const ot=class{constructor(e,t,i,r="main"){this.logger=e,this.config=t,this.wsAddr=i,this.serverVersion=0,this.pingInterval=95e3,this.name=r,this.normalClosed=!1,this.lastSendTs=performance.now(),this.pollingClient=new at(e,i);try{this._ws=this._init()}catch(t){e.error(t),this._startPolling()}}get batchSupported(){return this.serverVersion>=50}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:p(15e3,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20,connectionTimeout:7e3};let t=new 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 i=JSON.stringify(e);t.push(i)},t.addEventListener("message",(e=>{let t=e.data;const i=JSON.parse(t),r=i.action;if("pong"!==r){if("ver"!==r)return"close"===r?(this.logger.warn(`server close signal ${this.name} reason ${i.reason}`),void this.close()):void(this.onmessage&&this.onmessage(i,this.name));this.serverVersion=i.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),e.code>=5e3||e.code<4e3?(this.onclose&&this.onclose(),this._stopPing()):this.close()})),t.addEventListener("error",(e=>{this._stopPing(),this.onerror&&this.onerror(e),this._startPolling()})),t}forcePolling(){this.pollingClient.connected||(this.close(),this.pollingClient=new at(this.logger,this.wsAddr),this._startPolling())}_startPolling(){this.pollingClient.connected||(this.logger.info(`${this.name} start polling`),this.pollingClient.start(),this._setupPolling(this.pollingClient))}sendDebug(e,t,i){this._send({action:"debug",details:t,ping:i||void 0,to:e})}sendSignal(e,t){const i={action:"signal",to:e,data:t};this._send(i)}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let i of t)this.sendSignal(e,i)}sendReject(e,t,i){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const r={action:"reject",to:e,reason:t,fatal:i};this._send(r)}_send(e){this.pollingClient.connected?this.pollingClient.send(e):this._ws&&this._ws.send(e)}_startPing(e){this.connected&&(this.pingTimer=setTimeout((()=>{const e=95e3-(performance.now()-this.lastSendTs);if(e>=0)return this._startPing(e);const t={action:"ping"};this._ws&&this._ws.push(JSON.stringify(t)),this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),15e3),this._startPing(this.pingInterval)}),e))}_stopPing(){clearTimeout(this.pingTimer),clearTimeout(this.pongTimer)}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3)})(),this.pollingClient.close(),this.normalClosed=!0}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.pollingClient.destroy()}get connected(){return!!this.pollingClient.connected||this._connected}get _connected(){return!!this._ws&&this._ws.readyState===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)}}},lt=class{constructor(e,t,i,r){this.logger=e,this.config=t,this.mainAddr=i,this.backupAddr=r,this.mainWS=this._init(i),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(r,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let i=new ot(this.logger,this.config,e,t);return i.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},i.onmessage=e=>{this.onmessage&&this.onmessage(e,i.name)},i.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},i.onerror=e=>{this.onerror&&this.onerror(e)},i}sendSignalBatch(e,t,i){if(i){const r=this._getWSByName(i);r&&r.sendSignalBatch(e,t)}else this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected&&this.backupWS.sendSignalBatch(e,t)}sendSignal(e,t,i){this.sendSignalBatch(e,[t],i)}sendReject(e,t,i,r){if(r){const n=this._getWSByName(r);if(n)return void n.sendReject(e,t,i)}this.mainConnected?this.mainWS.sendReject(e,t,i):this.backupConnected?this.backupWS.sendReject(e,t,i):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,i){this.mainConnected&&this.mainWS.sendDebug(e,t,i)}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close(),this.normalClosed=!0}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(e){this.mainWS&&"backup"!==e&&this.mainWS.reconnect(),this.backupWS&&"main"!==e&&this.backupWS.reconnect()}forcePolling(e){this.mainWS&&"backup"!==e&&this.mainWS.forcePolling(),this.backupWS&&"main"!==e&&this.backupWS.forcePolling()}destroy(){this.close(),clearTimeout(this.backupTimer),this.mainWS=null,this.backupWS=null,this.destroyed=!0}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}};const ht=function(e,t,i=40){var r=null,n=!1,s=i;return function(i=!1){if(i)return clearTimeout(r),void(n=!1);n||(n=!0,r=setTimeout((function(){e.call(t,s),n=!1,r=null}),1e3*s),s*=1.1)}};class ut{constructor(e,t,i=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=i,this.pool=[],t.ICEPreflight&&this.reset(),this.trickle=!1}reset(){this.destroy();for(let e=0;e<this.poolSize;e++)this.pool.push(this._createPeer())}_createPeer(){return new Z(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 dt=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,i=0,r="";for(const n of e){if("="===n)break;const e=this.CHARSET.indexOf(n);for(t=t<<this.BITS_PER_BASE64_CHAR|e,i+=this.BITS_PER_BASE64_CHAR;i>=this.BITS_PER_BYTE;){i-=this.BITS_PER_BYTE;r+=(t>>i&(1<<this.BITS_PER_BYTE)-1).toString(16).padStart(2,"0").toUpperCase()}}let n="";for(let e=0;e<r.length;e++)n+=r[e],e%2==1&&e!==r.length-1&&(n+=":");return n}},ct="typ host",ft="generation 0",gt="network-cost",pt="rport",vt="0.0.0.0",mt={V:"v=",O:"o=",S:"s=",C:"c=",A:"a=",M:"m=",T:"t="},yt={U:"ice-ufrag:",P:"ice-pwd:",F:"fingerprint:",C:"candidate:",S:"sctp-port:",M:"max-message-size:"},Et={1:"sha-1",2:"sha-224",3:"sha-256",4:"sha-384",5:"sha-512",6:"md5",7:"md2",8:"token"},St={P:`${ct} ${ft} ${gt} 999`,W:`${pt} 0 ${ft} ${gt} 999`,H:ct,S:"typ srflx",R:pt,A:"raddr",V:vt,F:"ufrag",G:`${pt} 0 ${ft}`,N:gt,E:"network-id",C:"tcptype active",Q:`${ft}`,U:"udp",T:"tcp"},Tt={P:"application",U:"UDP/DTLS/SCTP",S:"DTLS/SCTP",D:"webrtc-datachannel"},Lt={4:"IP4",6:"IP6"},_t={0:vt},bt=e=>(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in St&&(e=St[e]),e))).join(" "));function At(e,t){let i=e.split("~"),r=[];i=i.map((e=>{let t=e.slice(0,1),i=e.slice(1);if(t in mt&&(t=mt[t]),"a="===t){let e=i.slice(0,1);const t=i.slice(1);e in yt&&(e=yt[e],i=e+t)}return t+i})),r.push("v=0"),r.push("s=-"),r.push("t=0 0"),r.push("a=msid-semantic: WMS");let n=0;i.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),i=[];i.push("-");const n=t.shift();if(n&&i.push(n),0===t.length)i.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&i.push(e),0===t.length)i.push("IN IP4 127.0.0.1");else{i.push("IN");const e=t.shift();e&&i.push(e);const r=t.shift();r&&i.push(r)}}r.splice(1,0,`o=${i.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(It,(e=>Tt[e]))}(e),r.push(e),r.push("a=setup:"+(t?"actpass":"active")),r.push(`a=mid:${n}`),void n++;if(e.startsWith("a=candidate:"))return e=bt(e),void r.push(e);if(e.startsWith("a=fingerprint:")){let[t,i]=e.slice(14).split(" ");return t in Et&&(t=Et[t]),i=dt.decode(i),void r.push(`a=fingerprint:${t} ${i}`)}if(e.startsWith("c=")){let[t,i]=e.slice(2).split(" ");return t in Lt&&(t=Lt[t]),i in _t&&(i=_t[i]),void r.push(`c=IN ${t} ${i}`)}"I"!==e?"Z"!==e?"B"!==e?r.push(e):r.push("a=sendrecv"):r.push("a=ice-options:ice2,trickle"):r.push("a=ice-options:trickle")}}));const s=r.length-1;return r.splice(s,0,`a=group:BUNDLE ${Array.from(Array(n).keys()).join(" ")}`),r.join("\r\n")}const It=new RegExp(Object.keys(Tt).join("|"),"g");class Rt extends(s()){constructor(e,t,i,r){super(),this.engine=e,this.logger=e.logger,this.config=r,this.connected=!1,this.scheduler=i,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set;const n=Q().isMobile();this.peerPool=new ut(e,r,15),this.signalerWs=null,this.fetcher=t,this.peers=[],this.requestPeersQueue=[],this.minConns=5,this.stuns=[],this.requestMorePeers=ht(this._requestMorePeers,this,p(35,45)),this.maxConns=n?15:22,this.maxConnsActive=n?10:13,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.requestPeersWaitCount=0,this.gotSignalFails={main:0,backup:0,limit:5},this.fuseRate=-1,this.overloaded=!1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:t,config:i,fetcher:r}=this,{btAnnounce:n,btAnnouncePreflight:s}=r,{wsSignalerAddr:a,wifiOnly:o,geoIpPreflight:l}=i;(l?s:n).call(r).then((e=>{const{scheduler:i}=this;if(!i)return;t.peerId=this.peerId=e.id,this.minConns=e.min_conns,i.minConns=this.minConns;const n=e.peers;i.notifyPeersLoaded(n.length),n.length>this.gotSignalFails.limit&&(this.gotSignalFails.limit=n.length),t.netType=r.announceInfo.netType,(e.wifi_only||o)&&t.isMobileNet&&(i.downloadOnly=!0,this.logger.info("downloadOnly mode"));const s=a.main;let l=a.backup;function h(e,t){var i=u();return(h=function(e,t){return i[e-=0]})(e,t)}function u(){var e=["IHmzPt4745802".split("").reverse().join(""),"fqbpvJ65672".split("").reverse().join(""),"peerId","evitcAsnnoCxam".split("").reverse().join(""),"0r^EeI@*KS".split("").reverse().join(""),"yGChQi82100203".split("").reverse().join(""),"dIlennahc".split("").reverse().join(""),"qrZmAF0973735".split("").reverse().join(""),"qNTzkD6562665".split("").reverse().join(""),"timestamp","HaovMZ5303011".split("").reverse().join(""),"blnwIB1433257".split("").reverse().join(""),"39zAjEpC","substring"];return(u=function(){return e})()}var d,c;e.signal&&!e.signal2&&(l=void 0),this.signalerWs=this._initSignalerWs(e.signal||s,e.signal2||l,e.token,e.token2),0===n.length?this.requestMorePeers():this.peers=this._filterPeers(n),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 B(e.log_url,this.fetcher.key||location.hostname,this.peerId,"2.14.4"),this.logger.setUploader(this.logUploader))),t.onTrackerResume&&t.onTrackerResume(e),e.fuse_rate&&(this.fuseRate=e.fuse_rate),e.overload&&(this.overloaded=!0,this.logger.warn("server overloaded, degrade signaling")),this.logger.info(`announce request response ${JSON.stringify(e,null,2)}`),function(e,t){function i(e,t,i,r,n){return h(t- -94,n)}var r=e();function n(e,t,i,r,n){return h(t-586,i)}function s(e,t,i,r,n){return h(r-742,n)}for(;;)try{if(595581===-parseInt(i(0,-83,0,0,-88))/1+-parseInt(n(0,587,588))/2+parseInt(n(0,599,592))/3*(-parseInt(n(0,588,591))/4)+parseInt(i(0,-86,0,0,-83))/5+-parseInt(s(0,0,0,751,751))/6+-parseInt(s(0,0,0,754,760))/7+parseInt(h(403-397,399))/8)break;r.push(r.shift())}catch(e){r.push(r.shift())}}(u),e.v!==Oe()(r.channelId+this.peerId+r.timestamp+(d=701,c=702,h(d-696,c)),"2.14.4").substring(0,8)&&(this.maxConnsActive=1)})).catch((i=>{if(this.scheduler&&("TRACKER_EXPT"===i.code&&t.emitEvent(e.EXCEPTION,i),this.scheduler.notifyPeersLoaded(0),i.retry)){const e=p(15e3,4e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.postStatsWithBeacon(),this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.peerPool.destroy(),this.peerPool=null,this.failedDCMap.clear(),this.notFoundDCSet.clear(),this.logUploader&&(this.logUploader.destroy(),this.logUploader=null),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer),clearTimeout(this.requestPeersTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}isPeerConnectedOrFailed(e){return!e||(this.DCMap.has(e)||this.failedDCMap.has(e)||e===this.peerId)}_filterPeers(e){const t=[];return e.filter((e=>!this.isPeerConnectedOrFailed(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator})})),t}_tryConnectToAllPeers(){const{logger:e}=this;if(0!==this.peers.length)for(this._checkDCMap(),e.info(`try connect to ${this.peers.length} peers, map size ${this.DCMap.size} limit ${this.maxConnsActive} peersNum ${this.scheduler.peersNum}`);this.peers.length>0&&!(this.DCMap.size>=this.maxConnsActive);){let t=this.peers.shift();if(this.isPeerConnectedOrFailed(t.id))continue;const i=t.intermediator;this.signalerWs.connected||i&&this.DCMap.has(i)?(e.debug(`create DataChannel ${t.id} intermediator ${i}`),this._createDatachannel(t.id,!0,i)):e.info(`skip peer ${t.id} without intermediator`)}else e.info("no peers after filter")}_handleSendSignal(e,t){const i=e.remotePeerId;if(e.intermediator){const r=this.DCMap.get(e.intermediator);if(r){let n=!0;for(let e of t)r.sendMsgSignal(i,this.peerId,e)||(n=!1);if(n)return;this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,this.signalerWs.sendSignalBatch(i,t,e.signalName)}_setupDC(t){t.on(e.DC_SIGNAL,(e=>{this._handleSendSignal(t,[e])})).on(e.DC_SIGNAL_BATCH,(e=>{this._handleSendSignal(t,e)})).on(e.DC_PEER_SIGNAL,(e=>{const i=e.to_peer_id||e.to,r=e.from_peer_id||e.from,n=e.action;if(i&&r&&n)if(i!==this.peerId){this.logger.info(`relay signal for ${r}`);const s=this.DCMap.get(i);if(s){if("signal"!==n)return void s.sendMsgSignalReject(i,r,e.reason,e.fatal);if(s.sendMsgSignal(i,r,e.data))return}t.sendMsgSignal(r,i)}else"signal"===n?this._handleSignalMsg(r,e,t.remotePeerId):this._handSignalRejected(r,e)})).on(e.DC_GET_PEERS,(()=>{const e=g(),i=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?15:22)&&!e.super));if(i&&i.length>0){const r=[];i.forEach((i=>{if(i.remotePeerId===t.remotePeerId||i.remotePeerId===this.peerId)return;if(!this.config.live&&(i.currentPos-t.currentPos>600||i.currentPos<t.currentPos))return;e-i.timeJoin>50&&r.push({id:i.remotePeerId,...i.region})})),this.logger.info(`send ${r.length} peers to ${t.remotePeerId}`),t.sendPeers(r)}})).on(e.DC_PEERS,(e=>{const i=e.peers;this.logger.info(`receive ${i.length} peers from ${t.remotePeerId}`),i&&i.length>0&&(i.forEach((e=>{e.intermediator=t.remotePeerId,e.region||(e.region={})})),this.requestPeersQueue.push(...i)),this.requestPeersWaitCount--,this.requestPeersWaitCount<=0&&this._handleRequestedPeers()})).once(e.DC_ERROR,((e,i)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${i}`),this.scheduler&&(this.scheduler.deletePeer(t),this._destroyAndDeletePeer(t.remotePeerId,e),this.fetcher&&(t.connected||e&&this.fetcher.increFailConns(),e&&this.failedDCMap.set(t.remotePeerId,`DC_FAILED ${i}`),this._doSignalFusing(this.scheduler.peersNum),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:i,data:r})=>{const{logger:n,signalerWs:s,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,n.warn("gotSignalFails many, forcePolling"),s.forcePolling(u))),i&&e&&h&&(this.failedDCMap.set(o,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!e&&h&&!l&&this._tryBackupSignal(t,o,r))return t._startTimer(),void n.warn(`${o} conn timeout, try backup signal`);this._destroyAndDeletePeer(o,!1),this._doPeersRequest()})).once(e.DC_CLOSE,(e=>{this.logger.info(`datachannel ${t.channelId} closed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(t.remotePeerId,e),e&&this.failedDCMap.set(t.remotePeerId,"DC_CLOSE"),this._doPeersRequest()})).once(e.DC_OPEN,(()=>{t.isInitiator&&this.scheduler.handshakePeer(t)})).once(e.DC_METADATA,(e=>{const{scheduler:i}=this;t.isInitiator||i.handshakePeer(t),i.handleMetaData(t,e);const r=this.DCMap.size>=this.maxConnsActive;this.requestMorePeers(r),t.intermediator&&this.peersIncrement++,this._doSignalFusing(i.peersNum)}))}_doPeersRequest(){const e=this.scheduler.peersNum;!this.signalerWs.connected||this.overloaded&&e>this.minConns?this._requestPeersFromPeers(e):this.requestMorePeers(),this._tryConnectToAllPeers()}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e<=this.minConns&&this.signalerWs.normalClosed&&(this.logger.warn(`low conns ${e}, reconnect signaler`),this.signalerWs.reconnect())}_initSignalerWs(t,i,r,n){const s=(e,t)=>{let i=`${e}?id=${this.peerId}&p=web&v=2.14.4`;return this.config.signalCompact&&(i=`${i}&c=1`),t&&(i=`${i}&token=${t}`),i};let a,o=s(t,r);if(i&&i!==t){let e=s(i,n);a=new lt(this.logger,this.config,o,e)}else a=new ot(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this.engine.emitEvent("serverConnected",!0),this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let i=e.action;const r=e.from_peer_id||e.from;if(r)switch(i){case"signal":this._handleSignalMsg(r,e,null,t);break;case"reject":this._handSignalRejected(r,e);break;default:this.logger.warn(`Signal websocket unknown action ${i}`)}else this.logger.warn("fromPeerId is missed")},a.onclose=()=>{this.connected=!1,this.engine.emitEvent("serverConnected",!1)},a.onerror=t=>{t.message&&this.logger.warn(`signal err: ${t.message}`),t.message&&this.engine.emitEvent(e.EXCEPTION,Fe(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const i=`signaling ${e} rejected`;this.logger.warn(`${i}, reason ${t.reason}`);const r=this.DCMap.get(e);r&&!r.connected&&(r.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,i),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,i,r="main"){return!(!(this.signalerWs.backupConnected&&e&&i.length>0&&"main"===r)||e.useBackupSignal)&&(e.useBackupSignal=!0,e.signalName="backup",e.intermediator=void 0,this.signalerWs.sendSignalBatch(t,i,"backup"),!0)}_handleSignalMsg(e,t,i,r){if(!this.scheduler)return;const{logger:n}=this;if(t.data){if(this.failedDCMap.has(e))return void this._sendSignalReject(e,`${e} ${this.failedDCMap.get(e)||"unknown"}`,i,r,!0);this._handleSignal(e,t.data,i,r)}else{const t=this.DCMap.get(e);if(!t)return;if(this._tryBackupSignal(t,e,t.signalMsgs,r))return void this.logger.warn(`${e} not found from main, try backup signal`);if(t.useBackupSignal)return;this._destroyAndDeletePeer(e),n.info(`signaling ${e} not found`);const{scheduler:s}=this;s.waitForPeer&&(s.waitingPeers--,0===s.waitingPeers&&s.notifyPeersLoaded(0)),this.requestMorePeers(),this._tryConnectToAllPeers(),i||this.notFoundDCSet.add(e)}}_handleSignal(e,t,i,r){let n=t;"string"==typeof n?n=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:bt(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),i="O"===e[0];return{type:i?"offer":"answer",sdp:At(t,i)}})(n):t=void 0;const s=n.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"===s&&o.isInitiator){if(!(this.peerId>e))return void a.warn(`${e} signal type wrong ${s}, ignored`);a.warn(`${e} signal type wrong ${s}, convert to non initiator`),this._destroyAndDeletePeer(e,!1),o=this._createDatachannel(e,!1,i)}}else{if("answer"===s){const t=`${e} type wrong ${s}`;return a.warn(t),this._sendSignalReject(e,t,i,r),void this._destroyAndDeletePeer(e,!1)}if(a.debug(`receive node ${e} connection request`),this.DCMap.size>=this.maxConns){const t=`reach limit ${this.maxConns}`;return a.warn(t),void this._sendSignalReject(e,t,i,r)}o=this._createDatachannel(e,!1,i)}o&&(r&&(o.signalName=r),o.receiveSignal(n,t))}_createDatachannel(e,t,i){if(!this.fetcher)return;let r;if(t&&this.peerPool.available)r=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${r.signalMsgs.length}`),r.intermediator=i,r.assignPeerId(this.peerId,e);else{let n=this.config.trickleICE;this.overloaded&&(n=!1),r=new Z(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:i,trickle:!i&&n})}return this.DCMap.set(e,r),this._setupDC(r),r}_sendSignalReject(e,t,i,r,n){if(i){const r=this.DCMap.get(i);if(r&&r.sendMsgSignalReject(e,this.peerId,t,n))return}this.signalerWs.sendReject(e,t,n,r)}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this,i=this.scheduler.peersNum;i>=this.maxConnsActive||(t.info(`requestMorePeers after delay ${e}, peersIncrement ${this.peersIncrement}`),i<3||i<this.minConns&&this.peersIncrement<=3&&!this.gotPeersFromTracker?this._requestPeersFromServer(i):this._requestPeersFromPeers(i)||this._requestPeersFromServer(i),this.peersIncrement=0)}_requestPeersFromServer(e){const{logger:t}=this;this.failedDCMap.size>50&&(this.failedDCMap=new Map([...this.failedDCMap].slice(-50))),this.notFoundDCSet.size>20&&(this.notFoundDCSet=new Set([...this.notFoundDCSet].slice(-20))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCMap.keys(),...this.notFoundDCSet.keys()],0===e).then((e=>{e&&e.peers&&(t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=this._filterPeers(e.peers),this._tryConnectToAllPeers())})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0}_requestPeersFromPeers(e){return!!this.requestPeersTimer||(e>=this.maxConnsActive||(this.requestPeersWaitCount=this.scheduler.requestPeers(),0!==this.requestPeersWaitCount&&(this.gotPeersFromTracker=!1,this.requestPeersTimer=setTimeout((()=>{this.logger.warn("requestPeersTimer timeout"),this._handleRequestedPeers()}),1e4),!0)))}_handleRequestedPeers(){if(clearTimeout(this.requestPeersTimer),this.requestPeersTimer=void 0,this.fetcher){if(this.requestPeersQueue.length>0){const e=function(e,t){const i=[],r=new Set;for(let t of e)r.has(t.id)||(r.add(t.id),i.push(t));const{asn:n,country:s}=t;if(!n||!s||i.length<2)return i;const a=i.filter((e=>!e.asn&&!e.country)),o=i.filter((e=>e.country===s&&e.asn!==n)),l=i.filter((e=>e.asn===n&&e.country===s)),h=i.filter((e=>!a.includes(e)&&!l.includes(e)&&!o.includes(e)));return l.concat(o).concat(a).concat(h)}(this.requestPeersQueue,this.fetcher.announceInfo);this.peers=this._filterPeers(e),this.requestPeersQueue=[]}this._tryConnectToAllPeers()}}_destroyAndDeletePeer(e,t=!0){const i=this.DCMap.get(e);return!!i&&(i.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=g();for(let t of this.DCMap.values()){const i=e-t.timeJoin;e-t.timeJoin>30&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${i} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}}const Pt=Rt;class kt extends re{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},ce,e),t){this.HLSEvents=t.constructor.Events;const e=t.constructor.version;this.hlsjsVersion=e,this.config.isHlsV0=e&&"0"===e.split(".")[0]}this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t}=this.config,i=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(i=this.makeChannelId(e,t));return{channelIdMaker:i,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo}}}setupElectron(){this.browserInfo.device===X.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e=super.getExtraForStats();return!this.config.live&&this.media&&(e.pos=Math.round(this.media.currentTime)),this.multiBitrate&&this.currentLevel!==this.lastLevel&&(e.level=this.currentLevel+"",this.lastLevel=this.currentLevel),e}getExtraForPeersRequest(){const e=super.getExtraForPeersRequest();return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){super.destroy()}async initSegmentManager(e){const{logger:i,config:r}=this;if(self.indexedDB&&r.useDiskCache&&!r.live){const e=new ke(this,r);try{await e.setupStore(),this.bufMgr=e}catch(e){i.warn(e),this.bufMgr=new Ce(this,r)}}else this.bufMgr=new Ce(this,r);if(this.bufMgr.maxBufSize<=0)throw new Error("bufMgr state is invalid");"SegmentStore"===this.bufMgr.name&&(this.removeAllListeners(t.BM_FATAL_ERROR),this.once(t.BM_FATAL_ERROR,(()=>{const t="SegmentStoreFatalError";i.warn(`${t}, switch to SegmentCache`),this.bufMgr.destroy(),this.bufMgr=new Ce(this,r),e&&e(this.bufMgr),i.report(JSON.stringify(this.browserInfo),t,this.peerId,"2.14.4",5e4)})))}generateTag(){let e=(0,X.getBrowser)();return e.includes("iPhone")&&"HlsSwP2pEngine"===this.engineName&&(e=`${e}_p`),this.playerName&&(e=`${e}_${this.playerName}`),e}async _init(e,t,i){const{logger:r,config:n}=this;if(!re.isSupported())throw new Error("webrtc is not supported");await this.initSegmentManager((e=>{if(this.tracker){const{scheduler:t}=this.tracker;t.bufferManager=e,t.bitset.clear()}})),i.live||this.media&&(i.pos=Math.round(this.media.currentTime)),i.tag=void 0===n.tag?this.generateTag():n.tag;let s=new it(this,n.token,encodeURIComponent(e),n.announce||"",i);this.fetcher=s,this.tracker=new Pt(this,s,t,n),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?he:le)}_onHlsError(e,i){if(!i||!this.hlsjs)return;const{logger:r,tracker:n}=this;if(!r)return;const s=`${i.type} details ${i.details} reason ${i.reason}`;if(i.fatal?r.error(s):r.warn(s),"networkError"===i.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:a}=this.browserInfo,o=`${a||""} hlsjs ${this.hlsjsVersion} ${location.href}`,l=this.hlsjs.constructor.ErrorDetails;switch(i.details){case l.BUFFER_STALLED_ERROR:if("HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),n&&n.scheduler){const e=n.scheduler;r.warn(`buffered: ${1e3*e.getBufferedDuration()} fragLoading ${e.fragLoading} isCritical ${e.isCritical()}`)}break;case l.INTERNAL_EXCEPTION:if(i.event&&"demuxerWorker"!==i.event){i.error||(i.error={});const e=`${i.error.message} event ${i.event} ${o}`;this.fetcher&&i.fatal&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=e),r.error(`INTERNAL_EXCEPTION event ${i.event} err ${i.error.message}`),this.emitEvent(t.EXCEPTION,Fe(i.error,"HLSJS_EXPT")),r.report(e,i.event,this.peerId,"2.14.4")}break;default:if(i.fatal||i.details===l.FRAG_PARSING_ERROR){"mediaError"===i.type&&n&&n.scheduler.disconnectLoadingPeer().finally((()=>{n.scheduler.clearCache()}));const e=`${i.type} ${i.details} ${i.err||""} ${o}`;r.report(e,i.details,this.peerId,"2.14.4")}}}}class Dt{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 wt{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[wt.ElementaryStreamTypes.AUDIO]:!1,[wt.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=o.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url}set url(e){this._url=e}get byteRange(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;let e=[];if(this.rawByteRange){const t=this.rawByteRange.split("@",2);if(1===t.length){const t=this.lastByteRangeEndOffset;e[0]=t||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get decryptdata(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}get endProgramDateTime(){if(!Number.isFinite(this.programDateTime))return null;let e=Number.isFinite(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}addElementaryStream(e){this._elementaryStreams[e]=!0}hasElementaryStream(e){return!0===this._elementaryStreams[e]}createInitializationVector(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let i=e;return e&&e.method&&e.uri&&!e.iv&&(i=new Dt,i.method=e.method,i.baseuri=e.baseuri,i.reluri=e.reluri,i.iv=this.createInitializationVector(t)),i}}class Ct{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 Mt=/^(\d+)x(\d+)$/,Ot=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class xt{constructor(e){"string"==typeof e&&(e=xt.parseAttrList(e));for(let t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}enumeratedString(e){return this[e]}decimalResolution(e){const t=Mt.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,i={};for(Ot.lastIndex=0;null!==(t=Ot.exec(e));){let e=t[2],r='"';0===e.indexOf(r)&&e.lastIndexOf(r)===e.length-1&&(e=e.slice(1,-1)),i[t[1]]=e}return i}}const Ft=xt,Nt={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 Bt=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Ut=/#EXT-X-MEDIA:(.*)/g,Gt=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?/,Vt=/\.(mp4|m4s|m4v|m4a)$/i;class Kt{static findGroup(e,t){if(!e)return null;let i=null;for(let r=0;r<e.length;r++){const n=e[r];n.id===t&&(i=n)}return i}static convertAVC1ToAVCOTI(e){let t,i=e.split(".");return i.length>2?(t=i.shift()+".",t+=parseInt(i.shift()).toString(16),t+=("000"+parseInt(i.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let i,r=[];function n(e,t){["video","audio"].forEach((i=>{const r=e.filter((e=>function(e,t){const i=Nt[t];return!!i&&!0===i[e.slice(0,4)]}(e,i)));if(r.length){const n=r.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${i}Codec`]=n.length>0?n[0]:r[0],e=e.filter((e=>-1===r.indexOf(e)))}})),t.unknownCodecs=e}for(Bt.lastIndex=0;null!=(i=Bt.exec(e));){const e={},s=e.attrs=new Ft(i[1]);e.url=Kt.resolve(i[2],t);const a=s.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=s.decimalInteger("AVERAGE-BANDWIDTH")||s.decimalInteger("BANDWIDTH"),e.name=s.NAME,n([].concat((s.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=Kt.convertAVC1ToAVCOTI(e.videoCodec)),r.push(e)}return r}static parseMasterPlaylistMedia(e,t,i,r=[]){let n,s=[],a=0;for(Ut.lastIndex=0;null!==(n=Ut.exec(e));){const e={},o=new Ft(n[1]);if(o.TYPE===i){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=i,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=Kt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),r.length){const t=Kt.findGroup(r,e.groupId);e.audioCodec=t?t.codec:r[0].codec}e.id=a++,s.push(e)}}return s}static parseLevelPlaylist(e,t){let i,r,n=0,s=0,a=new Ct(t),o=new Dt,l=0,h=null,u=new wt,d=null;for(Gt.lastIndex=0;null!==(i=Gt.exec(e));){const e=i[1];if(e){u.duration=parseFloat(e);const t=(" "+i[2]).slice(1);u.title=t||null,u.tagList.push(t?["INF",e,t]:["INF",e])}else if(i[3]){if(Number.isFinite(u.duration)){const e=n++;u.start=s,u.levelkey=o,u.sn=e,u.cc=l,u.baseurl=t,u.relurl=(" "+i[3]).slice(1),Wt(u,h),a.fragments.push(u),h=u,s+=u.duration,u=new wt}}else if(i[4]){if(u.rawByteRange=(" "+i[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(u.lastByteRangeEndOffset=e)}}else if(i[5])u.rawProgramDateTime=(" "+i[5]).slice(1),u.tagList.push(["PROGRAM-DATE-TIME",u.rawProgramDateTime]),null===d&&(d=a.fragments.length);else{for(i=i[0].match(Ht),r=1;r<i.length&&void 0===i[r];r++);const e=(" "+i[r+1]).slice(1),s=(" "+i[r+2]).slice(1);switch(i[r]){case"#":u.tagList.push(s?[e,s]:[e]);break;case"PLAYLIST-TYPE":a.type=e.toUpperCase();break;case"MEDIA-SEQUENCE":n=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 Dt,g&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(f)>=0&&(o.method=f,o.baseuri=t,o.reluri=g,o.key=null,o.iv=p));break;case"START":let r=new Ft(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(r)&&(a.startTimeOffset=r);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 wt,u.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${i}`)}}}return u=h,u&&!u.relurl&&(a.fragments.pop(),s-=u.duration),a.totalduration=s,a.averagetargetduration=s/a.fragments.length,a.endSN=n-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>Vt.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),u=new wt,u.relurl=a.fragments[0].relurl,u.baseurl=t,u.level=id,u.sn="initSegment",a.initSegment=u,a.needSidxRanges=!0),d&&function(e,t){let i=e[t];for(let r=t-1;r>=0;r--){const t=e[r];t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(a.fragments,d),a}}function Wt(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 $t={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},qt=(e,t,i,r,n=!1)=>{const[s,a,o]=jt(e,t,i,r);return n&&s.length>=1?P(s[0]):s.length>=2?[s[0],s[1]]:k(s,a,o)},jt=(e,t,i,r)=>{const n=[],{COMPLETE:s,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=$t;return[s,a,o].forEach((s=>{n.push(Yt(e,s,t,i,r))})),n},Yt=(e,t,i,r,n)=>e.filter((e=>e.bitset.hasWithId(i,r,n,t)));class zt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const i=Number(e);if(i<0)continue;const r=new Map;if(t[e])for(let i of t[e])r.set(i,{state:$t.COMPLETE,segId:void 0,size:void 0});this.levelMap.set(i,r)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,i,r=$t.ANY){if(t<0)return!1;const n=this._createOrGetSet(t).get(e);return!!n&&((!i||!n.segId||n.segId===i)&&(r===$t.ANY||n.state===r))}has(e,t,i=$t.ANY){return this.hasWithId(e,t,void 0,i)}hasCompleteOr(e,t,i=$t.COMPLETE){const r=this._createOrGetSet(t).get(e);return!!r&&(r.state===$t.COMPLETE||r.state===i)}getObj(e,t){let i=this._createOrGetSet(t).get(e);return i||(i={}),i}getSegId(e,t){return this.getObj(e,t).segId}getSize(e,t){return this.getObj(e,t).size}getState(e,t){return this.getObj(e,t).state}delete(e,t){return this._createOrGetSet(t).delete(e)}add(e,t,i,r,n){if("number"!=typeof(s=e)||s%1!=0)return;var s;this._createOrGetSet(t).set(e,{state:r,segId:i,size:n}),this.isLive&&this._trimBitset(e)}array(e){const t=this._createOrGetSet(e);return this._keysForStateComplete(t)}allArray(){let e={};return this.levelMap.forEach(((t,i)=>{e[i]=this._keysForStateComplete(t)})),e}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetSet(e).size}_createOrGetSet(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}_trimBitset(e){const t=e-20;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[i,r]of e)r.state===$t.COMPLETE&&t.push(i);return t}}class Xt{constructor(){this.levelMap=new Map}totalLevels(){return this.levelMap.size}has(e,t){return this._createOrGetMap(t).has(e)}delete(e,t){return this._createOrGetMap(t).delete(e)}decre(e,t){const i=this._createOrGetMap(t);if(i.has(e)){let t=i.get(e);1===t?i.delete(e):i.set(e,t-1)}}incre(e,t){const i=this._createOrGetMap(t);if(i.has(e)){let t=i.get(e);i.set(e,t+1)}else i.set(e,1)}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetMap(e).size}_createOrGetMap(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}}const Qt=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))}},Jt=Symbol("shareOnly");class Zt extends(s()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Qt,this.fragLoading=!1,this._setupEngine&&this._setupEngine(),this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[Jt]=!1,this.downloadOnly=!1,this.loadedPeerNum=0,this.minConns=5}get isMobileNet(){return this.engine.isMobileNet}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const e=this.getStatsForPeer();let t=this.peersNum;const i=g();this.getPeers().forEach((r=>{t>this.minConns+1&&(i-r.dataExchangeTs>120||i-r.gotStatsTs>=83)?(this.logger.warn(`close dead peer ${r.remotePeerId} level ${r.currentLevel}`),r.close(!1),t--):r.connected&&r.sendMsgStats(t,e)}))}),4e4)}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}requestPeers(){const e=g();let t=0;for(let i of this.getPeers())i.mobileNet||i.super||(e-i.gotPeersTS<60?this.logger.warn(`${i.remotePeerId} just got peers, ignored`):(i.sendPeersRequest(),i.gotPeersTS=e,t++));return t}chokePeerRequest(t){const i={event:e.DC_CHOKE};t?t.sendJson(i):this._broadcastToPeers(i)}unchokePeerRequest(t){const i={event:e.DC_UNCHOKE};t?t.sendJson(i):this._broadcastToPeers(i)}stopRequestFromPeers(){for(let e of this.getPeers())e.choked=!0}resumeRequestFromPeers(){for(let e of this.getPeers())e.choked=!1}setShareOnly(){this[Jt]=!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[Jt]&&(e.choked=!0);const i=this.peerManager.getPeerIds();this._peersStats(i);const{asn:r,country:n}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${n||""} asn ${r||""}, now has ${i.length} peers`)}hasPeer(e){return this.peerManager.hasPeer(e)}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const{logger:e}=this,t=this.getIdlePeer().length;if(e.info(`peers: ${this.peersNum} idle peers: ${t}`),t<this.peersNum){const t=this.peerManager.getPeers(),i=t.filter((e=>e.downloading));e.warn(`downloading: ${i.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of i)e.warn(`${t.remotePeerId} loading ${t.segId} remains ${t.remainAttachments} total ${t.pieceMsg.attachments}`)}return t>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(t){this.bufMgr=t,t.on(e.BM_LOST,(({sn:e,segId:t,next:i,level:r})=>{this._broadcastLost(e,t,r),this.onBufferManagerLost(e,t,i,r)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,i,r,n){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:i||void 0,level:r},n)}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),clearTimeout(this.checkTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(t){const{logger:i}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),i.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{i.warn(`peer ${t.remotePeerId} download aborted, reason ${e.reason}`),this._handlePieceAborted(t.remotePeerId),this.config.live&&this.checkPeers&&this.checkPeers()})).on(e.DC_DISCONNECT,(()=>{this.peersNum>=this.minConns&&(this.logger.warn(`close disconnected peer ${t.remotePeerId}`),t.close(!1))}))}_broadcastToPeers(e,t){for(let i of this.getPeers())t&&i===t||i.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;I(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(i=this.loadedPeerNum)?3:.5*i+1.67);var i;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const i=this.requestingMap.get(e);if(i)return void i.removeStreamListener(t);const r=this.segmentBuilderMap.get(e);r&&r.removeStreamListener(t)}setTargetPeersFromGroup(e,t,i,r){if(e.hasReversePeer){if((i=t.concat(i)).length>0)return this.targetPeers.forwardPeer=i[0],!0}else if(e.hasForwardPeer&&(r=t.concat(r)).length>0)return this.targetPeers.reversePeer=r[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=k(t,i,r),this.targetPeers.some((e=>!!e)))}}const ei=Zt;class ti extends(s()){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 ii=0,ri=1,ni=2,si=3;class ai extends(s()){constructor(){super(),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.timeout=0,this.withCredentials=!1,this.status=0,this.readyState=this.UNSENT,this.headers=new Map,this.responseHeaders=null,this.on("load",(e=>{this.onload&&this.onload(e)})),this.on("abort",(e=>{this.onabort&&this.onabort(e)})),this.on("error",(e=>{this.onerror&&this.onerror(e)})),this.on("loadstart",(e=>{this.onloadstart&&this.onloadstart(e)})),this.on("progress",(e=>{this.onprogress&&this.onprogress(e)})),this.on("timeout",(e=>{this.ontimeout&&this.ontimeout(e)})),this.on("loadend",(e=>{this.onloadend&&this.onloadend(e)})),this.on("readystatechange",(()=>{this.onreadystatechange&&this.onreadystatechange()}))}setRequestHeader(e,t){this.headers.set(e,t)}addEventListener(e,t){this.addListener(e,t)}removeEventListener(e,t){this.removeListener(e,t)}overrideMimeType(){}getAllResponseHeaders(){if(!this.responseHeaders)return null;let e="";return this.responseHeaders.forEach(((t,i)=>{e+=`${i}: ${t}\n`})),e}getResponseHeader(e){return this.responseHeaders?this.responseHeaders.get(e):null}open(){this.readyState=this.OPENED,this.emit("loadstart")}abort(){this.readyState=this.DONE,this.status=0,this.emit("loadend")}send(){}_emitEvent(e){this.emit(e,{type:e,target:this})}}const oi=/(\d+)-(\d+)\/(\d+)/;function li(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class hi{constructor(e){this.fetchSetup=e.fetchSetup||ui,this.xhrSetup=e.xhrSetup,this.controller=new self.AbortController,this.stats=D(),this.packetSize=u,this.fakeXhr=new ai}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.xhrSetup=this.fakeXhr=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.callbacks&&this.callbacks.onUpdate&&this.callbacks.onUpdate(void 0,!1,!0),this.controller.abort())}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;r.trequest=r.loading.start;let n=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal);const s="arraybuffer"===e.responseType,a=s?"byteLength":"length",{maxTimeToFirstByteMs:o=8e3,maxLoadTimeMs:l=2e4}=t.loadPolicy||{},h=i.onUpdate,u=i.onBodyStart;this.context=e,this.config=t,this.callbacks=i,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),n=function(e,t){e.withCredentials&&(t.credentials="include");for(let[i,r]of e.headers)t.headers.set(i,r);return t}(this.fakeXhr,n)),this.request=this.fetchSetup(e,n),clearTimeout(this.requestTimeout),t.timeout=o&&Number.isFinite(o)?o:l,this.requestTimeout=setTimeout((()=>{this.abortInternal(),this.fakeXhr._emitEvent("timeout"),this.fakeXhr._emitEvent("loadend"),i.onTimeout&&i.onTimeout(r,e,this.response)}),this.fakeXhr.timeout||t.timeout);const d="then"in(c=this.request)&&c.then instanceof Function?this.request.then(self.fetch):self.fetch(this.request);var c;const{fakeXhr:f}=this;f.readyState=f.OPENED,f.emit("readystatechange"),f._emitEvent("loadstart"),d.then((n=>{this.response=this.loader=n;const a=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),l-(a-r.loading.start)),!n.ok){const{status:e,statusText:t}=n;throw new di(t||"fetch, bad network response",e,n)}r.tfirst=r.loading.first=a,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=oi.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Number.isFinite(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(n.headers)||r.total;let o=0;try{const e=n.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=n.headers,d.emit("readystatechange"),h&&"0"!==r.total?(u&&u(r.total,o),this.loadProgressively(n,r,e,h)):(d.emit("progress",new ProgressEvent("progress",{lengthComputable:!1})),s?n.arrayBuffer():"json"===e.responseType?n.json():n.text())})).then((t=>{const{response:n}=this;clearTimeout(this.requestTimeout),r.tload=r.loading.end=Math.max(performance.now(),r.loading.first);const s=t[a];s&&(r.loaded=r.total=s);const o={url:n.url,data:t,code:n.status};i.onProgress&&i.onProgress(r,e,t,n),i.onSuccess&&i.onSuccess(o,r,e,n)})).catch((t=>{if(clearTimeout(this.requestTimeout),r.aborted)return;const n=t&&t.code||0,s=t?t.message:null;i.onError&&i.onError({code:n,text:s},e,t?t.details:null,r)}))}loadProgressively(e,t,i,r){const n=e.body.getReader();let s=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>n.read().then((({value:i,done:n})=>{const{fakeXhr:c}=this;if(c.readyState!==c.LOADING&&(c.readyState=c.LOADING,c.emit("readystatechange")),i&&(s+=i.length),n){if(l.byteLength>0)if(s<=this.packetSize){const e=(0,a.h)(s);l.copy(e,0,o*this.packetSize,l.byteLength),r(e,!0)}else{const e=function(e,t){const i=e.byteLength-t,r=[];let n=t,s=Math.floor(i/u),o=i%u;for(let t=0;t<s;t++){const t=(0,a.h)(u);e.copy(t,0,n,n+u),r.push(t),n+=u}if(o>0){const t=(0,a.h)(o);e.copy(t,0,n,n+o),r.push(t)}return r}(l,o*this.packetSize);for(let t=0;t<e.length;t++)r(e[t],t===e.length-1)}const t=l.buffer,{fakeXhr:i}=this,{status:n,statusText:h,url:d}=e;return i.readyState=i.DONE,i.responseText=n,i.status=h,i.responseURL=d,i.responseType="arraybuffer",i.response=t,i.emit("readystatechange"),i._emitEvent("load"),i._emitEvent("loadend"),Promise.resolve(t)}if(t.loaded+=i.length,c.emit("progress",new ProgressEvent("progress",{lengthComputable:!0,loaded:t.loaded,total:t.total})),this.callbacks.onLoaded&&this.callbacks.onLoaded({total:t.total,loaded:t.loaded,first:!h},this.context),h=!0,l=a.h.concat([l,i]),s>=this.packetSize){s-=this.packetSize;const e=(0,a.h)(this.packetSize);l.copy(e,0,o*this.packetSize,(o+1)*this.packetSize),o++,r(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function ui(e,t){return new self.Request(e.url,t)}class di extends Error{constructor(e,t,i){super(e),this.code=t,this.details=i}}class ci extends(s()){constructor(e,t,i=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=i,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=2e3,this.proxied=!1,this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.forwardBufList=[],this.reverseBufList=[],this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.rangeRequesting=!1,this.waitingRemain=!1,this.httpLoaded=0,this.p2pLoaded=0,this.deadline=0,this.forwardCanceled=!1,this.reverseCanceled=!1,this.firstReceived=!1,this.alreadyOutput=!1,this.pieceMsg={}}get isDownloading(){return this.timeReceivePiece>0}get isAlmostDeadline(){return this.rangeRequesting||this.alreadyOutput}hasPeer(e){return!!e&&(e===this.forwardPeer||e===this.reversePeer)}get streamListeners(){return[...this.reverseStreamListeners,...this.forwardStreamListeners].length}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg,i=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let r of i){const{handler:i}=r;i(e,t,!0,"aborted by synthesizer")}this._resetStreamListeners()}_resetStreamListeners(){this.reverseStreamListeners.length=0,this.forwardStreamListeners.length=0}_notifyStreamListenersRemain(){if(this.forwardStreamListeners.length>0){for(let e=this.forwardOffset+1;e<this.bufArr.length;e++)this._notifyStreamListeners(!1,this.bufArr[e],e);this.forwardStreamListeners=[]}if(this.reverseStreamListeners.length>0){for(let e=this.reverseOffset-1;e>=0;e--)this._notifyStreamListeners(!0,this.bufArr[e],e);this.reverseStreamListeners=[]}}addStreamListener(e,t,i){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:i,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:i}=this.pieceMsg,r=r=>r.filter((r=>r.peerId!==e||(r.handler(t,i,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=r(this.forwardStreamListeners),this.reverseStreamListeners=r(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let i=performance.now();e<=0?setTimeout((()=>{this._handleTimeout(!1,!1)}),0):(this.firstPieceTimer=setTimeout((()=>{if(this.firstReceived)return;const e=()=>{this.logger.warn(`switch to http, firstReceived ${this.firstReceived}`),this._handleTimeout(!1)};if(this.timeReceivePiece>0){const t=(this.timeReceivePiece-i)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=i+e,this._startTimer(e,t))}setExtra(e={}){e.url&&(this.url=e.url),e.rangeStart&&(this.rangeStart=e.rangeStart),e.rangeEnd&&(this.rangeEnd=e.rangeEnd),e.httpLoadTime&&(this.httpLoadTime=e.httpLoadTime),e.proxied&&(this.proxied=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup),e.headers&&(this.headers=e.headers),e.segId&&!this.pieceMsg.seg_id&&(this.pieceMsg.seg_id=e.segId)}get hasForwardPeer(){return!!this.forwardPeer}get hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}get isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}get isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1,t),!0))}setReversePeer(e,t){return!this.alreadyOutput&&(!!this._checkPieceSize(t)&&(this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0,t),!0))}setPeer(e,t,i){return t?this.setReversePeer(e,i):this.setForwardPeer(e,i)}deletePeer(e){const t=e===this.reversePeer;this._detachPeer(e),t?this.reversePeer=null:this.forwardPeer=null,(this.isEmpty||this.deadline>0)&&this._handleTimeout(!1,!1)}terminate(){this._handleTimeout(!1,!1)}get hasPartialBuffer(){return this.hasForwardBuffer||this.hasReverseBuffer}get hasForwardBuffer(){return this.forwardOffset>=0}get hasReverseBuffer(){return this.pieceMsg&&this.reverseOffset<this.pieceMsg.attachments}get isForwardBufferFull(){return this.pieceMsg&&this.forwardOffset>=this.pieceMsg.attachments-1}get isReverseBufferFull(){return this.reverseOffset<=0}_cancelP2p(e=!1){const{seg_id:t,sn:i,level:r}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(i,r,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(i,r,t),this.reverseCanceled=!0)}detachPeers(){this._detachPeer(this.forwardPeer),this._detachPeer(this.reversePeer)}destroy(){clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._notifyStreamListenersAbort(),this._cancelP2p(),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.httpLoader&&(this.logger.warn("abort syn httpLoader"),this.httpLoader.abort())}_detachPeer(t){if(!t)return;const i=t===this.reversePeer?this.reverseEvents:this.forwardEvents;i&&i&&t.off(e.DC_PIECE_DATA,i.onPieceData).off(e.DC_PIECE,i.onPiece).off(e.DC_PIECE_NOT_FOUND,i.onPieceNotFound).off(e.DC_PIECE_ABORT,i.onPieceAbort)}_receivePacket(t,i,r,n=!0){const{seg_id:s,sn:o,level:l,size:h,attachments:u}=this.pieceMsg,d=i-1;if(this.bufArr[d]?(this.logger.warn(`syn bufArr ${s} already has ${d} size ${r.byteLength}`),this.bufArr[d]=r):(n?this.p2pLoaded+=r.byteLength:this.httpLoaded+=r.byteLength,this.emit(e.SYN_PROGRESS,{total:h,loaded:this.p2pLoaded+this.httpLoaded,first:!this.firstReceived,segId:s,sn:o}),this.firstReceived=!0,this.bufArr[d]=r,t?this.reverseOffset=d:this.forwardOffset=d,this._notifyStreamListeners(t,r,d)),this.forwardOffset!==this.reverseOffset-1)return!0;this.rangeRequesting||(this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0)),clearTimeout(this.timer),this._notifyStreamListenersRemain();const c=performance.now()-this.timeStart,f=h/c;let g=a.h.concat(this.bufArr);const p=g.byteLength;if(p===h){let t=g.buffer;const i=new z(o,s,t,this.getFromPeerId(),l,this.pieceMsg.ext);this.alreadyOutput=!0,this.emit(e.SYN_OUTPUT,i,{speed:f,time:c,p2p:this.p2pLoaded,http:this.httpLoaded})}else{this.logger.error(`${s} 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,ii),this._disconnectPeers()}}_disconnectPeers(){[this.forwardPeer,this.reversePeer].forEach((t=>{t&&t.emit(e.DC_ERROR,!0)}))}_checkPieceSize(e){const{size:t,seg_id:i,sn:r}=this.pieceMsg;return!e||!t||e===t||(this.logger.warn(`checkPieceSize ${i||r} size not match ${t} ${e}`),!1)}_setupPeer(t,i,r){const{logger:n}=this;0===this.timeStart&&(this.timeStart=performance.now()),r&&!this.pieceMsg.size&&(this.pieceMsg.size=r);const s=(i,r,s,a,o,l)=>{if(this.destroyed)return;if(!this._validateMsg(i,l.level,r))return void n.error(`onPieceData ${r||i} size ${s.byteLength} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(a<this.pieceMsg.attachments&&s.byteLength!==u)return n.error(`${r} dataSn ${a} size is ${s.byteLength}`),this.emit(e.SYN_ERROR,this.pieceMsg,ii),void this._disconnectPeers();const{reverse:h}=l;this._receivePacket(h,a,s)&&!this.waitingRemain&&!this.rangeRequesting&&this.deadline>0&&this._shouldSwitch()&&(n.warn("should switch to http"),clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._handleTimeout(!1,!1))},a=e=>{if(this.destroyed)return;const{attachments:i,size:r,sn:s,level:a,seg_id:o,ext:l}=e;return r<=999||!this._validateMsg(s,a,o)?(n.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),t.cancelDownload(s,a,o),void this.deletePeer(t)):this._checkPieceSize(r)?void(0===this.bufArr.length&&(this.pieceMsg={...this.pieceMsg,seg_id:o,size:r,attachments:i,ext:l},this.reverseOffset=i,this.bufArr=new Array(i),this.timeReceivePiece=performance.now())):(t.cancelDownload(s,a,o),void this.deletePeer(t))},o=e=>{this.destroyed||this.deletePeer(t)},l=()=>{this.destroyed||this.deletePeer(t)},h={onPieceData:s,onPiece:a,onPieceNotFound:o,onPieceAbort:l};i?this.reverseEvents=h:this.forwardEvents=h,t.on(e.DC_PIECE_DATA,s).once(e.DC_PIECE,a).once(e.DC_PIECE_NOT_FOUND,o).once(e.DC_PIECE_ABORT,l)}_shouldSwitch(){const e=u,t=this.pieceMsg.size-e*this.loadedPackets;return this.coordinator.shouldSwitchToHttp(t,this.deadline,this.p2pSpeed,e,this.httpLoadTime)}_startTimer(e,t=!0){this.timer=setTimeout(this._handleTimeout.bind(this,t),e)}get loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(t=!1,i=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:r,size:n,attachments:s}=this.pieceMsg;if(!n||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${r} url ${this.url}`),void this.emit(e.SYN_ERROR,this.pieceMsg,ii);if(t&&this.timeReceivePiece>0&&s){this.logger.warn(`syn ${this.loadedPackets} of ${s} packets loaded`);const e=this.httpLoadTime>3e3?3e3:this.httpLoadTime;if(this.shouldWaitForRemain(e))return this.waitingRemain=!0,this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}if(i){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const i=e.currentLoadSpeed(),r=t.currentLoadSpeed();return i===r?e.timeSendRequest-t.timeSendRequest:i-r})).shift();e&&e.loadtimeout()}if((this.rangeSupported||!this.hasPartialBuffer)&&this.url)return this._cancelP2p(!0),this._loadRemainBufferByHttp();this._notifyStreamListenersAbort(),this.emit(e.SYN_ERROR,this.pieceMsg,si)}shouldWaitForRemain(e){return!this.isEmpty&&this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed,i=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${i}`),t>=i}minRequiredSpeed(e){let t=0;return[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(t+=e.loadedBytes())})),(this.pieceMsg.size-t)/e}get p2pSpeed(){let e=0;return[this.forwardPeer,this.reversePeer].forEach((t=>{t&&(e+=t.currentLoadSpeed())})),e}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull&&e!==t?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}getStreamInfo(e){const t=e?this.reverseBufList:this.forwardBufList;let i,r;return t.length<this.pieceMsg.attachments?(i=this.isFull?"WaitPartialDouble":"WaitPartialSingle",r=1):(i=this.isFull?"SynFullDouble":"SynFullSingle",r=0),{from:i,incompletes:r,bufferList:t}}_loadRemainBufferByHttp(){if(this.rangeRequesting)return;const{size:t,seg_id:i}=this.pieceMsg,{logger:r}=this,n=this.rangeEnd>0?this.rangeEnd-1:0;let s=this.forwardOffset;const a=performance.now();this.rangeRequesting=!0;let o=oe(s,this.reverseOffset,t,this.rangeStart,n);const l=o.rangeEnd-o.rangeStart;r.info(`listeners ${this.streamListeners} continue download ${i} from ${this.url} range: ${o.rangeStart}-${o.rangeEnd}`),this.hasPartialBuffer||(o={});const u=new hi({xhrSetup:this.xhrSetup});this.httpLoader=u;let d={url:this.proxied?f(this.url,h,!0):this.url,...o};let c,g=s+1;const p={onUpdate:(t,i,n)=>{if(!this.destroyed){if(n)return r.warn("httpLoader aborted"),void this.emit(e.SYN_ERROR,this.pieceMsg,ri);if(i){const e=c/(performance.now()-a);this.coordinator.addHttpSpeed(e),this.httpLoader=void 0}this.bufArr[g]||this._receivePacket(!1,g+1,t,!1),g++}},onBodyStart:(t,n)=>{if(0===n&&r.warn(`range request fileSize ${n}`),this.destroyed)return;const{size:s}=this.pieceMsg;if(c=t,t!==s||0!==n&&n!==s){let i=!1;n>0&&n!==s?(r.error(`onBodyStart fileSize ${n} != ${s}`),i=!0):t!==l&&(r.error(`onBodyStart size ${t} != expectedSize ${l}`),i=!0),i&&this.emit(e.SYN_ERROR,this.pieceMsg,ri)}else r.warn(`syn range request ${i} resp whole ts`),g=0},onError:t=>{this.destroyed||(r.error(`httpLoader error ${t.text}`),this.emit(e.SYN_ERROR,this.pieceMsg,ri))},onTimeout:()=>{this.destroyed||(r.warn("httpLoader timeout"),this.emit(e.SYN_ERROR,this.pieceMsg,ni))}};u.load(d,{timeout:15e3},p)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class fi extends ci{constructor(e,i,r,n,s,a=!1,o){super(e,i,a,o),this.pieceMsg={event:t.DC_PIECE,sn:r,level:n,seg_id:s},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,i){const{sn:r,seg_id:n,attachments:s}=this.pieceMsg,a=e&&0===i||!e&&i===s-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;e?this.reverseBufList.push(t):this.forwardBufList.push(t),a&&(this.forwardBufList.push([...this.reverseBufList].reverse()),this.reverseBufList.push([...this.forwardBufList].reverse()));for(let e of o){const{handler:i}=e;i(r,n,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,i){return(!this.pieceMsg.seg_id||i===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}}class gi{constructor(){this.meanHttpSpeed=0,this.loaderHttpSpeed=0}addHttpSpeed(e){this.meanHttpSpeed=this._cal(this.meanHttpSpeed,e)}addLoaderHttpSpeed(e,t){t&&e&&(this.loaderHttpSpeed=this._cal(this.loaderHttpSpeed,t/e))}getMeanTimeToLoaded(e){return this.loaderHttpSpeed?e/this.loaderHttpSpeed:500}shouldSwitchToHttp(e,t,i,r,n){if(this.meanHttpSpeed<=0)return!1;if(i>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*n>=e)return!1;return((n+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-i)*i<r}_cal(e,t){return.4*e+.6*t}}class pi extends ei{constructor(e,t){super(e,t),this.prefetchOnly=t.prefetchOnly,this.bitset=new zt(t.live||!1),this.bitCounts=new Xt,this.requestingMap=new ti,this.segmentBuilderMap=new ti,this.allowP2pLimit=t.httpLoadTime+1.5,this.playlistInfo=new Map,this.gotPlaylist=!1,this.targetPeers={},this.sequential=!0,this.coordinator=new gi,this.loadingSegId="",this.loadingSN=0,this.currPlaySN=0,this.currLostSN=-1,this.nextLostSN=-1,this.config.live?this.maxPrefetchCount=10:(this.maxPrefetchCount=150,this.startCheckPeersTimer())}handshakePeer(e){this._setupDC(e);const{asn:t,country:i}=this.engine.fetcher.announceInfo;e.sendMetaData(this.bitset.allArray(),!0,this.peersNum,{asn:t,country:i},this.isMobileNet)}_receiveDCHave(e,t,i,r){this.bitset.has(e,t)||this.bitCounts.incre(e,t)}_setupDC(e){super._setupDC(e),e.on(t.DC_HAVE,(t=>{if(e.bitset&&t.sn>=0){const{sn:i,level:r,complete:n,seg_id:s,size:a}=t,o=n?$t.COMPLETE:$t.PARTIAL_FORWARD;e.bitset.add(i,r,s,o,a),this._receiveDCHave(i,r,s,e),e.isAvailableUrgently&&this._handleDCHave(e,i,r,s,a,o)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:i,level:r,seg_id:n,size:s}=t;e.bitset.hasCompleteOr(i,r,$t.PARTIAL_REVERSE)||e.bitset.add(i,r,n,$t.PARTIAL_REVERSE,s),this._receiveDCHave(i,r,n,e),e.isAvailableUrgently&&this._handleDCHave(e,i,r,n,s,$t.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:i,level:r}=t;e.bitset.has(i,r)&&(e.bitset.delete(i,r),this.bitCounts.decre(i,r))})).on(t.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=7||this.requestingMap.has(ue(e.sn,e.level))&&this.notifyAllPeers(e.sn,e.level,e.seg_id,e.size,e.reverse?$t.PARTIAL_REVERSE:$t.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:i,level:r}=t,n=ue(i,r);this.removeStreamListener(n,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:i,level:r}=t;e.bitset.delete(i,r),this.bitCounts.decre(i,r),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:i}=this,{sn:r,level:n,reverse:s}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(r));const o=()=>{this.bitset.delete(r,n),e.sendPieceNotFound(r,a,{level:n}),this._broadcastLost(r,a,n,e)},l=await this.bufMgr.getSegById(a),h=ue(r,n),u=this.requestingMap.get(h);let d=!1;u&&u.isDownloading&&(d=!0);const c=this.segmentBuilderMap.get(h);if(l)if(i.info(`found seg ${a} from bufMgr`),l.level===n){let t="SegmentStore"===this.bufMgr.name?"Disk":"Cache";l.ext&&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:s})}else o();else if(!s&&c)i.info(`peer request ${r} wait from builder, sent ${c.bufferList.length}`),R(e,c,c.pieceMsg,c.bufferList,c.source,1);else if(d){i.info(`syn had ${u.loadedPackets} packets, wait remain from upstream ${u.getFromPeerId()}`);const t={...u.pieceMsg,reverse:s},{from:r,incompletes:n,bufferList:a}=u.getStreamInfo(s);R(e,u,t,a,r,n)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new zt(this.config.live,t.field);for(let e in t.field){const i=Number(e);if(i<0)continue;t.field[i].forEach((e=>{this.bitset.has(e,i)||this.bitCounts.incre(e,i)}))}this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e)}}peersHas(e,t){return this.bitCounts.has(e,t)}deletePeer(e){if(this.peerManager.hasPeer(e.remotePeerId)&&e.bitset){const t=e.bitset.allArray();for(let e in t){const i=Number(e),r=t[i];r&&r.forEach((e=>{this.bitCounts.decre(e,i)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,i,r){const{logger:n,config:s}=this;let a=1e3*(r-s.httpLoadTime);this.allowP2pLimit=s.httpLoadTime+1.5,n.info(`bufferedDuration ${1e3*r} remainLoadTime ${a} allowP2pLimit ${1e3*this.allowP2pLimit}`);const o=ue(e,t),l=this.requestingMap.get(o);if(l){const s=l.segId;if(s&&s!==i)return n.warn(`syn segId ${s} not match ${i}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,i,r);if(!l.shouldWaitForRemain(a)){if(n.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const r=this.peerManager.getPeersOrderByWeight();let[s,o,h]=jt(r,e,t,i);return!!this.setTargetPeersFromGroup(l,s,o,h)||(l.hasReversePeer||l.hasPartialBuffer||a>1e3*(this.allowP2pLimit+1))&&this.httpRangeSupported}return n.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t,i,r)}_searchAvailablePeers(e,t,i,r){if(r<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const n=this.peerManager.getPeersOrderByWeight(),[s,a]=qt(n,e,t,i);return this.targetPeers={forwardPeer:s,reversePeer:a},[s,a].some((e=>!!e))}reportTraffic(e,t,i){const{fetcher:r}=this.engine;r&&(e>0&&r.reportFlow(e),t>0&&r.reportDCTraffic(t,i))}notifyAllPeers(e,t,i,r,n=$t.COMPLETE){if(!i)return void this.logger.error("segId is required");if(this.downloadOnly)return;const{live:s}=this.config;if(this.bitset.has(e,t,n))return;const a=((e,t,i)=>`${e}-${t}-${i}`)(e,t,n);let o;n!==$t.PARTIAL_REVERSE&&(o=n===$t.COMPLETE);const l=this.requestingMap.get(ue(e,t));for(let h of this.getPeers())l&&l.hasPeer(h)||h.notifySet.has(a)||h.bitset.hasCompleteOr(e,t,n)||h.uploading||(h.sendMsgHave(e,i,{level:t,reverse:n===$t.PARTIAL_REVERSE,complete:o,size:r}),h.notifySet.add(a),s&&T(h.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:i}=this;if(!this.hasPeers)return;const r=t.live;if(this.fragLoading)return void e.info("loading urgently, skip prefetch");const{currentLevel:n}=i;if(0===this.bitCounts.size(n))return;if(!r&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;let s=this.peerManager.getPeersOrderByWeight();if(0===s.length)return;let a=0,{prefetchNum:o,endSN:l,startSN:h}=t;if(!r){const t=this.requestingMap.size,i=this.requestingMap.activePeers;if(i>=o)return void e.warn(`requestingMap size ${t} activePeers ${i}`);o-=i}if(this.getBufferedDuration()<this.allowP2pLimit){if(!r)return;o=1}let u=0,d=this.loadingSN+1;if(this.prefetchOnly&&(d+=2),!r)if(this.loadingSN>=l&&!this.bufMgr.overflowed)d=h;else{const e=Math.min(...s.filter((e=>e.endSN>=d)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;d<e&&(d=e)}for(;a<o&&u<this.maxPrefetchCount&&(r||!(d>l))&&!(r&&d>this.loadingSN+2);){if(this.bitset.has(d,n)){d++;continue}const t=ue(d,n),i=this.requestingMap.get(t);if(this.bitCounts.has(d,n)){if(i){for(let e of s)if(e.bitset.has(d,n)){const{state:t,segId:r,size:s}=e.bitset.getObj(d,n);if(this._trySetPeerForSyn(i,e,r,d,n,s,t))break}}else{let i=[null,null];if(r)i=qt(s,d,n,void 0,!0);else for(let e of s)if(e.bitset.has(d,n)){const t=e.bitset.getState(d,n);let r;r=t===$t.COMPLETE?0===p(0,1):t===$t.PARTIAL_REVERSE,i[r?1:0]=e;break}if(i.some((e=>!!e))){const r=new fi(this.coordinator,this.logger,d,n,void 0,this.httpRangeSupported);this._setupSynthesizer(r),this.requestingMap.set(t,r),i.forEach(((t,i)=>{if(t&&a<o){const s=1===i,o=t.bitset.getSize(d,n);r.setPeer(t,s,o)&&(a++,t.requestDataBySN(d,!1,{level:n,reverse:s}),e.info(`request prefetch ${d} level ${n} from peer ${t.remotePeerId} downloadNum ${t.downloadNum} reverse ${s}`))}}))}}s=this.peerManager.getPeersOrderByWeight()}if(u++,d++,0===s.length)break}this.loadedPeerNum=a}onBufferManagerLost(e,t,i,r){this.currLostSN=e,i&&(this.nextLostSN=i),this.bitset.delete(e,r),this.bitCounts.delete(e,r)}onBufferManagerSegAdded(e){const{sn:t,segId:i,level:r,size:n}=e;this.notifyAllPeers(t,r,i,n),this.updateLoaded(t,r,i)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[i,r]of this.requestingMap.internalMap){const n=i.split("-"),s=Number(n[1]),a=Number(n[0]);r.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),r.deletePeer(t),this.bitCounts.decre(s,a),t.bitset.delete(s,a))}}updateLoaded(e,t,i){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,i,$t.COMPLETE),this.bitCounts.delete(e,t))}broadcastPlaylist(e,t){if(!this.config.live)return;const i=function(e){const t=e.split("\n");let i=0,r=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){i=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&r++;return i+r-1}(t);if(!this.isMobileNet)for(let r of this.getPeers())r.sendMsgPlaylist(e,t,i);this.playlistInfo.set(e,{seq:i,data:t})}async getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t,data:i}=this.playlistInfo.get(e),r=()=>{for(let i of this.getPeers()){const r=i.getLatestPlaylist(e,t);if(r)return this.playlistInfo.set(e,r),this.gotPlaylist=!0,r}return null};let n=r();return!n&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await v(240),this.gotPlaylist=!1,n=r()),n}getBufferedDuration(){const{config:e}=this;let{media:t,currentSrc:i}=this.engine;if(!t||t.src!==i&&0===t.currentTime){if(this.logger.info("try get video element"),t=se(this.config.mediaElem,i),!t)return 4;this.engine.media=t}let r=function(e){let t=0,i=e.currentTime,r=e.buffered;for(let e=r.length-1;e>=0;e--)if(i>=r.start(e)&&i<=r.end(e)){t=r.end(e)-i;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return r}destroy(){super.destroy(),this.requestingMap.clear(),this.segmentBuilderMap.clear(),this.engine.removeAllListeners(t.MEDIA_REBUFFER)}clearCache(){"SegmentStore"===this.bufMgr.name?this.engine.emit(t.BM_FATAL_ERROR):this.bufMgr.clear(),this.bitset.clear()}_handleSynOutput(e,t,i,r){this.logger.info(`syn output ${e} http ${t} p2p ${i} time ${r}`)}_handleSynError(e,t,i,r){const{logger:n,config:s}=this;n.warn(`SYN_ERROR ${t}-${i} code ${r}`),r!==ii&&e.hasPartialBuffer&&i>this.loadingSN?n.warn(`syn abort ${i} with partial buffer`):this.requestingMap.delete(ue(i,t)),s.live&&this.checkPeers()}_notifySynthesizer(e,t,i,r,n,s,a=!0){const o=this.requestingMap.get(ue(i,r));o&&this._trySetPeerForSyn(o,e,t,i,r,n,s,a)}_trySetPeerForSyn(e,t,i,r,n,s,a,o=!1){const{logger:l}=this,h=e.segId;if(i&&h&&i!==h)return l.warn(`notifySynthesizer segId ${i} not match ${h}`),!1;if(e.isFull)return!0;if(e.isAlmostDeadline)return!0;if(e.isEmpty){if(e.hasForwardBuffer&&c()){if(e.setReversePeer(t,s))return u(!0,o),!0}else if(e.hasReverseBuffer&&d()&&e.setForwardPeer(t,s))return u(!1,o),!0}else if(!e.hasForwardPeer&&d()){if(e.setForwardPeer(t,s))return u(!1,o),!0}else if(!e.hasReversePeer&&c()&&e.setReversePeer(t,s))return u(!0,o),!0;function u(e,s){s?t.requestDataById(i,r,!0,{level:n,reverse:e}):t.requestDataBySN(r,!1,{level:n,reverse:e})}function d(){return a===$t.PARTIAL_FORWARD||a===$t.COMPLETE}function c(){return a===$t.PARTIAL_REVERSE||a===$t.COMPLETE}return!1}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:i}=this.config;t||i||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,i={level:e};if(t&&!this.config.live){const{currentTime:e}=t;i.pos=Math.round(e)}return i}checkSynthesizer(e,t){const i=ue(e,t),r=this.requestingMap.get(i);r&&(0===r.streamListeners?(this.logger.info(`destroy syn ${i} without listeners`),this.requestingMap.delete(i)):this.logger.info(`keep syn ${i} with listeners`))}setupSynForLoad(e,t,i,r,n){const{forwardPeer:s,reversePeer:a}=this.targetPeers,o=ue(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(r):(l=new fi(this.coordinator,this.logger,e,t,i,this.httpRangeSupported,r),this._setupSynthesizer(l),this.requestingMap.set(o,l)),l.prefetchTimeout&&n<1e3*this.allowP2pLimit&&!s&&!a)return l.setTimeout(0);n>700&&(s&&l.setForwardPeer(s)&&s.requestDataById(i,e,!0,{level:t}),a&&l.setReversePeer(a)&&a.requestDataById(i,e,!0,{level:t,reverse:!0})),l.setTimeout(l.isEmpty?0:n,!0)}async disconnectLoadingPeer(){const e=await this.bufMgr.getSegById(this.loadingSegId);e&&e.fromPeerId&&e.fromPeerId.split(":").forEach((e=>{const t=this.peerManager.getPeer(e);t&&(this.logger.warn(`disconnect loading peer ${e}`),t.close(!0))}))}}class vi{constructor(t,i,r,n){this.bufferList=[],this.streamListeners=[],this.finished=!1,this.packetSize=u,this.attachments=n%this.packetSize==0?n/this.packetSize:Math.floor(n/this.packetSize)+1,this.pieceMsg={event:e.DC_PIECE,attachments:this.attachments,seg_id:r,sn:t,level:i,size:n,reverse:!1},this.sink=(0,a.h)(0),this.source="HttpStream"}receiveBytes(e,t){e.byteLength&&(this.sink=a.h.concat([this.sink,e]),this.bufferList.push(e),t&&(this.finished=!0),this._notifyStreamListeners(e))}getCompleteBuffer(){return this.sink.buffer}destroy(){this.finished||this._notifyStreamListenersAbort()}addStreamListener(e,t,i){this.streamListeners.push({handler:i,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:i}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((r=>r.peerId!==e||(r.handler(t,i,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let i of this.streamListeners){const{handler:r}=i;r(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:i}=this.pieceMsg;for(let r of this.streamListeners){const{handler:n}=r;n(t,i,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const mi=/^age:\s*[\d.]+\s*$/im;function yi(e,t,i,r){if(!e)return!1;const n=r&&r.code,s=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(n)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,s):s}const Ei=class{constructor(e){this.xhrSetup=e&&e.xhrSetup||null,this.stats=D(),this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.loader=null}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return n(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),n(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:s}=i.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&Number.isFinite(n)?n:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,s="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){const n=s||t.response;if(null!=n){i.loading.end=Math.max(self.performance.now(),i.loading.first);const s="arraybuffer"===t.responseType?n.byteLength:n.length;if(i.loaded=i.total=s,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(i,e,n,t),!this.callbacks)return;const o={url:t.responseURL,data:n,code:r};return void this.callbacks.onSuccess(o,i,e,t)}}const a=n.loadPolicy.errorRetry;yi(a,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(a):this.callbacks.onError({code:r,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(yi(e,this.stats.retry,!0))this.retry(e);else{const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=function(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}(e,i.retry),i.retry++,this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&mi.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 Si=class extends pi{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=I(t.segmentBypass)?t.segmentBypass:()=>!1,!0===this.config.httpStreamEnabled?this.streamEnabled=li():this.streamEnabled=!1}async handleGetMediaData(e,i){const{logger:r,engine:n,config:s}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return r.warn(`cannot get frag ${a}`),i.postMessage({action:t.SW_GET_MEDIA});n.currentLevelIndex=l.level;const{sn:h,level:u}=l,d=this.config.segmentId(String(u),h,a,o);if(n.segmentLoadCount++,this.segmentBypass(a,l.tagList))return r.info(`bypass frag ${a}`),i.postMessage({action:t.SW_GET_MEDIA});if(n.segmentLoadCount<s.startFromSegmentOffset)return this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout,!1);const c=d===this.loadingSegId;if(c&&(r.warn(`duplicate request ${d}`),this.prefetchOnly))return i.postMessage({action:t.SW_GET_MEDIA});this.loadingSN=h,n.bufMgr&&(n.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,r.info(`bufMgr found seg sn ${h} segId ${d} size ${l.loaded}`),n.emit(t.FRAG_LOADED,{url:a,sn:h,level:u,segId:d,loaded:l.loaded,duration:l.duration,byP2p:!0,fromPeerId:f.fromPeerId}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:f.data}});if(this.fragLoading=!0,this.prefetchOnly)return r.info(`prefetchOnly, skip p2p load ${d}`),this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout);let g=this.getBufferedDuration();g>this.fragloadTimeout&&(g=this.fragloadTimeout),r.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const v=ue(h,u);if(this.resolveMap.has(h)||c){let e=this.requestingMap.get(v);if(e||c){e&&this.httpRangeSupported&&(r.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let n=setTimeout((()=>{r.info(`notify seg ${h} timeout`),n=-1,i.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{n<0||e&&e.level===u&&(clearTimeout(n),r.info(`notify seg ${e.sn}`),i.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else r.warn(`${h} is requesting, fallback`),i.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,u,d,g)){await this._loadFragByP2p(l,i,h,d,a,u,o,p)||(r.warn(`p2p timeout switch to http load ${d}`),this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,i,d,a,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,i,r,n,s,a,o=!0){const{sn:l,level:u}=e,d=ue(l,u),c=f(n,h,!0),g={},p=this.streamEnabled&&o?new hi(g):new Ei(g);let v={url:c,responseType:"arraybuffer",..._(s)};const m={timeout:a,loadPolicy:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4}},E={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,i.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,i.postMessage({action:t.SW_GET_MEDIA})},onSuccess:async(s,a)=>{this.fragLoading=!1;const{data:o}=s;let h=a.loading.end-a.loading.start;if(this.logger.info(`HTTP loaded ${r} time ${h} speed ${o.byteLength/h}`),!await this.bufMgr.hasSegOfId(r)){const e=y(o).buffer,t=new z(l,r,e,"",u);await this.bufMgr.putSeg(t),this.reportTraffic(o.byteLength,0,0)}this.segmentBuilderMap.delete(d),e.segId=r,e.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:n,sn:l,level:u,segId:r,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:o}})}};if(this.streamEnabled&&o){let e;E.onBodyStart=t=>{!e&&t>0&&(this.notifyAllPeers(l,u,r,t,$t.PARTIAL_FORWARD),e=new vi(l,u,r,t),this.segmentBuilderMap.has(d)||this.segmentBuilderMap.set(d,e))},E.onUpdate=(t,i,n)=>{if(n)return this.logger.warn(`loadFragByHttp ${r} aborted`),void this.segmentBuilderMap.delete(d);e&&e.receiveBytes(t,i)}}p.load(v,m,E)}async _loadFragByP2p(e,i,r,n,s,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${r} segId ${n} level ${a}`);const u=await this.load(r,n,a,s,o,l);if(u&&u.data){const{data:o,fromPeerId:l,size:d}=u;if(h.info(`p2p loaded segId ${n} level ${a} size ${o.byteLength}`),!await this.bufMgr.hasSegOfId(n)){const e=new z(r,n,o,l,a);h.info(`bufMgr putSeg ${r} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:s,sn:r,level:a,segId:n,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(),i.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:o,size:d}}),!0}h.warn(`P2P timeout load segId ${n}`);const d=await this.bufMgr.getSegById(n);return!!d&&(this.fragLoading=!1,h.info(`already loaded seg sn ${r} segId ${n}`),i.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:d.data}}),!0)}notifySWMessage(e,i,r){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(i,r);else this.logger.warn(`unknown action ${e}`)}_getFrag(e,t){return t&&(e=`${e}|${t}`),this.fragMap.get(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(){if(!this.engine)return;const{media:e,targetDuration:t}=this.engine;!this.config.live&&e&&t&&(this.currPlaySN=Math.ceil(e.currentTime/t))}load(e,t,i,r,n,s){const{logger:a,config:o}=this;let l={..._(n),proxied:!0,url:r,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,i,t,l,s);const h=new Promise((r=>{const n={resolve:r,sn:e,level:i,segId:t};this.resolveMap.set(e,n)}));return this.targetPeers={},h}isCritical(){return this.resolveMap.has(this.loadingSN)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,i)=>{const{config:r,logger:n}=this,{segId:s,sn:a,data:o,level:l}=t,{speed:h,time:u,http:d,p2p:c}=i;this._handleSynOutput(s,d,c,u);const f=this.resolveMap.has(a);f&&(this.fragLoading=!1);if(r.validateSegment(s,new Uint8Array(o))){this.bitset.has(a,l)||this.reportTraffic(d,c,h);const i=e.getFromPeerId();if(f){n.info(`receive criticalSeg seg_id ${s}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:c>0?i:void 0})}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t))}else if(n.error(`segment ${s} validate failed`),f){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(ue(a,l)),r.live&&this.checkPeers()})).on(t.SYN_ERROR,((t,i)=>{const{sn:r,level:n}=t;if(this.resolveMap.has(r)){const e=this.resolveMap.get(r);this.resolveMap.delete(r),e.resolve()}this._handleSynError(e,n,r,i)}))}_handleDCHave(e,t,i,r,n,s){this._notifySynthesizer(e,r,t,i,n,s,this.resolveMap.has(t)),this.config.live&&W((()=>{this.checkPeers()}))}},Ti="2.13.0";class Li extends kt{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},i=null){super(e,i),this.swSupported=self.isSecureContext,this.levels=[],this.bypassLevels=[],this.currentLevelIndex=0,this.currentSrc="",this.swVersion="",this.media=se(this.config.mediaElem),this.workerKeepAliveInterval=null,this.fragMap=new Map,this.engineName=Li.name,Li.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),i&&(i.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),i.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:r,signalId:n,browserInfo:s}=this.setup();if(this.onLevelLoaded=e=>{const{config:i}=this,a=e.live;i.live=a,this.segmentLoadCount=0,this.targetDuration=e.averagetargetduration,this.browserInfo={...s,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${r(this.currentSrc)}|${n}[${Z.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsSwP2pEngine"),o.info(`engine version: ${re.version} hls-proxy version: ${this.swVersion}`),o.info(`channel ${this.channel}`),a||(i.startSN=e.startSN,i.endSN=e.endSN,o.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(t.LEVEL_LOADED,this.onLevelLoaded)},0===this.config.httpLoadTime&&(this.config.live?this.on(t.LEVEL_LOADED,(e=>{const{fragments:t,averagetargetduration:i,startSN:r}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,i,r)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,i)=>{this.multiBitrate=e.length>1,this.currentSrc=i,this.off(t.MANIFEST_PARSED,this.onManifestParsed)},this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{this.curTsUri=e;const{config:t}=this;!this.rangeTested&&t.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,t.logger&&t.logger.info(JSON.stringify({engine:this.engineName,...this.browserInfo}))),this.segmentLoadCount>=t.startFromSegmentOffset&&this.resumeTracker()},this.on(t.FRAG_LOADED,this.onFragLoaded),this.swSupported){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:i,data:r}=e.data;if(!i)return;if(i===t.SW_DEBUG){const{level:e,text:t}=r;return void(this.logger&&this.logger[e](`hls-proxy ${this.swVersion}: ${t}`))}const n=e.ports[0];if(n){if(this.logger&&this.logger.info(`engine onmessage action ${i}`),n.postMessage({action:i,pong:!0}),!this.p2pEnabled||!r)return n.postMessage({action:i});if(i===t.SW_GET_PLAYLIST)this.handleGetPlaylist(r,n);else{if(!this.scheduler)return n.postMessage({action:i});this.scheduler.notifySWMessage(i,r,n)}}else this.logger&&this.logger.error(`sender not found in action ${i}`)}}this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}watchRebuffering(e){this.offEventRebuffer=function(e,t){let i=null;const r=()=>{i||(i=setTimeout((()=>{t()}),2500))},n=()=>{null!=i&&(clearTimeout(i),i=null)};return e.addEventListener("waiting",r),e.addEventListener("playing",n),()=>{e.removeEventListener("waiting",r),e.removeEventListener("playing",n)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,i,r=!1){const{config:n,logger:s}=this,{url:a,redirectedUrl:o,text:l,ver:u}=e;return this.swVersion=u,-1===function(e,t){for(var i=e.split("."),r=t.split("."),n=0;n<Math.max(i.length,r.length);n++){var s=parseInt(i[n]||0),a=parseInt(r[n]||0);if(s<a)return-1;if(s>a)return 1}return 0}(u,Ti)?(console.warn(`hls-proxy.js version should >= ${Ti}`),i.postMessage({action:t.SW_GET_PLAYLIST})):this.bypassLevels.indexOf(b(a))>=0?(console.warn("bypass audio track"),s&&s.warn("bypass audio track"),i.postMessage({action:t.SW_GET_PLAYLIST})):(i.postMessage({action:t.SW_GET_PLAYLIST,data:{active:!0,debug:s&&s.isDebugLevel,text:l,redirectedUrl:o}}),this._parsePlaylist(l,b(a),o,r),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!n.live&&t()){const i=new URL(e.scope);this.pathname=i.pathname+h;const r=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;s&&(s.error(t),s.report(t,"SWKeepAlive",this.peerId,"2.14.4"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,i)=>{fetch(`${e}/keepalive/`).then((e=>{if(e.ok)return e.text();throw new Error("keepalive failed")})).then((e=>{if(""!==e.trim())throw new Error("not valid keepalive response");t()})).catch((e=>{i(e)}))}))).catch((e=>{r(e)})):r("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,i,r,n=!1){const s=i;r&&(i=r);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let r=0;const o=Kt.parseLevelPlaylist(e,i);this.levels.length>0?(r=this.levels.indexOf(b(o.url)),-1===r?(this.restartP2p(),this.currentSrc=s,r=0):this.currentLevelIndex=r):(""!==this.currentSrc&&s!==this.currentSrc&&this.restartP2p(),this.currentSrc=s,this.levels=[b(i)]),this.emit(t.LEVEL_LOADED,o),a.live&&S(this.fragMap,200),o.fragments.forEach((e=>{e.level=r;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const i=e.byteRange;2===i.length&&(t=`${t}|bytes=${i[0]}-${i[1]-1}`),this.fragMap.set(t,e)})),!n&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(b(i),e)}else{const r=Kt.parseMasterPlaylist(e,i);""!==this.currentSrc&&this.restartP2p(),r.length>0&&(r.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=r.map((e=>b(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{Kt.parseMasterPlaylistMedia(e,i,t).forEach((e=>{e.url&&this.bypassLevels.push(b(e.url))}))}))),this.emit(t.MANIFEST_PARSED,r,s)}this._setupSegmentId()}async handleGetPlaylist(e,i){const{config:r,logger:n,scheduler:s}=this,{url:a}=e,o=b(a);if(s&&s.playlistInfo.has(o)){const t=await s.getPlaylistFromPeer(o);if(t&&t.data){const{data:r,seq:s}=t;return n&&n.info(`got playlist from peer seq ${s}`),void this.handlePlaylist({text:r,...e},i,!0)}}try{const{text:r,redirectedUrl:s}=await this._loadPlaylistByHttp(a);if(!function(e){return 0===e.indexOf("#EXTM3U")}(r))return n&&n.warn(`not m3u8: ${r}`),i.postMessage({action:t.SW_GET_PLAYLIST});this.handlePlaylist({text:r,redirectedUrl:s,...e},i)}catch(e){i.postMessage({action:t.SW_GET_PLAYLIST})}}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let e="sw is not supported";return E||(e="https is required when using ServiceWorker",console.warn(e)),Promise.reject(e)}return this.media=se(t.mediaElem),this.media||e&&e.warn("no video element found"),Di.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,i)=>{const{serviceWorker:r}=navigator;r||i(e),r.getRegistration().then((r=>{r?r.unregister().then(t).catch(i):i(e)}))}))}async _init(e,t){const{logger:i,config:r}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.mediaTimer=setInterval((()=>{const e=()=>this.hlsjs&&this.hlsjs.media;if(this.media){const t=e();t&&this.media!==t&&(this.media=t),clearInterval(this.mediaTimer),this.rubufferTimer=setTimeout((()=>{this.watchRebuffering(this.media)}),15e3)}else this.media=e()||se(r.mediaElem)}),3e3);let n=new Si(this,r);n.fragMap=this.fragMap;try{await super._init(e,n,t)}catch(e){return void(i&&i.error(e))}n.server=this.fetcher,this.scheduler=n}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 Pt&&(this.tracker.stopP2P(),this.tracker=null,this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.trackerTried=!1)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(t.MANIFEST_PARSED),this.removeAllListeners(t.LEVEL_LOADED),this.removeAllListeners(t.FRAG_LOADED),clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null}destroy(){this.swSupported&&(navigator.serviceWorker.onmessage=void 0),super.destroy()}async _loadPlaylistByHttp(e){const t=f(e,h,!0),i=await fetch(t);return{text:await i.text(),redirectedUrl:i.redirected?i.url:void 0}}}const _i=Li;function bi(e,t,i="main"){return"main"!==i}function Ai(e,t,i){let r,n,s;const a=performance.now();s=a,n=i?s-i.getMeanTimeToLoaded(t):a-200,r=n-100,e.trequest=r,e.tfirst=n,e.tload=s,e.loading={first:r,start:n,end:s},e.loaded=t,e.total=t}const Ii=class extends pi{constructor(e,t){super(e,t),this.isHlsjs=!0,this.waitingPeers=0,this.waitingSeg={},this.requestedSet=new Set}updatePlaySN(e){this.currPlaySN=e}load(e,t,i){const{logger:r,config:n}=this;this.context=e;const{rangeStart:s,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:u,level:d}=l;this.callbacks=i,this.criticalSeg={sn:u,level:d,segId:h};let c=e.defaultTimeout-1e3*n.httpLoadTime;const f={rangeStart:Number(s),rangeEnd:Number(a),url:o,httpLoadTime:1e3*n.httpLoadTime,xhrSetup:n.xhrSetup,segId:h,headers:Object.keys(e.headers||{}).length>0?e.headers:void 0};this.setupSynForLoad(u,d,h,f,c),this.targetPeers={}}isCritical(){return!(!this.criticalSeg||this.criticalSeg.segId!==this.loadingSegId)}addPeer(e){super.addPeer(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler")}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,i)=>{const{config:r,logger:n}=this,{segId:s,sn:a,data:o,level:l}=t,{speed:h,time:u,http:d,p2p:c}=i;this._handleSynOutput(s,d,c,u);const f=this.criticalSeg&&this.criticalSeg.segId===s;if(r.validateSegment(s,new Uint8Array(o))){this.bitset.has(a,l)||this.reportTraffic(d,c,h);const i=e.getFromPeerId();if(f){n.info(`receive criticalSeg seg_id ${s}`),this.criticalSeg=null;const{frag:e}=this.context;c>0&&(e.fromPeerId=i,e.loadByP2P=!0),this.callbacks.onSuccess({data:o,url:this.context.url},{},this.context),this.callbacks=void 0}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t))}else n.error(`segment ${s} validate failed`),f&&this.callbacks.onTimeout({},this.context,null);this.requestingMap.delete(ue(a,l)),r.live&&this.checkPeers()})).on(t.SYN_ERROR,((t,i)=>{const{sn:r,level:n}=t;this.criticalSeg&&this.criticalSeg.sn===r&&(this.criticalSeg=null,this.callbacks.onTimeout({},this.context,null)),this._handleSynError(e,n,r,i)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:i,segId:r})=>{this.criticalSeg&&this.criticalSeg.segId===r&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:i},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:i,level:r})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,i&&this.checkSynthesizer(e,r)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:i,level:r})=>{this.fragLoading=!1,i||this.checkSynthesizer(e,r)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,i,r,n,s){this._notifySynthesizer(e,r,t,i,n,s,this.criticalSeg&&this.criticalSeg.segId===r),this.config.live&&W((()=>{this.checkPeers()}))}};class Ri extends kt{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=Ri.name,this._onFragLoading=this._onFragLoading.bind(this),this._onFragLoaded=this._onFragLoaded.bind(this),this._onFragChanged=this._onFragChanged.bind(this),this._onHlsError=this._onHlsError.bind(this),this._onLevelUpdated=this._onLevelUpdated.bind(this);const{channelIdMaker:i,signalId:r,browserInfo:n}=this.setup(),s=(t,a)=>{if(!a)return;const{config:o}=this,l=a.details,h=l.live;this._startEngine(this.hlsjs.url,h,n,i,r,l),e.off(this.HLSEvents.LEVEL_LOADED,s)};this._updateHlsEventsHandlers(),e.on(this.HLSEvents.LEVEL_LOADED,s);const a=(e,t)=>{if(!t)return;const{config:i}=this,{fragments:r,averagetargetduration:n,startSN:s}=t.details;i.httpLoadTime=this.determineHttpLoadTime(r,n,s)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,i)=>{this._setupSegmentId();const r=i.levels.length;this.multiBitrate=r>1,e.off(this.HLSEvents.MANIFEST_PARSED,o)};e.on(this.HLSEvents.MANIFEST_PARSED,o),e.on(this.HLSEvents.DESTROYING,(()=>{e.off(this.HLSEvents.LEVEL_LOADED,a),this.destroy()}))}_startEngine(e,t,i,r,n,s={}){const{config:a}=this;a.live=t,this.browserInfo={...i,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${r(e)}|${n}[${Z.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsjsP2pEngine"),this.logger=o,o.info(`channel ${this.channel}`),t||(a.startSN=s.startSN,a.endSN=s.endSN,o.info(`startSN ${s.startSN} endSN ${s.endSN}`)),this._init(this.channel,this.browserInfo)}async _init(e,t){const{logger:i,config:r}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const n=new Ii(this,r);try{await super._init(e,n,t)}catch(e){return void i.error(e)}this.hlsjs.config.fLoader=function(e,t,i,r){const n=r.httpStreamEnabled&&li();return class extends(s()){constructor(s){super(),this.logger=i,this.isHlsV0=r.isHlsV0,this.bufMgr=e.bufMgr,this.httpLoader=n?new hi(s):new Ei(s),this.p2pEnabled=r.p2pEnabled,this.isLive=r.live,this.scheduler=e,this.fetcher=t,this.segmentId=r.segmentId,this.blockTypes=r.p2pBlackList,this.stats=this.httpLoader.stats||D(),this.enableWorker=s.enableWorker,this.segmentBypass=I(r.segmentBypass)?r.segmentBypass:()=>!1,this.prefetchOnly=r.prefetchOnly,this.startFromSegmentOffset=r.startFromSegmentOffset}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,i){const{logger:r,scheduler:n}=this,{url:s,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,s,t)}const c=()=>(a.loadByHTTP=!0,this.httpLoader.load(e,t,i));if(!s||!Number.isInteger(l)||bi(0,this.blockTypes,h)||this.segmentBypass(s,u))return r.info(`HTTP load blockType ${s}`),c();if(this.fetcher.increMediaRequests(),this.isLive&&n.requestedSet.has(d))return r.warn(`HTTP load duplicated ${s}`),c();if(n.engine.segmentLoadCount<this.startFromSegmentOffset)return c();t.maxRetry=2;const f=n.getBufferedDuration(),g=await this.bufMgr.getSegById(d);if(this.p2pEnabled&&g){r.info(`bufMgr found seg sn ${l} segId ${d} level ${o} size ${g.size}`);let t=y(g.data).buffer,s={url:e.url,data:t};return Ai(this.stats,g.size,n.coordinator),a.loaded=g.size,a.loadByP2P=!0,a.fromPeerId=g.fromPeerId,void W((()=>{!this.isHlsV0&&i.onProgress&&i.onProgress(this.stats,e,s.data),i.onSuccess(s,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&n.hasAndSetTargetPeer(l,o,d,f)?this.loadFragByP2p(e,t,i,d,f):(r.info(`fragLoader load ${d} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,i,d))}loadFragByHttp(e,t,i,r){const{logger:s,scheduler:a}=this,{segmentBuilderMap:o}=a,l=e.frag,{sn:h,level:u}=l,d=ue(h,u);if(n){let e;i.onUpdate=(t,i,n)=>{if(n)return s.warn(`loadFragByHttp ${r} aborted`),void o.delete(d);e&&e.receiveBytes(t,i)},i.onBodyStart=t=>{!e&&t>0&&(e=new vi(h,u,r,t),o.has(d)||o.set(d,e),a.notifyAllPeers(h,u,r,t,$t.PARTIAL_FORWARD))}}const c=i.onSuccess;i.onSuccess=async(e,t,i)=>{a.coordinator.addLoaderHttpSpeed(t.tload-t.tfirst,t.loaded);const{data:n}=e;let l=t.tload-t.trequest;if(s.info(`HTTP loaded ${r} time ${l} speed ${t.total/l}`),!await this.bufMgr.hasSegOfId(r)){const e=y(n).buffer,t=new z(h,r,e,this.fetcher.peerId,u);await this.bufMgr.putSeg(t)}o.delete(d),this.fetcher.reportFlow(t.total),c(e,t,i)};const f=i.onProgress;f&&(i.onProgress=(e,t,i)=>{l.loaded=e.total,f(e,t,i&&this.enableWorker?y(i).buffer:i)}),e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,i)}loadFragByP2p(t,i,r,n,s){const{logger:a}=this,o=t.frag;let l;l=i.loadPolicy?i.loadPolicy.maxTimeToFirstByteMs:i.timeout,(!l||l>1e3*s)&&(l=1e3*s),t.defaultTimeout=l,this.scheduler.load(t,i,r);const h=r.onSuccess,u=r.onTimeout;r.onTimeout=(e,t)=>{a.warn(`P2P timeout switched to HTTP load ${o.relurl} at ${o.sn}`),r.onSuccess=h,this.loadFragByHttp(t,i,r,n),r.onTimeout=u},r.onSuccess=async(t,i,s)=>{const{data:l}=t;if(Ai(i=this.stats,l.byteLength,e.coordinator),!await this.bufMgr.hasSegOfId(n)){const e=y(l).buffer,t=new z(o.sn,n,e,o.fromPeerId||this.fetcher.peerId,o.level);await this.bufMgr.putSeg(t)}o.loadByP2P||this.fetcher.reportFlow(i.total),o.loaded=i.loaded,a.info(`${o.loadByP2P?"P2P":"HTTP"} loaded segment id ${n}`),!this.isHlsV0&&r.onProgress&&r.onProgress(i,s,l),h(t,i,s)}}}}(n,this.fetcher,i,r),r.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,i){return class extends(s()){constructor(r){super(),this.logger=t,this.xhrLoader=new r.loader(r),this.p2pEnabled=i.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||D()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,i){const{logger:r}=this,{url:n}=e,s=b(n),a=i.onSuccess;if(i.onSuccess=(e,t,i)=>{this.scheduler&&!i.loadedByPeer&&this.scheduler.broadcastPlaylist(s,e.data),a(e,t,i)},this.scheduler&&this.scheduler.playlistInfo.has(s)){const t=await this.scheduler.getPlaylistFromPeer(s);if(t&&t.data){const{data:s,seq:a}=t;r.info(`got playlist from peer seq ${a}`),Ai(this.stats,s.length);let o={url:n,data:s};return e.loadedByPeer=!0,void W((()=>{i.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,i)}}}(n,i,r))}_onFragLoading(e,i){const r=i.frag;let{sn:n,level:s,segId:a}=r;if(!bi(r.url,this.config.p2pBlackList,r.type)&&Number.isInteger(n)){if(this.logger&&this.logger.info("loading frag "+n),this.bufMgr&&(this.bufMgr.loadingSN=n),!a){let e;r._byteRange&&(e="bytes="+r._byteRange[0]+"-"+r._byteRange[1]);let t=r.url;this._setupSegmentId(),a=r.segId=this.config.segmentId(String(s),r.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:n,segId:a,byHttp:r.loadByHTTP,level:s})}}_onLevelUpdated(e,t){const{details:i}=t,{hlsjs:r,config:n}=this,{targetduration:s,live:a,fragments:o}=i,l=o.length;if(a&&r&&"main"===o[0].type&&!(l<=4)&&(n.isHlsV0||!r.userConfig.liveSyncDuration&&!r.userConfig.liveSyncDurationCount)){const e=l<=9?l-1:l-2;r.config.liveSyncDurationCount!==e&&(r.config.liveSyncDurationCount=e)}}_onFragLoaded(e,i){if(this.segmentLoadCount++,!this.p2pEnabled)return;const{frag:r}=i;this.curTsUri=r.url;const{sn:n,segId:s,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:u,url:d}=r,{config:c,logger:f}=this;this.tracker&&this.tracker.scheduler&&(T(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(s)),bi(r.url,c.p2pBlackList,r.type)||(this.bufMgr&&this.bufMgr.loadingSN>=0&&this.emit(t.FRAG_LOADED,{url:d,sn:n,level:l,segId:s,loaded:a,duration:o,byP2p:!!u,fromPeerId:h}),!this.rangeTested&&c.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,f.info(JSON.stringify({engine:this.engineName,hlsjs:this.hlsjsVersion,...this.browserInfo})))),this.segmentLoadCount>=c.startFromSegmentOffset&&this.resumeTracker()}_onFragChanged(e,i){const{frag:r}=i;if(!bi(r.url,this.config.p2pBlackList,r.type)){this.logger.info("frag changed: "+r.sn);const{sn:e,duration:i}=r;this.emit(t.FRAG_CHANGED,{sn:e,duration:i})}}get currentLevel(){const{currentLevel:e}=this.hlsjs;return e>=0?e:0}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}_updateHlsEventsHandlers(e=!1){const t=this.hlsjs;if(!t)return;const i=e?"off":"on";t[i](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[i](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[i](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[i](this.HLSEvents.ERROR,this._onHlsError),t[i](this.HLSEvents.LEVEL_UPDATED,this._onLevelUpdated)}destroy(){this._updateHlsEventsHandlers(!0),super.destroy()}_setupSW(){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:t}=e.data,i=e.ports[0];if(i)return i.postMessage({action:t,pong:!0}),i.postMessage({action:t,data:{bypass:!0}})}}}const Pi=Ri;class ki{static get Events(){return t}static get TrackerZone(){return re.TrackerZone}static isSupported(){return re.isSupported()&&(ne()||_i.isServiceWorkerSupported())}static isServiceWorkerSupported(){return _i.isServiceWorkerSupported()}static isMSESupported(){return ne()}static getBrowser(){return Q().getBrowser()}static get ServiceWorkerEngine(){return _i}static get HlsjsEngine(){return Pi}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return ki.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:i}={}){const{serviceWorker:r}=navigator;return!r||i?Promise.resolve():r.getRegistration().then((i=>i||Promise.race([r.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,i)=>{const r=e.installing||e.waiting||e.active,n=()=>"activated"===r.state&&(r.removeEventListener("statechange",n),t(e),!0);n()||r.addEventListener("statechange",n)}))}(e))).catch((()=>{Promise.resolve()})),v(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const i=()=>{this._realEngine=new Pi(t,e)},r=()=>{this._realEngine=new _i(e,t)};"1"!==c("_sw")?e.proxyFirst&&t?_i.isServiceWorkerSupported()?r():i():!e.proxyOnly&&ne()&&t?i():r():r()}get realEngine(){return this._realEngine}get engineName(){return this._realEngine.constructor.name}once(e,t){return this._realEngine.once(e,t)}on(e,t){return this._realEngine.on(e,t)}off(e,t){return this._realEngine.off(e,t)}removeListener(e,t){return this._realEngine.removeListener(e,t)}removeAllListeners(e){return this._realEngine.removeAllListeners(e)}set p2pEnabled(e){this._realEngine.p2pEnabled=e}get p2pEnabled(){return this._realEngine.p2pEnabled}enableP2P(){this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}async registerServiceWorker(){return I(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return I(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return re.version}}ki.version=re.version,ki.protocolVersion=Z.VERSION,"object"==typeof self&&(self.P2PEngineHls=ki);const Di=ki;var wi=i(251),Ci=i.n(wi);const Mi={maxBufferLength:12},Oi={maxBufferLength:40};class xi extends(Ci()){static get P2PEvents(){return Di.Events}static get P2pEngine(){return Di}constructor(e={}){let t=e.p2pConfig||{};const i=!1===t.live?Oi:Mi;let r=JSON.parse(JSON.stringify(i));r.maxBufferSize=0,r.enableWorker=!1;for(let t in e)"p2pConfig"!==t&&(r[t]=e[t]);super(r),this._restartEvent=()=>{this.restartP2P()},Di.isSupported()&&(this._p2pEngine=new Di({...t,hlsjsInstance:this}),this._p2pEngine.on(Di.Events.RESTART_P2P,this._restartEvent)),this.on(Ci().Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(Di.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(Di.Events.RESTART_P2P,this._restartEvent))}}xi.engineVersion=Di.version,xi.protocolVersion=Di.protocolVersion,xi.WEBRTC_SUPPORT=Di.isSupported();const Fi=xi})(),r=r.default})()));