@ezuikit/player-ezopen 9.0.6-beta.5 → 9.0.6

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.
@@ -1,6 +1,6 @@
1
1
  /*
2
2
  *
3
- * JsPlugin.js v9.0.6-beta.5
3
+ * JsPlugin.js v9.0.6
4
4
  * Copyright (c) 2026-7-13 Ezviz-OpenBiz
5
5
  * Released under MIT the License.
6
6
  *
@@ -13,7 +13,7 @@ import deepmerge from"deepmerge";import Logger$1 from"@ezuikit/utils-logger";imp
13
13
  */Logger.NOOP=function(){},Logger.LEVEL={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},(
14
14
  /*
15
15
  * @skax/hls-io v0.1.0-beta.2
16
- * Copyright (c) 2026-05-17
16
+ * Copyright (c) 2026-05-17
17
17
  * Released under the MIT License.
18
18
  */
19
19
  HLSTag={}).EXTM3U="#EXTM3U",HLSTag.EXTINF="#EXTINF",HLSTag.EXT_X_BYTERANGE="#EXT-X-BYTERANGE",HLSTag.EXT_X_DISCONTINUITY="#EXT-X-DISCONTINUITY",HLSTag.EXT_X_KEY="#EXT-X-KEY",HLSTag.EXT_X_MAP="#EXT-X-MAP",HLSTag.EXT_X_PROGRAM_DATE_TIME="#EXT-X-PROGRAM-DATE-TIME",HLSTag.EXT_X_DATERANGE="#EXT-X-DATERANGE",HLSTag.EXT_X_TARGETDURATION="#EXT-X-TARGETDURATION",HLSTag.EXT_X_MEDIA_SEQUENCE="#EXT-X-MEDIA-SEQUENCE",HLSTag.EXT_X_DISCONTINUITY_SEQUENCE="#EXT-X-DISCONTINUITY-SEQUENCE",HLSTag.EXT_X_ENDLIST="#EXT-X-ENDLIST",HLSTag.EXT_X_PLAYLIST_TYPE="#EXT-X-PLAYLIST-TYPE",HLSTag.EXT_X_I_FRAMES_ONLY="#EXT-X-I-FRAMES-ONLY",HLSTag.EXT_X_MEDIA="#EXT-X-MEDIA",HLSTag.EXT_X_STREAM_INF="#EXT-X-STREAM-INF",HLSTag.EXT_X_I_FRAME_STREAM_INF="#EXT-X-I-FRAME-STREAM-INF",HLSTag.EXT_X_SESSION_DATA="#EXT-X-SESSION-DATA",HLSTag.EXT_X_SESSION_KEY="#EXT-X-SESSION-KEY",HLSTag.EXT_X_INDEPENDENT_SEGMENTS="#EXT-X-INDEPENDENT-SEGMENTS",HLSTag.EXT_X_START="#EXT-X-START",HLSTag.EXT_X_VERSION="#EXT-X-VERSION",HLSTag.EXT_X_SERVER_CONTROL="#EXT-X-SERVER-CONTROL",HLSTag.EXT_X_PART="#EXT-X-PART",HLSTag.EXT_X_PART_INF="#EXT-X-PART-INF",HLSTag.EXT_X_PRELOAD_HINT="#EXT-X-PRELOAD-HINT",HLSTag.EXT_X_RENDITION_REPORT="#EXT-X-RENDITION-REPORT",HLSTag.EXT_X_SKIP="#EXT-X-SKIP",HLSTag.EXT_X_GAP="#EXT-X-GAP",HLSTag.EXT_X_BITRATE="#EXT-X-BITRATE",HLSTag.EXT_X_ALLOW_CACHE="#EXT-X-ALLOW-CACHE",HLSTag.EXT_X_CONTENT_STEERING="#EXT-X-CONTENT-STEERING";var SegmentFormat,PlaylistType=function(PlaylistType){return PlaylistType.LIVE="LIVE",PlaylistType.VOD="VOD",PlaylistType}({});(SegmentFormat={}).TS="ts",SegmentFormat.FMP4="fmp4";var EncryptionMethod=function(EncryptionMethod){return EncryptionMethod.NONE="NONE",EncryptionMethod.AES_128="AES-128",EncryptionMethod.SAMPLE_AES="SAMPLE-AES",EncryptionMethod}({}),KeyFormat=function(KeyFormat){return KeyFormat.IDENTITY="identity",KeyFormat.COMMON_ENCRYPTION="com.apple.streamingkeydelivery",KeyFormat}({}),DEFAULT_CONFIG={url:"",playlistType:"LIVE",bufferAhead:5,maxCacheSize:50,heartbeatInterval:3e4,playlistRefreshInterval:0,fetchOptions:{},resolveRelativeUris:!0,baseUrl:"",debug:!1,lowLatencyMode:!1,partTargetDuration:0,onLastSegment:function(){},cachePolicy:"lru",followRedirectUrl:!0,timeout:3e4,segmentRetryCount:5,segmentTimeout:0,segmentRetryDelay:500,segmentRetryBackoff:2},HlsIOEvents=function(HlsIOEvents){return HlsIOEvents.PLAYLIST_LOADED="playlistLoaded",HlsIOEvents.SEGMENTS_UPDATED="segmentsUpdated",HlsIOEvents.SEGMENT_READY="segmentReady",HlsIOEvents.LAST_SEGMENT="lastSegment",HlsIOEvents.ERROR="error",HlsIOEvents.HEARTBEAT="heartbeat",HlsIOEvents.PLAYLIST_TYPE_DETECTED="playlistTypeDetected",HlsIOEvents.DISCONTINUITY="discontinuity",HlsIOEvents.ENDED="ended",HlsIOEvents.MANIFEST_PARSED="manifestParsed",HlsIOEvents.DECRYPTING="decrypting",HlsIOEvents.DECRYPTED="decrypted",HlsIOEvents.PART_SEGMENT="partSegment",HlsIOEvents.MAP_LOADED="mapLoaded",HlsIOEvents.BUFFER_STALL="bufferStall",HlsIOEvents.DURATION_UPDATED="durationUpdated",HlsIOEvents.BUFFERED_TIME_UPDATED="bufferedTimeUpdated",HlsIOEvents.TIMEOUT="timeout",HlsIOEvents}({});function _array_like_to_array$4(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function asyncGeneratorStep$4$1(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$4$1(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$4$1(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$4$1(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _extends$4$1(){return _extends$4$1=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$4$1.apply(this,arguments)}function _instanceof$1(left,right){return null!=right&&"undefined"!=typeof Symbol&&right[Symbol.hasInstance]?!!right[Symbol.hasInstance](left):left instanceof right}function _ts_generator$4$1(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var Fetcher=function(){function Fetcher(fetchOptions,debug,timeout){void 0===fetchOptions&&(fetchOptions={}),void 0===debug&&(debug=!1),void 0===timeout&&(timeout=3e4),this._heartbeatTimer=null,this._abortControllers=new Map,this._logger=new Logger("HLS-IO:Fetcher",debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),this._fetchOptions=_extends$4$1({mode:"cors",credentials:"omit"},fetchOptions),this._timeout=timeout}var _proto=Fetcher.prototype;return _proto.startHeartbeat=function(url,intervalMs,callback){var _this=this;this.stopHeartbeat(),this._logger.info("Starting heartbeat every "+intervalMs+"ms to "+url),this._heartbeatTimer=setInterval(function(){return _async_to_generator$4$1(function(){var controller,timeoutId,response,error;return _ts_generator$4$1(this,function(_state){switch(_state.label){case 0:return _state.trys.push([0,2,,3]),controller=new AbortController,timeoutId=setTimeout(function(){return controller.abort()},5e3),[4,fetch(url,_extends$4$1({method:"HEAD",signal:controller.signal},this._fetchOptions))];case 1:return response=_state.sent(),clearTimeout(timeoutId),response.ok?callback(Date.now()):this._logger.warn("Heartbeat failed with status "+response.status),[3,3];case 2:return error=_state.sent(),this._logger.warn("Heartbeat error: "+error.message),[3,3];case 3:return[2]}})}).call(_this)},intervalMs)},_proto.stopHeartbeat=function(){this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null,this._logger.info("Heartbeat stopped"))},_proto.isHeartbeatActive=function(){return null!==this._heartbeatTimer},_proto.fetch=function(url,options){return _async_to_generator$4$1(function(){var _ref,fetchOptionsHeaders,headers,optionsHeaders,headers1,mergedOptions,controller,timeoutId,effectiveTimeout,response,err;return _ts_generator$4$1(this,function(_state){switch(_state.label){case 0:if(fetchOptionsHeaders={},_instanceof$1(this._fetchOptions.headers,Headers))this._fetchOptions.headers.forEach(function(value,key){fetchOptionsHeaders[key]=value});else if(this._fetchOptions.headers)for(var key in headers=this._fetchOptions.headers)Object.prototype.hasOwnProperty.call(headers,key)&&(fetchOptionsHeaders[key]=headers[key]);if(optionsHeaders={},_instanceof$1(null==options?void 0:options.headers,Headers))options.headers.forEach(function(value,key){optionsHeaders[key]=value});else if(null==options?void 0:options.headers)for(var key1 in headers1=options.headers)Object.prototype.hasOwnProperty.call(headers1,key1)&&(optionsHeaders[key1]=headers1[key1]);mergedOptions=_extends$4$1({},this._fetchOptions,options,{headers:_extends$4$1({},fetchOptionsHeaders,optionsHeaders)}),controller=new AbortController,this._abortControllers.set(url,controller),timeoutId=null,(effectiveTimeout=null!=(_ref=null==options?void 0:options.timeout)?_ref:this._timeout)>0&&(timeoutId=setTimeout(function(){return controller.abort()},effectiveTimeout)),_state.label=1;case 1:return _state.trys.push([1,,4,5]),[4,fetch(url,_extends$4$1({},mergedOptions,{signal:controller.signal}))];case 2:if(!(response=_state.sent()).ok)throw(err=new Error("HTTP "+response.status+": "+response.statusText)).status=response.status,err;return[4,response.arrayBuffer()];case 3:return[2,{data:_state.sent(),url:response.url||url,contentType:response.headers.get("content-type")||void 0,contentLength:parseInt(response.headers.get("content-length")||"0",10)||void 0}];case 4:return timeoutId&&clearTimeout(timeoutId),this._abortControllers.delete(url),[7];case 5:return[2]}})}).call(this)},_proto.fetchSegment=function(url,byteRange,options){return _async_to_generator$4$1(function(){var headers,_byteRange_offset,start,end;return _ts_generator$4$1(this,function(_state){return headers=_extends$4$1({},(null==options?void 0:options.headers)||{}),byteRange&&(start=null!=(_byteRange_offset=byteRange.offset)?_byteRange_offset:0,end=start+byteRange.length-1,headers.Range="bytes="+start+"-"+end),[2,this.fetch(url,_extends$4$1({},options,{headers:headers}))]})}).call(this)},_proto.cancelRequest=function(url){var controller=this._abortControllers.get(url);controller&&(controller.abort(),this._abortControllers.delete(url),this._logger.debug("Cancelled request to "+url))},_proto.cancelAll=function(){for(var _step,_iterator=function(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o){if(o){if("string"==typeof o)return _array_like_to_array$4(o,void 0);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array$4(o,void 0):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._abortControllers);!(_step=_iterator()).done;){var _step_value=_step.value,url=_step_value[0];_step_value[1].abort(),this._logger.debug("Cancelled request to "+url)}this._abortControllers.clear()},_proto.updateFetchOptions=function(options){this._fetchOptions=_extends$4$1({},this._fetchOptions,options)},Fetcher}();function asyncGeneratorStep$3$1(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$3$1(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$3$1(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$3$1(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _extends$3$1(){return _extends$3$1=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$3$1.apply(this,arguments)}function _ts_generator$3$1(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var Decryptor=function(){function Decryptor(config){void 0===config&&(config={}),this._keyCache=new Map,this._pendingKeyFetches=new Map,this._MAX_KEY_CACHE_SIZE=50,this._logger=new Logger("HLS-IO:Decryptor",Logger.LEVEL.WARN),this._config=_extends$3$1({useWebCrypto:!0},config)}var _proto=Decryptor.prototype;return _proto.needsDecryption=function(segment){var _segment_key;return!((null==(_segment_key=segment.key)?void 0:_segment_key.keyFormat)&&segment.key.keyFormat!==KeyFormat.IDENTITY||!segment.key||segment.key.method===EncryptionMethod.NONE||void 0===segment.key.method)},_proto.decrypt=function(segment,data){return _async_to_generator$3$1(function(){var rawData,keyInfo;return _ts_generator$3$1(this,function(_state){if(!segment.data&&!data)throw new Error("No data to decrypt");if(rawData=data||segment.data,!(keyInfo=segment.key)||keyInfo.method===EncryptionMethod.NONE)return[2,{data:rawData,method:EncryptionMethod.NONE}];switch(this._logger.debug("Decrypting segment "+segment.uri+" with method "+keyInfo.method),keyInfo.method){case EncryptionMethod.AES_128:return[2,this._decryptAES128(segment,rawData,keyInfo)];case EncryptionMethod.SAMPLE_AES:return[2,this._decryptSampleAES(segment,rawData,keyInfo)];default:return this._logger.warn("Unknown encryption method, returning raw data"),[2,{data:rawData,method:EncryptionMethod.NONE}]}})}).call(this)},_proto.prefetchKey=function(segment){return _async_to_generator$3$1(function(){var _this,keyInfo,fetchPromise;return _ts_generator$3$1(this,function(_state){switch(_state.label){case 0:return _this=this,(keyInfo=segment.key)&&keyInfo.method!==EncryptionMethod.NONE&&keyInfo.method===EncryptionMethod.AES_128?this._config.keyProvider||!keyInfo.uri||this._keyCache.has(keyInfo.uri)?[2]:this._pendingKeyFetches.has(keyInfo.uri)?[4,this._pendingKeyFetches.get(keyInfo.uri)]:[3,2]:[2];case 1:case 3:return _state.sent(),[2];case 2:return this._logger.debug("Prefetching decryption key from "+keyInfo.uri),fetchPromise=fetch(keyInfo.uri).then(function(res){if(!res.ok)throw new Error("HTTP "+res.status);return res.arrayBuffer()}).then(function(key){if(_this._keyCache.size>=_this._MAX_KEY_CACHE_SIZE){var oldestKey=_this._keyCache.keys().next().value;oldestKey&&_this._keyCache.delete(oldestKey)}return _this._keyCache.set(keyInfo.uri,key),_this._pendingKeyFetches.delete(keyInfo.uri),key}).catch(function(err){throw _this._pendingKeyFetches.delete(keyInfo.uri),new Error("Prefetching key failed for "+keyInfo.uri+": "+err.message)}),this._pendingKeyFetches.set(keyInfo.uri,fetchPromise),[4,fetchPromise]}})}).call(this)},_proto._decryptAES128=function(segment,data,keyInfo){return _async_to_generator$3$1(function(){var _this,key,fetchPromise,iv,seq,i,cryptoKey,decrypted,error;return _ts_generator$3$1(this,function(_state){switch(_state.label){case 0:_this=this,_state.label=1;case 1:return _state.trys.push([1,14,,15]),this._config.keyProvider?[4,this._config.keyProvider(keyInfo,segment)]:[3,3];case 2:return key=_state.sent(),[3,10];case 3:return keyInfo.uri?this._keyCache.has(keyInfo.uri)?(key=this._keyCache.get(keyInfo.uri),[3,8]):[3,4]:[3,9];case 4:return this._pendingKeyFetches.has(keyInfo.uri)?[4,this._pendingKeyFetches.get(keyInfo.uri)]:[3,6];case 5:return key=_state.sent(),[3,8];case 6:return this._logger.debug("Fetching decryption key from "+keyInfo.uri),fetchPromise=fetch(keyInfo.uri).then(function(res){if(!res.ok)throw new Error("HTTP "+res.status);return res.arrayBuffer()}).then(function(k){if(_this._keyCache.size>=_this._MAX_KEY_CACHE_SIZE){var oldestKey=_this._keyCache.keys().next().value;oldestKey&&_this._keyCache.delete(oldestKey)}return _this._keyCache.set(keyInfo.uri,k),_this._pendingKeyFetches.delete(keyInfo.uri),k}).catch(function(err){throw _this._pendingKeyFetches.delete(keyInfo.uri),err}),this._pendingKeyFetches.set(keyInfo.uri,fetchPromise),[4,fetchPromise];case 7:key=_state.sent(),_state.label=8;case 8:return[3,10];case 9:throw new Error("No key URI or key provider available for AES-128 decryption");case 10:if(16!==key.byteLength)throw new Error("Invalid AES-128 key length: "+key.byteLength+" bytes (expected 16)");if(keyInfo.iv&&16===keyInfo.iv.length)iv=keyInfo.iv;else for(iv=new Uint8Array(16),seq=segment.sequence,i=0;i<8;i++)iv[15-i]=seq>>8*i&255;return this._logger.debug("Using IV: ["+Array.from(iv).map(function(b){return b.toString(16).padStart(2,"0")}).join(" ")+"]"),this._config.useWebCrypto&&"undefined"!=typeof crypto&&crypto.subtle?[4,crypto.subtle.importKey("raw",key,{name:"AES-CBC"},!1,["decrypt"])]:[3,13];case 11:return cryptoKey=_state.sent(),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:iv},cryptoKey,data)];case 12:return decrypted=_state.sent(),this._logger.debug("AES-128-CBC decryption successful"),[2,{data:decrypted,method:EncryptionMethod.AES_128}];case 13:throw new Error("Web Crypto API not available. Use a polyfill or provide a keyProvider.");case 14:throw error=_state.sent(),this._logger.error("AES-128 decryption failed: "+error.message),error;case 15:return[2]}})}).call(this)},_proto._decryptSampleAES=function(_segment,data,keyInfo){return _async_to_generator$3$1(function(){return _ts_generator$3$1(this,function(_state){return this._logger.warn("SAMPLE-AES decryption is not fully implemented. It requires container-level parsing of TS or fMP4. Returning raw data as-is."),[2,{data:data,method:keyInfo.method}]})}).call(this)},_proto.setDebug=function(debug){this._logger.setLevel(debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN)},_proto.updateConfig=function(config){this._config=_extends$3$1({},this._config,config)},Decryptor}();function getTagName(line){var colon=line.indexOf(":");return-1===colon?line:line.substring(0,colon)}function getTagAttributes(line){var colon=line.indexOf(":");return-1===colon?"":line.substring(colon+1)}function parseAttributes(attrStr){var attrs={};if(!attrStr)return attrs;for(var i=0,len=attrStr.length;i<len;){for(;i<len&&(" "===attrStr[i]||"\t"===attrStr[i]||","===attrStr[i]);)i++;if(i>=len)break;for(var nameStart=i;i<len&&"="!==attrStr[i]&&" "!==attrStr[i]&&","!==attrStr[i];)i++;for(var name=attrStr.substring(nameStart,i);i<len&&" "===attrStr[i];)i++;if(!(i>=len||"="!==attrStr[i])){for(i++;i<len&&" "===attrStr[i];)i++;var value=void 0;if(i<len&&'"'===attrStr[i]){for(var valStart=++i;i<len&&'"'!==attrStr[i];)i++;value=attrStr.substring(valStart,i),i++}else{for(var valStart1=i;i<len&&","!==attrStr[i]&&" "!==attrStr[i];)i++;value=attrStr.substring(valStart1,i)}attrs[name]=value}}return attrs}function parseResolution(res){if(!res)return null;var parts=res.split("x");if(2!==parts.length)return null;var w=parseInt(parts[0],10),h=parseInt(parts[1],10);return isNaN(w)||isNaN(h)?null:{width:w,height:h}}function parseHexBytes(hex){if(!hex.startsWith("0x")&&!hex.startsWith("0X"))return null;var hexStr=hex.substring(2);if(hexStr.length%2!=0)return null;if(!/^[0-9a-fA-F]+$/.test(hexStr))return null;for(var len=hexStr.length/2,bytes=new Uint8Array(len),i=0;i<len;i++)bytes[i]=parseInt(hexStr.substring(2*i,2*i+2),16);return bytes}function parseExtInf(line){var attrs=getTagAttributes(line),comma=attrs.indexOf(",");if(-1===comma){var duration=parseFloat(attrs);return isNaN(duration)?null:{duration:duration}}var duration1=parseFloat(attrs.substring(0,comma)),title=attrs.substring(comma+1).trim();return isNaN(duration1)?null:{duration:duration1,title:title||void 0}}function parseByteRange(line){var attrs=getTagAttributes(line),at=attrs.indexOf("@");if(-1===at){var length=parseInt(attrs,10);return isNaN(length)?null:{length:length}}var length1=parseInt(attrs.substring(0,at),10),offset=parseInt(attrs.substring(at+1),10);return isNaN(length1)?null:{length:length1,offset:isNaN(offset)?void 0:offset}}function parseEncryptionMethod(method){switch(method.toUpperCase()){case"AES-128":return EncryptionMethod.AES_128;case"SAMPLE-AES":case"SAMPLE-AES-CTR":return EncryptionMethod.SAMPLE_AES;default:return EncryptionMethod.NONE}}function parseKeyAttributes(attrs){var _parseHexBytes,format;return{method:parseEncryptionMethod(attrs.METHOD||"NONE"),uri:attrs.URI,iv:attrs.IV&&null!=(_parseHexBytes=parseHexBytes(attrs.IV))?_parseHexBytes:void 0,keyFormat:attrs.KEYFORMAT?(format=attrs.KEYFORMAT,"com.apple.streamingkeydelivery"===format?KeyFormat.COMMON_ENCRYPTION:KeyFormat.IDENTITY):void 0,keyFormatVersions:attrs.KEYFORMATVERSIONS}}function parseMapAttributes(attrs){var uri=attrs.URI;return uri?{uri:uri,byteRange:attrs.BYTERANGE?parseByteRangeText(attrs.BYTERANGE):void 0}:null}function parseByteRangeText(text){var at=text.indexOf("@");return-1===at?{length:parseInt(text,10)}:{length:parseInt(text.substring(0,at),10),offset:parseInt(text.substring(at+1),10)}}function parsePartAttributes(attrs){var duration=parseFloat(attrs.DURATION),uri=attrs.URI;return isNaN(duration)||!uri?null:{duration:duration,uri:uri,byteRange:attrs.BYTERANGE?parseByteRangeText(attrs.BYTERANGE):void 0,independent:"YES"===attrs.INDEPENDENT,gap:"YES"===attrs.GAP}}function parseServerControl(attrs){return{canSkipUntil:attrs["CAN-SKIP-UNTIL"]?parseFloat(attrs["CAN-SKIP-UNTIL"]):void 0,canSkipDateTimes:"YES"===attrs["CAN-SKIP-DATERANGES"],canBlockReload:"YES"===attrs["CAN-BLOCK-RELOAD"],holdBack:attrs["HOLD-BACK"]?parseFloat(attrs["HOLD-BACK"]):void 0,partHoldBack:attrs["PART-HOLD-BACK"]?parseFloat(attrs["PART-HOLD-BACK"]):void 0}}function parsePreloadHint(attrs){var type=attrs.TYPE,uri=attrs.URI;return type&&uri?{type:type,uri:uri,byteRangeStart:attrs["BYTERANGE-START"]?parseInt(attrs["BYTERANGE-START"],10):void 0,byteRangeLength:attrs["BYTERANGE-LENGTH"]?parseInt(attrs["BYTERANGE-LENGTH"],10):void 0}:null}function parseRenditionReport(attrs){var uri=attrs.URI;return uri?{uri:uri,lastMSN:attrs["LAST-MSN"]?parseInt(attrs["LAST-MSN"],10):void 0,lastPart:attrs["LAST-PART"]?parseInt(attrs["LAST-PART"],10):void 0}:null}function parseDateRange(attrs){var id=attrs.ID;return id?{id:id,class:attrs.CLASS,startDate:attrs["START-DATE"]||"",endDate:attrs["END-DATE"],duration:attrs.DURATION?parseFloat(attrs.DURATION):void 0,plannedDuration:attrs["PLANNED-DURATION"]?parseFloat(attrs["PLANNED-DURATION"]):void 0,endOnNext:"YES"===attrs["END-ON-NEXT"],attributes:attrs}:null}function parseStreamInf(attrs){var _parseResolution,bandwidth=parseInt(attrs.BANDWIDTH,10);return isNaN(bandwidth)?null:{bandwidth:bandwidth,averageBandwidth:attrs["AVERAGE-BANDWIDTH"]?parseInt(attrs["AVERAGE-BANDWIDTH"],10):void 0,codecs:attrs.CODECS,resolution:attrs.RESOLUTION&&null!=(_parseResolution=parseResolution(attrs.RESOLUTION))?_parseResolution:void 0,frameRate:attrs["FRAME-RATE"]?parseFloat(attrs["FRAME-RATE"]):void 0,hdcpLevel:attrs["HDCP-LEVEL"],audio:attrs.AUDIO,video:attrs.VIDEO,subtitles:attrs.SUBTITLES,closedCaptions:attrs["CLOSED-CAPTIONS"],score:attrs.SCORE?parseFloat(attrs.SCORE):void 0}}function parseM3U8(text,baseUrl){return function(text){return text.includes("#EXT-X-STREAM-INF")}(text)?{type:"master",playlist:parseMasterPlaylist(text,baseUrl)}:{type:"media",playlist:parseMediaPlaylist(text,baseUrl)}}function parseMediaPlaylist(text,baseUrl){for(var allowCache,independentSegments,startOffset,partTargetDuration,serverControl,preloadHint,currentKey,currentMap,currentByteRange,currentProgramDateTime,currentDateRange,currentBitrate,lines=text.split(/\r?\n/),segments=[],partialSegments=[],renditionReports=[],version=3,playlistType=PlaylistType.LIVE,targetDuration=0,mediaSequence=0,discontinuitySequence=0,iFramesOnly=!1,currentDiscontinuity=!1,currentGap=!1,totalDuration=0,segmentIndex=0,i=0;i<lines.length;){var line=lines[i].trim();if(!line||line.startsWith("#")&&!line.startsWith("#EXT"))i++;else{if(line.startsWith("#EXT")){var tagName=getTagName(line),attrStr=getTagAttributes(line),attrs=parseAttributes(attrStr);switch(tagName){case"#EXTM3U":break;case"#EXT-X-VERSION":version=parseInt(attrStr,10)||3;break;case"#EXT-X-PLAYLIST-TYPE":"VOD"===attrStr?playlistType=PlaylistType.VOD:"EVENT"===attrStr&&(playlistType=PlaylistType.LIVE);break;case"#EXT-X-TARGETDURATION":targetDuration=parseFloat(attrStr)||0;break;case"#EXT-X-MEDIA-SEQUENCE":mediaSequence=parseInt(attrStr,10)||0;break;case"#EXT-X-DISCONTINUITY-SEQUENCE":discontinuitySequence=parseInt(attrStr,10)||0;break;case"#EXT-X-ENDLIST":playlistType=PlaylistType.VOD;break;case"#EXT-X-ALLOW-CACHE":allowCache="YES"===attrStr;break;case"#EXT-X-INDEPENDENT-SEGMENTS":independentSegments=!0;break;case"#EXT-X-START":startOffset=attrs["TIME-OFFSET"]?parseFloat(attrs["TIME-OFFSET"]):void 0;break;case"#EXT-X-I-FRAMES-ONLY":iFramesOnly=!0;break;case"#EXT-X-PART-INF":partTargetDuration=attrs["PART-TARGET"]?parseFloat(attrs["PART-TARGET"]):void 0;break;case"#EXT-X-SERVER-CONTROL":serverControl=parseServerControl(attrs);break;case"#EXT-X-KEY":(currentKey=parseKeyAttributes(attrs))&&currentKey.uri&&baseUrl&&(currentKey.uri=resolveAgainstBase(currentKey.uri,baseUrl));break;case"#EXT-X-MAP":var _parseMapAttributes;(currentMap=null!=(_parseMapAttributes=parseMapAttributes(attrs))?_parseMapAttributes:void 0)&&currentMap.uri&&baseUrl&&(currentMap.uri=resolveAgainstBase(currentMap.uri,baseUrl));break;case"#EXT-X-DISCONTINUITY":currentDiscontinuity=!0,discontinuitySequence++;break;case"#EXT-X-GAP":currentGap=!0;break;case"#EXT-X-BITRATE":currentBitrate=parseInt(attrStr,10)||void 0;break;case"#EXT-X-PROGRAM-DATE-TIME":currentProgramDateTime=new Date(attrStr);break;case"#EXT-X-DATERANGE":var dateRange=parseDateRange(attrs);dateRange&&(currentDateRange=dateRange);break;case"#EXTINF":var info=parseExtInf(line);if(++i<lines.length){var uri=lines[i].trim();if(uri&&!uri.startsWith("#")){var _ref,resolvedUri=baseUrl?resolveAgainstBase(uri,baseUrl):uri,segment={sequence:mediaSequence+segmentIndex,duration:null!=(_ref=null==info?void 0:info.duration)?_ref:0,uri:resolvedUri,title:null==info?void 0:info.title,byteRange:currentByteRange,key:currentKey,map:currentMap,programDateTime:currentProgramDateTime,discontinuity:currentDiscontinuity,gap:currentGap,dateRange:currentDateRange,bitrate:currentBitrate};segments.push(segment),totalDuration+=segment.duration,segmentIndex++}}currentDiscontinuity=!1,currentGap=!1,currentByteRange=void 0,currentProgramDateTime=void 0,currentDateRange=void 0,currentBitrate=void 0;break;case"#EXT-X-BYTERANGE":var _parseByteRange;currentByteRange=null!=(_parseByteRange=parseByteRange(line))?_parseByteRange:void 0;break;case"#EXT-X-PART":var part=parsePartAttributes(attrs);part&&(part.uri=baseUrl?resolveAgainstBase(part.uri,baseUrl):part.uri,partialSegments.push(part));break;case"#EXT-X-PRELOAD-HINT":var hint=parsePreloadHint(attrs);hint&&(hint.uri=baseUrl?resolveAgainstBase(hint.uri,baseUrl):hint.uri,preloadHint=hint);break;case"#EXT-X-RENDITION-REPORT":var report=parseRenditionReport(attrs);report&&(report.uri=baseUrl?resolveAgainstBase(report.uri,baseUrl):report.uri,renditionReports.push(report))}}i++}}return{type:playlistType,version:version,targetDuration:targetDuration,mediaSequence:mediaSequence,discontinuitySequence:discontinuitySequence,segments:segments,partialSegments:partialSegments.length>0?partialSegments:void 0,preloadHint:preloadHint,renditionReports:renditionReports.length>0?renditionReports:void 0,serverControl:serverControl,allowCache:allowCache,independentSegments:independentSegments,startOffset:startOffset,iFramesOnly:iFramesOnly,partTargetDuration:partTargetDuration,duration:totalDuration,endTime:totalDuration,raw:text}}function parseMasterPlaylist(text,baseUrl){for(var independentSegments,lines=text.split(/\r?\n/),variants=[],mediaRenditions=[],sessionData={},sessionKeys=[],version=3,currentStreamAttrs=null,i=0;i<lines.length;i++){var line=lines[i].trim();if(line&&(!line.startsWith("#")||line.startsWith("#EXT"))&&line.startsWith("#EXT")){var tagName=getTagName(line),attrStr=getTagAttributes(line),attrs=parseAttributes(attrStr);switch(tagName){case"#EXTM3U":break;case"#EXT-X-VERSION":version=parseInt(attrStr,10)||3;break;case"#EXT-X-INDEPENDENT-SEGMENTS":independentSegments=!0;break;case"#EXT-X-STREAM-INF":if(currentStreamAttrs=attrs,++i<lines.length){var uri=lines[i].trim();if(uri&&!uri.startsWith("#")){var info=parseStreamInf(currentStreamAttrs);info&&variants.push({uri:baseUrl?resolveAgainstBase(uri,baseUrl):uri,bandwidth:info.bandwidth,averageBandwidth:info.averageBandwidth,codecs:info.codecs,resolution:info.resolution,frameRate:info.frameRate,hdcpLevel:info.hdcpLevel,audio:info.audio,video:info.video,subtitles:info.subtitles,closedCaptions:info.closedCaptions,score:info.score,attributes:currentStreamAttrs})}}currentStreamAttrs=null;break;case"#EXT-X-I-FRAME-STREAM-INF":var info1=parseStreamInf(attrs),uri1=attrs.URI;info1&&uri1&&variants.push({uri:baseUrl?resolveAgainstBase(uri1,baseUrl):uri1,bandwidth:info1.bandwidth,codecs:info1.codecs,resolution:info1.resolution,attributes:attrs});break;case"#EXT-X-MEDIA":var rendition={type:attrs.TYPE||"AUDIO",uri:attrs.URI?baseUrl?resolveAgainstBase(attrs.URI,baseUrl):attrs.URI:void 0,groupId:attrs["GROUP-ID"]||"",language:attrs.LANGUAGE,assocLanguage:attrs["ASSOC-LANGUAGE"],name:attrs.NAME||"",default:"YES"===attrs.DEFAULT,autoselect:"YES"===attrs.AUTOSELECT,forced:"YES"===attrs.FORCED,instreamId:attrs["INSTREAM-ID"],characteristics:attrs.CHARACTERISTICS,channels:attrs.CHANNELS};mediaRenditions.push(rendition);break;case"#EXT-X-SESSION-DATA":attrs["DATA-ID"]&&attrs.VALUE&&(sessionData[attrs["DATA-ID"]]=attrs.VALUE);break;case"#EXT-X-SESSION-KEY":var keyInfo=parseKeyAttributes(attrs);keyInfo&&keyInfo.uri&&baseUrl&&(keyInfo.uri=resolveAgainstBase(keyInfo.uri,baseUrl)),sessionKeys.push(keyInfo)}}}return{version:version,variants:variants,mediaRenditions:mediaRenditions.length>0?mediaRenditions:void 0,sessionData:Object.keys(sessionData).length>0?sessionData:void 0,sessionKeys:sessionKeys.length>0?sessionKeys:void 0,independentSegments:independentSegments,raw:text}}function resolveAgainstBase(uri,baseUrl){if(/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(uri))return uri;if(uri.startsWith("//"))return"https:"+uri;if(uri.startsWith("/"))try{var base=new URL(baseUrl);return base.protocol+"//"+base.host+uri}catch(unused){return uri}return baseUrl.substring(0,baseUrl.lastIndexOf("/")+1)+uri}function resolveUri(uri,baseUrl){if(!uri)return baseUrl;if(function(uri){return/^([a-zA-Z][a-zA-Z0-9+\-.]*:|\/\/)/.test(uri)}(uri))return uri;if(function(uri){return/^\/\//.test(uri)}(uri))return"undefined"!=typeof window&&window.location?window.location.protocol+uri:"https:"+uri;if(uri.startsWith("/")){var base=new URL(baseUrl);return base.protocol+"//"+base.host+uri}var resolved=baseUrl.substring(0,baseUrl.lastIndexOf("/")+1)+uri;if(resolved.includes("../")||resolved.includes("./"))try{return new URL(resolved).href}catch(unused){return resolved}return resolved}function segmentCacheKey(uri,byteRange){var _byteRange_offset,cleanUri=function(uri){return uri.split("?")[0].split("#")[0]}(uri);return byteRange?cleanUri+"#"+(null!=(_byteRange_offset=byteRange.offset)?_byteRange_offset:0)+"-"+byteRange.length:cleanUri}function asyncGeneratorStep$2$1(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$2$1(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$2$1(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$2$1(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _ts_generator$2$1(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var PlaylistManager=function(){function PlaylistManager(fetcher,config,callbacks,debug){void 0===debug&&(debug=!1),this._pollTimer=null,this._isDestroyed=!1,this._lastPlaylist=null,this._lastETag=null,this._lastModified=null,this._segmentUpdateSeq=0,this._pollCount=0,this._isPollRequestInFlight=!1,this._lastPollHadChanges=!1,this._fetcher=fetcher,this._config=config,this._logger=new Logger("HLS-IO:Playlist",debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),this._callbacks=callbacks,this._originalUrl=config.url,this._playlistUrl=config.url,this.playlistUrl=config.url}var _proto=PlaylistManager.prototype;return _proto.start=function(){return _async_to_generator$2$1(function(){var result,variant,variantUrl,mediaResult;return _ts_generator$2$1(this,function(_state){switch(_state.label){case 0:return this._logger.info("Loading playlist: "+this._playlistUrl),[4,this._loadPlaylist()];case 1:if("master"!==(result=_state.sent()).type)return[3,6];if(this._logger.info("Master playlist detected, selecting first variant"),!(result.playlist.variants.length>0))return[3,5];variant=result.playlist.variants[0],variantUrl=this._config.resolveRelativeUris?resolveUri(variant.uri,this._config.baseUrl||this._playlistUrl):variant.uri,this._playlistUrl=variantUrl,this.playlistUrl=variantUrl,_state.label=2;case 2:return _state.trys.push([2,,4,5]),[4,this._loadPlaylist()];case 3:return"media"===(mediaResult=_state.sent()).type?(this._handleMediaPlaylist(mediaResult.playlist),[2,mediaResult.playlist]):[3,5];case 4:return[7];case 5:return[2,result.playlist];case 6:return this._handleMediaPlaylist(result.playlist),[2,result.playlist]}})}).call(this)},_proto.destroy=function(){this._isDestroyed=!0,this._stopPolling(),this._lastPlaylist=null},_proto.refresh=function(){return _async_to_generator$2$1(function(){var result,error;return _ts_generator$2$1(this,function(_state){switch(_state.label){case 0:return _state.trys.push([0,2,,3]),[4,this._loadPlaylist()];case 1:return"media"===(result=_state.sent()).type?(this._handleMediaPlaylist(result.playlist),[2,result.playlist]):[3,3];case 2:return error=_state.sent(),this._logger.error("Refresh failed: "+error.message),[3,3];case 3:return[2,null]}})}).call(this)},_proto.getLastPlaylist=function(){return this._lastPlaylist},_proto._loadPlaylist=function(){return _async_to_generator$2$1(function(){var headers,result,text,baseUrl,error,lastError,err;return _ts_generator$2$1(this,function(_state){switch(_state.label){case 0:return _state.trys.push([0,2,,3]),headers={},this._lastETag&&(headers["If-None-Match"]=this._lastETag),this._lastModified&&(headers["If-Modified-Since"]=this._lastModified),[4,this._fetcher.fetch(this._playlistUrl,{headers:headers})];case 1:return result=_state.sent(),this._config.followRedirectUrl&&(null==result?void 0:result.url)!==this._playlistUrl&&(this._logger.info("Playlist URL redirected: "+this._playlistUrl+" → "+result.url),this._playlistUrl=result.url),text=(new TextDecoder).decode(result.data),baseUrl=this._config.resolveRelativeUris?this._config.baseUrl||this._playlistUrl:void 0,[2,parseM3U8(text,baseUrl)];case 2:throw error=_state.sent(),lastError=error,this._logger.warn("Playlist fetch failed: "+lastError.message),this._playlistUrl!==this._originalUrl&&(this._logger.info("Resetting URL to original: "+this._originalUrl),this._playlistUrl=this._originalUrl),err={type:"NETWORK",subType:"M3U8",message:"Failed to load playlist: "+lastError.message,originalError:lastError,playlistUrl:this._playlistUrl},this._callbacks.onError(err),this._stopPolling(),lastError;case 3:return[2]}})}).call(this)},_proto._handleMediaPlaylist=function(playlist){var _this__lastPlaylist,isFirst=!this._lastPlaylist;if((isFirst||(null==(_this__lastPlaylist=this._lastPlaylist)?void 0:_this__lastPlaylist.type)!==playlist.type)&&this._callbacks.onPlaylistTypeDetected(playlist.type),!isFirst&&this._lastPlaylist){var newSegments=this._detectNewSegments(this._lastPlaylist.segments,playlist.segments);this._lastPollHadChanges=newSegments.length>0,this._lastPollHadChanges&&(this._logger.info("Detected "+newSegments.length+" new segments"),this._segmentUpdateSeq++,this._callbacks.onSegmentsUpdated(newSegments,playlist)),playlist.partialSegments&&playlist.partialSegments.length>0&&this._callbacks.onPartialSegments(playlist.partialSegments)}this._lastPlaylist=playlist,this._callbacks.onPlaylistLoaded(playlist),playlist.type!==PlaylistType.LIVE||this._isDestroyed||this._schedulePoll(playlist),playlist.type===PlaylistType.VOD&&this._callbacks.onEnded()},_proto._detectNewSegments=function(oldSegments,newSegments){var oldSeqSet=new Set(oldSegments.map(function(s){return s.sequence}));return newSegments.filter(function(s){return!oldSeqSet.has(s.sequence)})},_proto._schedulePoll=function(playlist){var _this=this;this._stopPolling();var interval=this._config.playlistRefreshInterval;if(!Number.isFinite(interval)||interval<=0){var baseInterval=this._lastPollHadChanges?1e3*playlist.targetDuration:500*playlist.targetDuration;interval=Math.max(250,Math.min(baseInterval,2e3*playlist.targetDuration)),playlist.targetDuration<=2&&(interval=this._lastPollHadChanges?Math.max(250,1e3*playlist.targetDuration):Math.max(250,500*playlist.targetDuration))}this._logger.debug("Polling every "+interval+"ms (targetDuration="+playlist.targetDuration+")"),this._pollTimer=setInterval(function(){return _async_to_generator$2$1(function(){var result;return _ts_generator$2$1(this,function(_state){switch(_state.label){case 0:if(this._isDestroyed)return[2];if(this._isPollRequestInFlight)return this._logger.debug("Skip poll tick: previous playlist request still in flight"),[2];this._pollCount++,this._isPollRequestInFlight=!0,_state.label=1;case 1:return _state.trys.push([1,3,4,5]),[4,this._loadPlaylist()];case 2:return"media"===(result=_state.sent()).type&&this._handleMediaPlaylist(result.playlist),[3,5];case 3:return _state.sent(),[3,5];case 4:return this._isPollRequestInFlight=!1,[7];case 5:return[2]}})}).call(_this)},interval)},_proto._stopPolling=function(){this._pollTimer&&(clearInterval(this._pollTimer),this._pollTimer=null)},PlaylistManager}();function _array_like_to_array$2(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _extends$2$1(){return _extends$2$1=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$2$1.apply(this,arguments)}var SegmentCache=function(){function SegmentCache(maxSize,policy){void 0===maxSize&&(maxSize=50),void 0===policy&&(policy="lru"),this._cache=new Map,this._accessOrder=[],this._maxSize=Number.isFinite(maxSize)?Math.max(1,Math.floor(maxSize)):50,this._policy=policy,this._stats={size:0,hits:0,misses:0,evictions:0}}var Constructor,protoProps,_proto=SegmentCache.prototype;return _proto.set=function(segment,data){var key=segmentCacheKey(segment.uri,segment.byteRange);if(this._cache.has(key)){var entry=this._cache.get(key);return entry.data=data,entry.segment=segment,entry.timestamp=Date.now(),void this._updateAccess(key)}this._cache.size>=this._maxSize&&this._evict();var entry1={segment:segment,data:data,timestamp:Date.now(),key:key};this._cache.set(key,entry1),this._accessOrder.push(key),this._stats.size=this._cache.size},_proto.get=function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange),entry=this._cache.get(key);return entry?(this._stats.hits++,"lru"===this._policy&&this._updateAccess(key),entry.data):(this._stats.misses++,null)},_proto.has=function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange);return this._cache.has(key)},_proto.delete=function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange),deleted=this._cache.delete(key);return deleted&&(this._accessOrder=this._accessOrder.filter(function(k){return k!==key}),this._stats.size=this._cache.size),deleted},_proto.clear=function(){this._cache.clear(),this._accessOrder=[],this._stats.size=0},_proto.getStats=function(){return _extends$2$1({},this._stats)},_proto.evictBeforeSequence=function(sequence){for(var _step,_this=this,removed=0,_iterator=function(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o){if(o){if("string"==typeof o)return _array_like_to_array$2(o,void 0);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array$2(o,void 0):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._cache);!(_step=_iterator()).done;){var _step_value=_step.value,key=_step_value[0];_step_value[1].segment.sequence<sequence&&(this._cache.delete(key),removed++)}return this._accessOrder=this._accessOrder.filter(function(key){return _this._cache.has(key)}),this._stats.size=this._cache.size,this._stats.evictions+=removed,removed},_proto.getSegmentsInOrder=function(){return[].concat(this._cache.values()).map(function(entry){return entry.segment}).sort(function(a,b){return a.sequence-b.sequence})},_proto._evict=function(){if(0!==this._cache.size){var firstKey=this._cache.keys().next().value;void 0!==firstKey&&(this._cache.delete(firstKey),this._accessOrder=this._accessOrder.filter(function(k){return k!==firstKey}),this._stats.evictions++,this._stats.size=this._cache.size)}},_proto._updateAccess=function(key){if("lru"===this._policy){var entry=this._cache.get(key);entry&&(this._cache.delete(key),this._cache.set(key,entry))}},Constructor=SegmentCache,(protoProps=[{key:"size",get:function(){return this._cache.size}},{key:"keys",get:function(){return[].concat(this._accessOrder)}}])&&function(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}(Constructor.prototype,protoProps),SegmentCache}(),LookAheadPrefetchStrategy=function(){function LookAheadPrefetchStrategy(){}return LookAheadPrefetchStrategy.prototype.getNextSegments=function(currentSequence,allSegments,bufferAhead){var sorted=[].concat(allSegments).sort(function(a,b){return a.sequence-b.sequence}),startIndex=sorted.findIndex(function(s){return s.sequence>currentSequence});return-1===startIndex?[]:sorted.slice(startIndex,startIndex+bufferAhead)},LookAheadPrefetchStrategy}();function _array_like_to_array$1(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function asyncGeneratorStep$1$2(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$1$1(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$1$2(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$1$2(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _extends$1$1(){return _extends$1$1=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$1$1.apply(this,arguments)}function _create_for_of_iterator_helper_loose$1(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o){if(o){if("string"==typeof o)return _array_like_to_array$1(o,void 0);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array$1(o,void 0):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}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 _ts_generator$1$2(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var SegmentManager=function(){function SegmentManager(fetcher,decryptor,config,callbacks,debug){void 0===debug&&(debug=!1),this._segments=[],this._currentSequence=-1,this._fetchQueue=new Set,this._loadedSegmentKeys=new Set,this._mapDataCache=new Map,this._MAX_MAP_CACHE=10,this._isDestroyed=!1,this._pendingPartials=[],this._pendingFetchQueue=[],this._isFetchLoopRunning=!1;var normalizedMaxCacheSize=Number.isFinite(config.maxCacheSize)?Math.max(1,Math.floor(config.maxCacheSize)):50,normalizedBufferAheadRaw=Number.isFinite(config.bufferAhead)?Math.max(1,Math.floor(config.bufferAhead)):1,normalizedBufferAhead=Math.min(normalizedBufferAheadRaw,normalizedMaxCacheSize);this._fetcher=fetcher,this._cache=new SegmentCache(normalizedMaxCacheSize,config.cachePolicy),this._decryptor=decryptor,this._config=_extends$1$1({},config,{bufferAhead:normalizedBufferAhead,maxCacheSize:normalizedMaxCacheSize}),this._logger=new Logger("HLS-IO:Segment",debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),this._callbacks=callbacks,this._prefetchStrategy=new LookAheadPrefetchStrategy}var Constructor,protoProps,_proto=SegmentManager.prototype;return _proto.updateSegments=function(newSegments,partialSegments){if(!this._isDestroyed){var oldSegmentCount=this._segments.length;if(this._segments=newSegments,partialSegments){this._pendingPartials=partialSegments;for(var _step,_iterator=_create_for_of_iterator_helper_loose$1(partialSegments);!(_step=_iterator()).done;){var part=_step.value;this._callbacks.onPartSegment(part)}}this._config.playlistType===PlaylistType.LIVE?this._handleLiveSegments():this._handleVODSegments(),this._logger.debug("Segments updated: "+oldSegmentCount+" -> "+newSegments.length+", type: "+this._config.playlistType)}},_proto.fetchSegment=function(sequence){return _async_to_generator$1$1(function(){var segment;return _ts_generator$1$2(this,function(_state){return(segment=this._segments.find(function(s){return s.sequence===sequence}))?[2,this._loadSegment(segment)]:[2,null]})}).call(this)},_proto.getNextSegment=function(){var _this=this,sorted=this.getSortedSegments(),idx=sorted.findIndex(function(s){return s.sequence>_this._currentSequence});return-1===idx?null:sorted[idx]},_proto.advanceToNext=function(){var next=this.getNextSegment();return next&&(this._currentSequence=next.sequence,this._cache.evictBeforeSequence(this._currentSequence-this._config.maxCacheSize),this._config.playlistType===PlaylistType.LIVE?this._handleLiveSegments():this._handleVODSegments()),next},_proto.getCachedSegment=function(segment){return this._cache.get(segment)},_proto.getSortedSegments=function(){return[].concat(this._segments).sort(function(a,b){return a.sequence-b.sequence})},_proto.getCacheStats=function(){return this._cache.getStats()},_proto.getLastSegment=function(){var sorted=this.getSortedSegments();return sorted.length>0?sorted[sorted.length-1]:null},_proto.setPlaylistType=function(type){this._config.playlistType=type},_proto.destroy=function(){this._isDestroyed=!0,this._cache.clear(),this._segments=[],this._fetchQueue.clear(),this._loadedSegmentKeys.clear(),this._mapDataCache.clear(),this._pendingFetchQueue=[]},_proto._handleLiveSegments=function(){var _sorted_,sorted=this.getSortedSegments();if(0!==sorted.length){if(-1===this._currentSequence){for(var td=this._config.targetDuration||sorted[0].duration||6,acc=0,i=sorted.length-1;i>=0;i--)if((acc+=sorted[i].duration)>=3*td){this._currentSequence=sorted[i].sequence-1;break}-1===this._currentSequence&&(this._currentSequence=sorted[0].sequence-1)}for(var _step,_iterator=_create_for_of_iterator_helper_loose$1(sorted.slice(-this._config.bufferAhead));!(_step=_iterator()).done;){var segment=_step.value;this._cache.has(segment)||this._enqueueFetch(segment)}var oldestToKeep=(null==(_sorted_=sorted[sorted.length-1])?void 0:_sorted_.sequence)-this._config.maxCacheSize;oldestToKeep>0&&this._cache.evictBeforeSequence(oldestToKeep)}},_proto._handleVODSegments=function(){var _this=this,sorted=this.getSortedSegments();if(0!==sorted.length){for(var _step,_iterator=_create_for_of_iterator_helper_loose$1(this._prefetchStrategy.getNextSegments(this._currentSequence,sorted,this._config.bufferAhead));!(_step=_iterator()).done;){var segment=_step.value;this._cache.has(segment)||this._enqueueFetch(segment)}var buffered=sorted.filter(function(s){return s.sequence>_this._currentSequence&&_this._cache.has(s)}).length,remaining=sorted.filter(function(s){return s.sequence>_this._currentSequence}).length,needed=Math.min(this._config.bufferAhead,remaining);needed>0&&buffered<needed&&this._currentSequence>=0&&this._callbacks.onBufferStall({buffered:buffered,needed:needed})}},_proto._enqueueFetch=function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange);this._loadedSegmentKeys.has(key)||this._fetchQueue.has(key)||(this._fetchQueue.add(key),this._pendingFetchQueue.push(segment),this._processFetchQueue())},_proto._processFetchQueue=function(){return _async_to_generator$1$1(function(){var segment,key,err;return _ts_generator$1$2(this,function(_state){switch(_state.label){case 0:if(this._isFetchLoopRunning)return[2];this._isFetchLoopRunning=!0,_state.label=1;case 1:_state.trys.push([1,5,6,7]),_state.label=2;case 2:return this._pendingFetchQueue.length>0&&!this._isDestroyed?(segment=this._pendingFetchQueue.shift(),key=segmentCacheKey(segment.uri,segment.byteRange),this._loadedSegmentKeys.has(key)?(this._fetchQueue.delete(key),[3,2]):[4,this._loadSegment(segment)]):[3,4];case 3:return _state.sent(),[3,2];case 4:return[3,7];case 5:return err=_state.sent(),this._logger.error("Fetch queue processing error: "+err.message),[3,7];case 6:return this._isFetchLoopRunning=!1,[7];case 7:return[2]}})}).call(this)},_proto._loadSegment=function(segment){return _async_to_generator$1$1(function(){var queueKey,_this__config_segmentRetryCount,_this__config_segmentRetryDelay,_this__config_segmentRetryBackoff,mapData,keyErr,url,result,attempt,maxRetries,delay,backoff,_this__config_segmentTimeout,err,data,decrypted,decryptErr,format,_sorted_,sorted,lastSeq,error,lastError;return _ts_generator$1$2(this,function(_state){switch(_state.label){case 0:if(queueKey=segmentCacheKey(segment.uri,segment.byteRange),this._loadedSegmentKeys.has(queueKey))return this._fetchQueue.delete(queueKey),[2,segment];if(this._isDestroyed)return[2,null];_state.label=1;case 1:return _state.trys.push([1,19,,20]),this._logger.debug("Fetching segment seq="+segment.sequence+" uri="+segment.uri),segment.map?[4,this._loadMap(segment.map)]:[3,3];case 2:if(!(mapData=_state.sent()))return this._fetchQueue.delete(queueKey),[2,null];segment.mapData=mapData,_state.label=3;case 3:if(!this._decryptor.needsDecryption(segment))return[3,7];_state.label=4;case 4:return _state.trys.push([4,6,,7]),[4,this._decryptor.prefetchKey(segment)];case 5:return _state.sent(),[3,7];case 6:return keyErr=_state.sent(),this._callbacks.onError({type:"DECRYPT",message:"Key fetch failed for segment "+segment.uri+": "+keyErr.message,originalError:keyErr,segmentUri:segment.uri}),this._fetchQueue.delete(queueKey),[2,null];case 7:url=this._config.resolveRelativeUris&&this._config.baseUrl?resolveUri(segment.uri,this._config.baseUrl):segment.uri,attempt=0,maxRetries=this._config.playlistType===PlaylistType.LIVE?0:null!=(_this__config_segmentRetryCount=this._config.segmentRetryCount)?_this__config_segmentRetryCount:5,delay=null!=(_this__config_segmentRetryDelay=this._config.segmentRetryDelay)?_this__config_segmentRetryDelay:500,backoff=null!=(_this__config_segmentRetryBackoff=this._config.segmentRetryBackoff)?_this__config_segmentRetryBackoff:2,_state.label=8;case 8:_state.label=9;case 9:return _state.trys.push([9,11,,13]),[4,this._fetcher.fetchSegment(url,segment.byteRange,{timeout:null!=(_this__config_segmentTimeout=this._config.segmentTimeout)?_this__config_segmentTimeout:void 0})];case 10:return result=_state.sent(),[3,14];case 11:if(err=_state.sent(),++attempt>maxRetries||this._isDestroyed)throw err;return this._logger.warn("Segment fetch failed sequence="+segment.sequence+", retrying ("+attempt+"/"+maxRetries+") in "+delay+"ms"),[4,new Promise(function(resolve){return setTimeout(resolve,delay)})];case 12:return _state.sent(),delay*=backoff,[3,13];case 13:return[3,8];case 14:if(this._isDestroyed)return[2,null];if(data=result.data,segment.data=data,!this._decryptor.needsDecryption(segment))return[3,18];this._callbacks.onDecrypting(segment),_state.label=15;case 15:return _state.trys.push([15,17,,18]),[4,this._decryptor.decrypt(segment,data)];case 16:return decrypted=_state.sent(),this._isDestroyed?[2,null]:(data=decrypted.data,segment.data=data,this._callbacks.onDecrypted(segment),[3,18]);case 17:return decryptErr=_state.sent(),this._isDestroyed||(this._callbacks.onError({type:"DECRYPT",message:"Decryption failed for "+segment.uri+": "+decryptErr.message,originalError:decryptErr,segmentUri:segment.uri}),this._fetchQueue.delete(queueKey)),[2,null];case 18:return this._isDestroyed?[2,null]:(this._cache.set(segment,data),this._loadedSegmentKeys.add(queueKey),uri=segment.uri,clean=uri.split("?")[0].split("#")[0],format=clean.endsWith(".ts")||clean.endsWith(".TS")?"ts":clean.endsWith(".m4s")||clean.endsWith(".mp4")||clean.endsWith(".m4v")||clean.endsWith(".cmfv")||clean.endsWith(".cmfa")?"fmp4":"unknown",this._logger.debug("Segment "+segment.sequence+" loaded ("+format+", "+data.byteLength+" bytes)"),this._callbacks.onSegmentReady(segment),segment.discontinuity&&this._callbacks.onDiscontinuity(segment),this._config.playlistType===PlaylistType.VOD&&(sorted=this.getSortedSegments(),lastSeq=null==(_sorted_=sorted[sorted.length-1])?void 0:_sorted_.sequence,segment.sequence===lastSeq&&(this._logger.info("Last segment fetched: seq="+segment.sequence),this._callbacks.onLastSegment(segment))),this._fetchQueue.delete(queueKey),[2,segment]);case 19:return error=_state.sent(),this._isDestroyed?(this._fetchQueue.delete(queueKey),[2,null]):"AbortError"===(lastError=error).name?(this._callbacks.onError({type:"TIMEOUT",subType:"SEGMENT",message:"Segment fetch timed out: "+segment.uri,originalError:lastError,segmentUri:segment.uri}),this._fetchQueue.delete(queueKey),[2,null]):(this._logger.warn("Segment fetch failed for "+segment.uri+": "+lastError.message),this._callbacks.onError({type:"NETWORK",subType:"SEGMENT",message:"Segment fetch failed: "+lastError.message,originalError:lastError,segmentUri:segment.uri}),this._fetchQueue.delete(queueKey),[2,null]);case 20:return[2]}var uri,clean})}).call(this)},_proto._loadMap=function(map){return _async_to_generator$1$1(function(){var mapKey,cached,_this__config_segmentRetryCount,_this__config_segmentRetryDelay,_this__config_segmentRetryBackoff,mapUrl,result,attempt,maxRetries,delay,backoff,_this__config_segmentTimeout,err,oldestKey,error,lastError;return _ts_generator$1$2(this,function(_state){switch(_state.label){case 0:if(mapKey=segmentCacheKey(map.uri,map.byteRange),cached=this._mapDataCache.get(mapKey))return[2,cached];if(this._isDestroyed)return[2,null];_state.label=1;case 1:_state.trys.push([1,9,,10]),this._logger.debug("Fetching EXT-X-MAP uri="+map.uri),mapUrl=this._config.resolveRelativeUris&&this._config.baseUrl?resolveUri(map.uri,this._config.baseUrl):map.uri,attempt=0,maxRetries=this._config.playlistType===PlaylistType.LIVE?0:null!=(_this__config_segmentRetryCount=this._config.segmentRetryCount)?_this__config_segmentRetryCount:5,delay=null!=(_this__config_segmentRetryDelay=this._config.segmentRetryDelay)?_this__config_segmentRetryDelay:500,backoff=null!=(_this__config_segmentRetryBackoff=this._config.segmentRetryBackoff)?_this__config_segmentRetryBackoff:2,_state.label=2;case 2:_state.label=3;case 3:return _state.trys.push([3,5,,7]),[4,this._fetcher.fetchSegment(mapUrl,map.byteRange,{timeout:null!=(_this__config_segmentTimeout=this._config.segmentTimeout)?_this__config_segmentTimeout:void 0})];case 4:return result=_state.sent(),[3,8];case 5:if(err=_state.sent(),++attempt>maxRetries||this._isDestroyed)throw err;return this._logger.warn("EXT-X-MAP fetch failed uri="+map.uri+", retrying ("+attempt+"/"+maxRetries+") in "+delay+"ms"),[4,new Promise(function(resolve){return setTimeout(resolve,delay)})];case 6:return _state.sent(),delay=Math.min(delay*backoff,5e3),[3,7];case 7:return[3,2];case 8:return this._isDestroyed?[2,null]:(this._mapDataCache.size>=this._MAX_MAP_CACHE&&(oldestKey=this._mapDataCache.keys().next().value)&&this._mapDataCache.delete(oldestKey),this._mapDataCache.set(mapKey,result.data),this._callbacks.onMapLoaded({mapUri:mapUrl,data:result.data}),[2,result.data]);case 9:return error=_state.sent(),this._isDestroyed?[2,null]:"AbortError"===(lastError=error).name?(this._callbacks.onError({type:"TIMEOUT",subType:"MAP",message:"EXT-X-MAP fetch timed out: "+map.uri,originalError:lastError,segmentUri:map.uri}),[2,null]):(this._logger.warn("EXT-X-MAP fetch failed for "+map.uri+": "+lastError.message),this._callbacks.onError({type:"NETWORK",subType:"MAP",message:"EXT-X-MAP fetch failed: "+lastError.message,originalError:lastError,segmentUri:map.uri}),[2,null]);case 10:return[2]}})}).call(this)},Constructor=SegmentManager,(protoProps=[{key:"totalDuration",get:function(){return this._segments.reduce(function(sum,s){return sum+s.duration},0)}},{key:"bufferedDuration",get:function(){return this._cache.getSegmentsInOrder().reduce(function(sum,segment){return sum+segment.duration},0)}}])&&function(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}(Constructor.prototype,protoProps),SegmentManager}();function _array_like_to_array$3(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function asyncGeneratorStep$c(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$c(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$c(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$c(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _extends$7(){return _extends$7=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$7.apply(this,arguments)}function _set_prototype_of$4(o,p){return _set_prototype_of$4=Object.setPrototypeOf||function(o,p){return o.__proto__=p,o},_set_prototype_of$4(o,p)}function _create_for_of_iterator_helper_loose$3(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o){if(o){if("string"==typeof o)return _array_like_to_array$3(o,void 0);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array$3(o,void 0):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}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 _ts_generator$c(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var HlsIO=function(EventEmitter){function HlsIO(config){var _this;return(_this=EventEmitter.call(this)||this)._playlistManager=null,_this._segmentManager=null,_this._currentPlaylist=null,_this._isRunning=!1,_this._isDestroyed=!1,_this._duration=0,_this._bufferedTime=0,_this._durationSegmentKeys=new Set,_this._downloadedSegmentKeys=new Set,_this._config=deepmerge.all([DEFAULT_CONFIG,config],{clone:!1}),_this._logger=new Logger("HLS-IO",_this._config.debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),_this._logger.info("Initializing HlsIO with config:",_this._config),_this._fetcher=new Fetcher(_extends$7({},_this._config.fetchOptions),_this._config.debug,_this._config.timeout),_this._decryptor=new Decryptor({useWebCrypto:!0}),_this._logger.info("HlsIO initialized"),_this}!function(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),superClass&&_set_prototype_of$4(subClass,superClass)}(HlsIO,EventEmitter);var Constructor,protoProps,_proto=HlsIO.prototype;return _proto.start=function(url){return _async_to_generator$c(function(){var _this,result,mediaPlaylist,error;return _ts_generator$c(this,function(_state){switch(_state.label){case 0:if(_this=this,this._isDestroyed)throw new Error("HlsIO has been destroyed");if(this._isRunning)return this._logger.warn("HlsIO is already running"),[2];if(this._isRunning=!0,this._logger.info("Starting HlsIO..."),url&&(this._config.url=url),!this._config.url)throw new Error("HlsIO: url is required");_state.label=1;case 1:return _state.trys.push([1,3,,4]),this._config.heartbeatInterval,this._playlistManager=new PlaylistManager(this._fetcher,{url:this._config.url,playlistType:this._config.playlistType,playlistRefreshInterval:this._config.playlistRefreshInterval,lowLatencyMode:this._config.lowLatencyMode,resolveRelativeUris:this._config.resolveRelativeUris,baseUrl:this._config.baseUrl||this._config.url,followRedirectUrl:this._config.followRedirectUrl},{onPlaylistLoaded:function(playlist){return _this._onPlaylistLoaded(playlist)},onSegmentsUpdated:function(segments,playlist){return _this._onSegmentsUpdated(segments,playlist)},onPartialSegments:function(parts){return _this._onPartialSegments(parts)},onPlaylistTypeDetected:function(type){return _this.emit(HlsIOEvents.PLAYLIST_TYPE_DETECTED,type)},onEnded:function(){return _this._onEnded()},onError:function(error){return _this.emit(HlsIOEvents.ERROR,error)}},this._config.debug),[4,this._playlistManager.start()];case 2:return result=_state.sent(),this._isMediaPlaylist(result)?this._onPlaylistLoaded(result):(mediaPlaylist=this._playlistManager.getLastPlaylist())&&this._onPlaylistLoaded(mediaPlaylist),[3,4];case 3:throw error=_state.sent(),this._logger.error("Start failed: "+error.message),this.emit(HlsIOEvents.ERROR,{type:"NETWORK",message:"Failed to start: "+error.message,originalError:error,playlistUrl:this._config.url}),this._isRunning=!1,error;case 4:return[2]}})}).call(this)},_proto.stop=function(){this._logger.info("Stopping HlsIO..."),this._isRunning=!1,this._fetcher.stopHeartbeat(),this._fetcher.cancelAll(),this._playlistManager&&(this._playlistManager.destroy(),this._playlistManager=null),this._segmentManager&&(this._segmentManager.destroy(),this._segmentManager=null),this._currentPlaylist=null,this._setDuration(0),this._setBufferedTime(0),this._durationSegmentKeys.clear(),this._downloadedSegmentKeys.clear()},_proto.destroy=function(){this.stop(),this._isDestroyed=!0,this.removeAllListeners(),this._logger.info("HlsIO destroyed")},_proto.switchUrl=function(newUrl){return _async_to_generator$c(function(){return _ts_generator$c(this,function(_state){switch(_state.label){case 0:if(this._isDestroyed)throw new Error("HlsIO has been destroyed — cannot switch URL");return this._logger.info("Switching URL to "+newUrl),this.stop(),this._currentPlaylist=null,[4,this.start(newUrl)];case 1:return _state.sent(),[2]}})}).call(this)},_proto.advanceByTime=function(seconds){for(var consumed=[],remaining=seconds,maxIterations=Math.max(this.segments.length,1),iterations=0;remaining>0&&iterations<maxIterations;){iterations++;var next=this.advance();if(!next)break;consumed.push(next),remaining-=next.duration}return consumed},_proto.getNextSegment=function(){var _this__segmentManager;return(null==(_this__segmentManager=this._segmentManager)?void 0:_this__segmentManager.getNextSegment())||null},_proto.advance=function(){var _this__segmentManager;return(null==(_this__segmentManager=this._segmentManager)?void 0:_this__segmentManager.advanceToNext())||null},_proto.fetchSegment=function(sequence){return _async_to_generator$c(function(){return _ts_generator$c(this,function(_state){return this._segmentManager?[2,this._segmentManager.fetchSegment(sequence)]:[2,null]})}).call(this)},_proto.getCacheStats=function(){var _this__segmentManager;return(null==(_this__segmentManager=this._segmentManager)?void 0:_this__segmentManager.getCacheStats())||null},_proto.setDebug=function(debug){this._config.debug=debug,this._logger.setLevel(debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),this._decryptor.setDebug(debug)},_proto.setCorsMode=function(mode,credentials){var _this__config_fetchOptions;this._fetcher.updateFetchOptions({mode:mode,credentials:credentials||(null==(_this__config_fetchOptions=this._config.fetchOptions)?void 0:_this__config_fetchOptions.credentials)})},_proto.setKeyProvider=function(keyProvider){this._decryptor.updateConfig({keyProvider:keyProvider})},_proto._accumulateDurationFromSegments=function(segments){for(var _step,addedDuration=0,_iterator=_create_for_of_iterator_helper_loose$3(segments);!(_step=_iterator()).done;){var segment=_step.value,key=segmentCacheKey(segment.uri,segment.byteRange);this._durationSegmentKeys.has(key)||(this._durationSegmentKeys.add(key),addedDuration+=segment.duration)}addedDuration>0&&this._setDuration(this._duration+addedDuration)},_proto._setDuration=function(nextDuration){this._duration!==nextDuration&&(this._duration=nextDuration,this.emit(HlsIOEvents.DURATION_UPDATED,this._duration))},_proto._setBufferedTime=function(nextBufferedTime){this._bufferedTime!==nextBufferedTime&&(this._bufferedTime=nextBufferedTime,this.emit(HlsIOEvents.BUFFERED_TIME_UPDATED,this._bufferedTime))},_proto._pruneDedupSets=function(segments){for(var _step,currentKeys=new Set(segments.map(function(s){return segmentCacheKey(s.uri,s.byteRange)})),_iterator=_create_for_of_iterator_helper_loose$3(this._durationSegmentKeys);!(_step=_iterator()).done;){var key=_step.value;currentKeys.has(key)||this._durationSegmentKeys.delete(key)}for(var _step1,_iterator1=_create_for_of_iterator_helper_loose$3(this._downloadedSegmentKeys);!(_step1=_iterator1()).done;){var key1=_step1.value;currentKeys.has(key1)||this._downloadedSegmentKeys.delete(key1)}},_proto._onPlaylistLoaded=function(playlist){var _this__currentPlaylist,_this=this,previousType=null==(_this__currentPlaylist=this._currentPlaylist)?void 0:_this__currentPlaylist.type,isFirstLoad=!this._segmentManager;this._currentPlaylist=playlist,this._pruneDedupSets(playlist.segments),this._accumulateDurationFromSegments(playlist.segments),this._segmentManager?this._segmentManager.setPlaylistType(playlist.type):this._segmentManager=new SegmentManager(this._fetcher,this._decryptor,{playlistType:playlist.type,bufferAhead:this._config.bufferAhead,maxCacheSize:this._config.maxCacheSize,cachePolicy:this._config.cachePolicy,resolveRelativeUris:this._config.resolveRelativeUris,baseUrl:this._config.baseUrl||this._config.url,segmentRetryCount:this._config.segmentRetryCount,segmentRetryDelay:this._config.segmentRetryDelay,segmentRetryBackoff:this._config.segmentRetryBackoff,segmentTimeout:this._config.segmentTimeout||this._config.timeout,targetDuration:playlist.targetDuration},{onSegmentReady:function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange);_this._downloadedSegmentKeys.has(key)||(_this._downloadedSegmentKeys.add(key),_this._setBufferedTime(_this._bufferedTime+segment.duration)),_this.emit(HlsIOEvents.SEGMENT_READY,segment)},onLastSegment:function(segment){_this.emit(HlsIOEvents.LAST_SEGMENT,segment),_this._config.onLastSegment&&_this._config.onLastSegment()},onDiscontinuity:function(segment){_this.emit(HlsIOEvents.DISCONTINUITY,segment)},onPartSegment:function(part){_this.emit(HlsIOEvents.PART_SEGMENT,part)},onMapLoaded:function(info){_this.emit(HlsIOEvents.MAP_LOADED,info)},onBufferStall:function(info){_this.emit(HlsIOEvents.BUFFER_STALL,info)},onError:function(error){"TIMEOUT"===error.type&&_this.emit(HlsIOEvents.TIMEOUT,error),_this.emit(HlsIOEvents.ERROR,error)},onDecrypting:function(segment){_this.emit(HlsIOEvents.DECRYPTING,segment)},onDecrypted:function(segment){_this.emit(HlsIOEvents.DECRYPTED,segment)}},this._config.debug),(isFirstLoad||playlist.type!==PlaylistType.LIVE||previousType!==playlist.type)&&this._segmentManager.updateSegments(playlist.segments,playlist.partialSegments),this.emit(HlsIOEvents.PLAYLIST_LOADED,playlist),this.emit(HlsIOEvents.MANIFEST_PARSED,playlist)},_proto._onSegmentsUpdated=function(newSegments,playlist){this._currentPlaylist=playlist,this._pruneDedupSets(playlist.segments),this._accumulateDurationFromSegments(newSegments),this.emit(HlsIOEvents.SEGMENTS_UPDATED,newSegments),this._segmentManager&&this._segmentManager.updateSegments(playlist.segments,playlist.partialSegments)},_proto._onPartialSegments=function(parts){for(var _step,_iterator=_create_for_of_iterator_helper_loose$3(parts);!(_step=_iterator()).done;){var part=_step.value;this.emit(HlsIOEvents.PART_SEGMENT,part)}},_proto._onEnded=function(){this._fetcher.stopHeartbeat(),this.emit(HlsIOEvents.ENDED)},_proto._isMediaPlaylist=function(playlist){return"segments"in playlist&&Array.isArray(playlist.segments)},Constructor=HlsIO,(protoProps=[{key:"duration",get:function(){return this._duration}},{key:"bufferedTime",get:function(){return this._bufferedTime}},{key:"playlistType",get:function(){var _this__currentPlaylist;return(null==(_this__currentPlaylist=this._currentPlaylist)?void 0:_this__currentPlaylist.type)||this._config.playlistType}},{key:"playlist",get:function(){return this._currentPlaylist}},{key:"segments",get:function(){var _this__currentPlaylist;return(null==(_this__currentPlaylist=this._currentPlaylist)?void 0:_this__currentPlaylist.segments)||[]}},{key:"running",get:function(){return this._isRunning}}])&&function(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}(Constructor.prototype,protoProps),HlsIO}(EventEmitter);HlsIO.VERSION="0.1.0-beta.2",HlsIO.EVENTS=HlsIOEvents;
package/dist/adapter.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*
2
2
  *
3
- * JsPlugin.js v9.0.6-beta.5
3
+ * JsPlugin.js v9.0.6
4
4
  * Copyright (c) 2026-7-13 Ezviz-OpenBiz
5
5
  * Released under MIT the License.
6
6
  *
@@ -13,7 +13,7 @@
13
13
  */Logger.NOOP=function(){},Logger.LEVEL={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},(
14
14
  /*
15
15
  * @skax/hls-io v0.1.0-beta.2
16
- * Copyright (c) 2026-05-17
16
+ * Copyright (c) 2026-05-17
17
17
  * Released under the MIT License.
18
18
  */
19
19
  HLSTag={}).EXTM3U="#EXTM3U",HLSTag.EXTINF="#EXTINF",HLSTag.EXT_X_BYTERANGE="#EXT-X-BYTERANGE",HLSTag.EXT_X_DISCONTINUITY="#EXT-X-DISCONTINUITY",HLSTag.EXT_X_KEY="#EXT-X-KEY",HLSTag.EXT_X_MAP="#EXT-X-MAP",HLSTag.EXT_X_PROGRAM_DATE_TIME="#EXT-X-PROGRAM-DATE-TIME",HLSTag.EXT_X_DATERANGE="#EXT-X-DATERANGE",HLSTag.EXT_X_TARGETDURATION="#EXT-X-TARGETDURATION",HLSTag.EXT_X_MEDIA_SEQUENCE="#EXT-X-MEDIA-SEQUENCE",HLSTag.EXT_X_DISCONTINUITY_SEQUENCE="#EXT-X-DISCONTINUITY-SEQUENCE",HLSTag.EXT_X_ENDLIST="#EXT-X-ENDLIST",HLSTag.EXT_X_PLAYLIST_TYPE="#EXT-X-PLAYLIST-TYPE",HLSTag.EXT_X_I_FRAMES_ONLY="#EXT-X-I-FRAMES-ONLY",HLSTag.EXT_X_MEDIA="#EXT-X-MEDIA",HLSTag.EXT_X_STREAM_INF="#EXT-X-STREAM-INF",HLSTag.EXT_X_I_FRAME_STREAM_INF="#EXT-X-I-FRAME-STREAM-INF",HLSTag.EXT_X_SESSION_DATA="#EXT-X-SESSION-DATA",HLSTag.EXT_X_SESSION_KEY="#EXT-X-SESSION-KEY",HLSTag.EXT_X_INDEPENDENT_SEGMENTS="#EXT-X-INDEPENDENT-SEGMENTS",HLSTag.EXT_X_START="#EXT-X-START",HLSTag.EXT_X_VERSION="#EXT-X-VERSION",HLSTag.EXT_X_SERVER_CONTROL="#EXT-X-SERVER-CONTROL",HLSTag.EXT_X_PART="#EXT-X-PART",HLSTag.EXT_X_PART_INF="#EXT-X-PART-INF",HLSTag.EXT_X_PRELOAD_HINT="#EXT-X-PRELOAD-HINT",HLSTag.EXT_X_RENDITION_REPORT="#EXT-X-RENDITION-REPORT",HLSTag.EXT_X_SKIP="#EXT-X-SKIP",HLSTag.EXT_X_GAP="#EXT-X-GAP",HLSTag.EXT_X_BITRATE="#EXT-X-BITRATE",HLSTag.EXT_X_ALLOW_CACHE="#EXT-X-ALLOW-CACHE",HLSTag.EXT_X_CONTENT_STEERING="#EXT-X-CONTENT-STEERING";var SegmentFormat,PlaylistType=function(PlaylistType){return PlaylistType.LIVE="LIVE",PlaylistType.VOD="VOD",PlaylistType}({});(SegmentFormat={}).TS="ts",SegmentFormat.FMP4="fmp4";var EncryptionMethod=function(EncryptionMethod){return EncryptionMethod.NONE="NONE",EncryptionMethod.AES_128="AES-128",EncryptionMethod.SAMPLE_AES="SAMPLE-AES",EncryptionMethod}({}),KeyFormat=function(KeyFormat){return KeyFormat.IDENTITY="identity",KeyFormat.COMMON_ENCRYPTION="com.apple.streamingkeydelivery",KeyFormat}({}),DEFAULT_CONFIG={url:"",playlistType:"LIVE",bufferAhead:5,maxCacheSize:50,heartbeatInterval:3e4,playlistRefreshInterval:0,fetchOptions:{},resolveRelativeUris:!0,baseUrl:"",debug:!1,lowLatencyMode:!1,partTargetDuration:0,onLastSegment:function(){},cachePolicy:"lru",followRedirectUrl:!0,timeout:3e4,segmentRetryCount:5,segmentTimeout:0,segmentRetryDelay:500,segmentRetryBackoff:2},HlsIOEvents=function(HlsIOEvents){return HlsIOEvents.PLAYLIST_LOADED="playlistLoaded",HlsIOEvents.SEGMENTS_UPDATED="segmentsUpdated",HlsIOEvents.SEGMENT_READY="segmentReady",HlsIOEvents.LAST_SEGMENT="lastSegment",HlsIOEvents.ERROR="error",HlsIOEvents.HEARTBEAT="heartbeat",HlsIOEvents.PLAYLIST_TYPE_DETECTED="playlistTypeDetected",HlsIOEvents.DISCONTINUITY="discontinuity",HlsIOEvents.ENDED="ended",HlsIOEvents.MANIFEST_PARSED="manifestParsed",HlsIOEvents.DECRYPTING="decrypting",HlsIOEvents.DECRYPTED="decrypted",HlsIOEvents.PART_SEGMENT="partSegment",HlsIOEvents.MAP_LOADED="mapLoaded",HlsIOEvents.BUFFER_STALL="bufferStall",HlsIOEvents.DURATION_UPDATED="durationUpdated",HlsIOEvents.BUFFERED_TIME_UPDATED="bufferedTimeUpdated",HlsIOEvents.TIMEOUT="timeout",HlsIOEvents}({});function _array_like_to_array$4(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function asyncGeneratorStep$4$1(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$4$1(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$4$1(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$4$1(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _extends$4$1(){return _extends$4$1=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$4$1.apply(this,arguments)}function _instanceof$1(left,right){return null!=right&&"undefined"!=typeof Symbol&&right[Symbol.hasInstance]?!!right[Symbol.hasInstance](left):left instanceof right}function _ts_generator$4$1(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var Fetcher=function(){function Fetcher(fetchOptions,debug,timeout){void 0===fetchOptions&&(fetchOptions={}),void 0===debug&&(debug=!1),void 0===timeout&&(timeout=3e4),this._heartbeatTimer=null,this._abortControllers=new Map,this._logger=new Logger("HLS-IO:Fetcher",debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),this._fetchOptions=_extends$4$1({mode:"cors",credentials:"omit"},fetchOptions),this._timeout=timeout}var _proto=Fetcher.prototype;return _proto.startHeartbeat=function(url,intervalMs,callback){var _this=this;this.stopHeartbeat(),this._logger.info("Starting heartbeat every "+intervalMs+"ms to "+url),this._heartbeatTimer=setInterval(function(){return _async_to_generator$4$1(function(){var controller,timeoutId,response,error;return _ts_generator$4$1(this,function(_state){switch(_state.label){case 0:return _state.trys.push([0,2,,3]),controller=new AbortController,timeoutId=setTimeout(function(){return controller.abort()},5e3),[4,fetch(url,_extends$4$1({method:"HEAD",signal:controller.signal},this._fetchOptions))];case 1:return response=_state.sent(),clearTimeout(timeoutId),response.ok?callback(Date.now()):this._logger.warn("Heartbeat failed with status "+response.status),[3,3];case 2:return error=_state.sent(),this._logger.warn("Heartbeat error: "+error.message),[3,3];case 3:return[2]}})}).call(_this)},intervalMs)},_proto.stopHeartbeat=function(){this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null,this._logger.info("Heartbeat stopped"))},_proto.isHeartbeatActive=function(){return null!==this._heartbeatTimer},_proto.fetch=function(url,options){return _async_to_generator$4$1(function(){var _ref,fetchOptionsHeaders,headers,optionsHeaders,headers1,mergedOptions,controller,timeoutId,effectiveTimeout,response,err;return _ts_generator$4$1(this,function(_state){switch(_state.label){case 0:if(fetchOptionsHeaders={},_instanceof$1(this._fetchOptions.headers,Headers))this._fetchOptions.headers.forEach(function(value,key){fetchOptionsHeaders[key]=value});else if(this._fetchOptions.headers)for(var key in headers=this._fetchOptions.headers)Object.prototype.hasOwnProperty.call(headers,key)&&(fetchOptionsHeaders[key]=headers[key]);if(optionsHeaders={},_instanceof$1(null==options?void 0:options.headers,Headers))options.headers.forEach(function(value,key){optionsHeaders[key]=value});else if(null==options?void 0:options.headers)for(var key1 in headers1=options.headers)Object.prototype.hasOwnProperty.call(headers1,key1)&&(optionsHeaders[key1]=headers1[key1]);mergedOptions=_extends$4$1({},this._fetchOptions,options,{headers:_extends$4$1({},fetchOptionsHeaders,optionsHeaders)}),controller=new AbortController,this._abortControllers.set(url,controller),timeoutId=null,(effectiveTimeout=null!=(_ref=null==options?void 0:options.timeout)?_ref:this._timeout)>0&&(timeoutId=setTimeout(function(){return controller.abort()},effectiveTimeout)),_state.label=1;case 1:return _state.trys.push([1,,4,5]),[4,fetch(url,_extends$4$1({},mergedOptions,{signal:controller.signal}))];case 2:if(!(response=_state.sent()).ok)throw(err=new Error("HTTP "+response.status+": "+response.statusText)).status=response.status,err;return[4,response.arrayBuffer()];case 3:return[2,{data:_state.sent(),url:response.url||url,contentType:response.headers.get("content-type")||void 0,contentLength:parseInt(response.headers.get("content-length")||"0",10)||void 0}];case 4:return timeoutId&&clearTimeout(timeoutId),this._abortControllers.delete(url),[7];case 5:return[2]}})}).call(this)},_proto.fetchSegment=function(url,byteRange,options){return _async_to_generator$4$1(function(){var headers,_byteRange_offset,start,end;return _ts_generator$4$1(this,function(_state){return headers=_extends$4$1({},(null==options?void 0:options.headers)||{}),byteRange&&(start=null!=(_byteRange_offset=byteRange.offset)?_byteRange_offset:0,end=start+byteRange.length-1,headers.Range="bytes="+start+"-"+end),[2,this.fetch(url,_extends$4$1({},options,{headers:headers}))]})}).call(this)},_proto.cancelRequest=function(url){var controller=this._abortControllers.get(url);controller&&(controller.abort(),this._abortControllers.delete(url),this._logger.debug("Cancelled request to "+url))},_proto.cancelAll=function(){for(var _step,_iterator=function(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o){if(o){if("string"==typeof o)return _array_like_to_array$4(o,void 0);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array$4(o,void 0):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._abortControllers);!(_step=_iterator()).done;){var _step_value=_step.value,url=_step_value[0];_step_value[1].abort(),this._logger.debug("Cancelled request to "+url)}this._abortControllers.clear()},_proto.updateFetchOptions=function(options){this._fetchOptions=_extends$4$1({},this._fetchOptions,options)},Fetcher}();function asyncGeneratorStep$3$1(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$3$1(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$3$1(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$3$1(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _extends$3$1(){return _extends$3$1=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$3$1.apply(this,arguments)}function _ts_generator$3$1(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var Decryptor=function(){function Decryptor(config){void 0===config&&(config={}),this._keyCache=new Map,this._pendingKeyFetches=new Map,this._MAX_KEY_CACHE_SIZE=50,this._logger=new Logger("HLS-IO:Decryptor",Logger.LEVEL.WARN),this._config=_extends$3$1({useWebCrypto:!0},config)}var _proto=Decryptor.prototype;return _proto.needsDecryption=function(segment){var _segment_key;return!((null==(_segment_key=segment.key)?void 0:_segment_key.keyFormat)&&segment.key.keyFormat!==KeyFormat.IDENTITY||!segment.key||segment.key.method===EncryptionMethod.NONE||void 0===segment.key.method)},_proto.decrypt=function(segment,data){return _async_to_generator$3$1(function(){var rawData,keyInfo;return _ts_generator$3$1(this,function(_state){if(!segment.data&&!data)throw new Error("No data to decrypt");if(rawData=data||segment.data,!(keyInfo=segment.key)||keyInfo.method===EncryptionMethod.NONE)return[2,{data:rawData,method:EncryptionMethod.NONE}];switch(this._logger.debug("Decrypting segment "+segment.uri+" with method "+keyInfo.method),keyInfo.method){case EncryptionMethod.AES_128:return[2,this._decryptAES128(segment,rawData,keyInfo)];case EncryptionMethod.SAMPLE_AES:return[2,this._decryptSampleAES(segment,rawData,keyInfo)];default:return this._logger.warn("Unknown encryption method, returning raw data"),[2,{data:rawData,method:EncryptionMethod.NONE}]}})}).call(this)},_proto.prefetchKey=function(segment){return _async_to_generator$3$1(function(){var _this,keyInfo,fetchPromise;return _ts_generator$3$1(this,function(_state){switch(_state.label){case 0:return _this=this,(keyInfo=segment.key)&&keyInfo.method!==EncryptionMethod.NONE&&keyInfo.method===EncryptionMethod.AES_128?this._config.keyProvider||!keyInfo.uri||this._keyCache.has(keyInfo.uri)?[2]:this._pendingKeyFetches.has(keyInfo.uri)?[4,this._pendingKeyFetches.get(keyInfo.uri)]:[3,2]:[2];case 1:case 3:return _state.sent(),[2];case 2:return this._logger.debug("Prefetching decryption key from "+keyInfo.uri),fetchPromise=fetch(keyInfo.uri).then(function(res){if(!res.ok)throw new Error("HTTP "+res.status);return res.arrayBuffer()}).then(function(key){if(_this._keyCache.size>=_this._MAX_KEY_CACHE_SIZE){var oldestKey=_this._keyCache.keys().next().value;oldestKey&&_this._keyCache.delete(oldestKey)}return _this._keyCache.set(keyInfo.uri,key),_this._pendingKeyFetches.delete(keyInfo.uri),key}).catch(function(err){throw _this._pendingKeyFetches.delete(keyInfo.uri),new Error("Prefetching key failed for "+keyInfo.uri+": "+err.message)}),this._pendingKeyFetches.set(keyInfo.uri,fetchPromise),[4,fetchPromise]}})}).call(this)},_proto._decryptAES128=function(segment,data,keyInfo){return _async_to_generator$3$1(function(){var _this,key,fetchPromise,iv,seq,i,cryptoKey,decrypted,error;return _ts_generator$3$1(this,function(_state){switch(_state.label){case 0:_this=this,_state.label=1;case 1:return _state.trys.push([1,14,,15]),this._config.keyProvider?[4,this._config.keyProvider(keyInfo,segment)]:[3,3];case 2:return key=_state.sent(),[3,10];case 3:return keyInfo.uri?this._keyCache.has(keyInfo.uri)?(key=this._keyCache.get(keyInfo.uri),[3,8]):[3,4]:[3,9];case 4:return this._pendingKeyFetches.has(keyInfo.uri)?[4,this._pendingKeyFetches.get(keyInfo.uri)]:[3,6];case 5:return key=_state.sent(),[3,8];case 6:return this._logger.debug("Fetching decryption key from "+keyInfo.uri),fetchPromise=fetch(keyInfo.uri).then(function(res){if(!res.ok)throw new Error("HTTP "+res.status);return res.arrayBuffer()}).then(function(k){if(_this._keyCache.size>=_this._MAX_KEY_CACHE_SIZE){var oldestKey=_this._keyCache.keys().next().value;oldestKey&&_this._keyCache.delete(oldestKey)}return _this._keyCache.set(keyInfo.uri,k),_this._pendingKeyFetches.delete(keyInfo.uri),k}).catch(function(err){throw _this._pendingKeyFetches.delete(keyInfo.uri),err}),this._pendingKeyFetches.set(keyInfo.uri,fetchPromise),[4,fetchPromise];case 7:key=_state.sent(),_state.label=8;case 8:return[3,10];case 9:throw new Error("No key URI or key provider available for AES-128 decryption");case 10:if(16!==key.byteLength)throw new Error("Invalid AES-128 key length: "+key.byteLength+" bytes (expected 16)");if(keyInfo.iv&&16===keyInfo.iv.length)iv=keyInfo.iv;else for(iv=new Uint8Array(16),seq=segment.sequence,i=0;i<8;i++)iv[15-i]=seq>>8*i&255;return this._logger.debug("Using IV: ["+Array.from(iv).map(function(b){return b.toString(16).padStart(2,"0")}).join(" ")+"]"),this._config.useWebCrypto&&"undefined"!=typeof crypto&&crypto.subtle?[4,crypto.subtle.importKey("raw",key,{name:"AES-CBC"},!1,["decrypt"])]:[3,13];case 11:return cryptoKey=_state.sent(),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:iv},cryptoKey,data)];case 12:return decrypted=_state.sent(),this._logger.debug("AES-128-CBC decryption successful"),[2,{data:decrypted,method:EncryptionMethod.AES_128}];case 13:throw new Error("Web Crypto API not available. Use a polyfill or provide a keyProvider.");case 14:throw error=_state.sent(),this._logger.error("AES-128 decryption failed: "+error.message),error;case 15:return[2]}})}).call(this)},_proto._decryptSampleAES=function(_segment,data,keyInfo){return _async_to_generator$3$1(function(){return _ts_generator$3$1(this,function(_state){return this._logger.warn("SAMPLE-AES decryption is not fully implemented. It requires container-level parsing of TS or fMP4. Returning raw data as-is."),[2,{data:data,method:keyInfo.method}]})}).call(this)},_proto.setDebug=function(debug){this._logger.setLevel(debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN)},_proto.updateConfig=function(config){this._config=_extends$3$1({},this._config,config)},Decryptor}();function getTagName(line){var colon=line.indexOf(":");return-1===colon?line:line.substring(0,colon)}function getTagAttributes(line){var colon=line.indexOf(":");return-1===colon?"":line.substring(colon+1)}function parseAttributes(attrStr){var attrs={};if(!attrStr)return attrs;for(var i=0,len=attrStr.length;i<len;){for(;i<len&&(" "===attrStr[i]||"\t"===attrStr[i]||","===attrStr[i]);)i++;if(i>=len)break;for(var nameStart=i;i<len&&"="!==attrStr[i]&&" "!==attrStr[i]&&","!==attrStr[i];)i++;for(var name=attrStr.substring(nameStart,i);i<len&&" "===attrStr[i];)i++;if(!(i>=len||"="!==attrStr[i])){for(i++;i<len&&" "===attrStr[i];)i++;var value=void 0;if(i<len&&'"'===attrStr[i]){for(var valStart=++i;i<len&&'"'!==attrStr[i];)i++;value=attrStr.substring(valStart,i),i++}else{for(var valStart1=i;i<len&&","!==attrStr[i]&&" "!==attrStr[i];)i++;value=attrStr.substring(valStart1,i)}attrs[name]=value}}return attrs}function parseResolution(res){if(!res)return null;var parts=res.split("x");if(2!==parts.length)return null;var w=parseInt(parts[0],10),h=parseInt(parts[1],10);return isNaN(w)||isNaN(h)?null:{width:w,height:h}}function parseHexBytes(hex){if(!hex.startsWith("0x")&&!hex.startsWith("0X"))return null;var hexStr=hex.substring(2);if(hexStr.length%2!=0)return null;if(!/^[0-9a-fA-F]+$/.test(hexStr))return null;for(var len=hexStr.length/2,bytes=new Uint8Array(len),i=0;i<len;i++)bytes[i]=parseInt(hexStr.substring(2*i,2*i+2),16);return bytes}function parseExtInf(line){var attrs=getTagAttributes(line),comma=attrs.indexOf(",");if(-1===comma){var duration=parseFloat(attrs);return isNaN(duration)?null:{duration:duration}}var duration1=parseFloat(attrs.substring(0,comma)),title=attrs.substring(comma+1).trim();return isNaN(duration1)?null:{duration:duration1,title:title||void 0}}function parseByteRange(line){var attrs=getTagAttributes(line),at=attrs.indexOf("@");if(-1===at){var length=parseInt(attrs,10);return isNaN(length)?null:{length:length}}var length1=parseInt(attrs.substring(0,at),10),offset=parseInt(attrs.substring(at+1),10);return isNaN(length1)?null:{length:length1,offset:isNaN(offset)?void 0:offset}}function parseEncryptionMethod(method){switch(method.toUpperCase()){case"AES-128":return EncryptionMethod.AES_128;case"SAMPLE-AES":case"SAMPLE-AES-CTR":return EncryptionMethod.SAMPLE_AES;default:return EncryptionMethod.NONE}}function parseKeyAttributes(attrs){var _parseHexBytes,format;return{method:parseEncryptionMethod(attrs.METHOD||"NONE"),uri:attrs.URI,iv:attrs.IV&&null!=(_parseHexBytes=parseHexBytes(attrs.IV))?_parseHexBytes:void 0,keyFormat:attrs.KEYFORMAT?(format=attrs.KEYFORMAT,"com.apple.streamingkeydelivery"===format?KeyFormat.COMMON_ENCRYPTION:KeyFormat.IDENTITY):void 0,keyFormatVersions:attrs.KEYFORMATVERSIONS}}function parseMapAttributes(attrs){var uri=attrs.URI;return uri?{uri:uri,byteRange:attrs.BYTERANGE?parseByteRangeText(attrs.BYTERANGE):void 0}:null}function parseByteRangeText(text){var at=text.indexOf("@");return-1===at?{length:parseInt(text,10)}:{length:parseInt(text.substring(0,at),10),offset:parseInt(text.substring(at+1),10)}}function parsePartAttributes(attrs){var duration=parseFloat(attrs.DURATION),uri=attrs.URI;return isNaN(duration)||!uri?null:{duration:duration,uri:uri,byteRange:attrs.BYTERANGE?parseByteRangeText(attrs.BYTERANGE):void 0,independent:"YES"===attrs.INDEPENDENT,gap:"YES"===attrs.GAP}}function parseServerControl(attrs){return{canSkipUntil:attrs["CAN-SKIP-UNTIL"]?parseFloat(attrs["CAN-SKIP-UNTIL"]):void 0,canSkipDateTimes:"YES"===attrs["CAN-SKIP-DATERANGES"],canBlockReload:"YES"===attrs["CAN-BLOCK-RELOAD"],holdBack:attrs["HOLD-BACK"]?parseFloat(attrs["HOLD-BACK"]):void 0,partHoldBack:attrs["PART-HOLD-BACK"]?parseFloat(attrs["PART-HOLD-BACK"]):void 0}}function parsePreloadHint(attrs){var type=attrs.TYPE,uri=attrs.URI;return type&&uri?{type:type,uri:uri,byteRangeStart:attrs["BYTERANGE-START"]?parseInt(attrs["BYTERANGE-START"],10):void 0,byteRangeLength:attrs["BYTERANGE-LENGTH"]?parseInt(attrs["BYTERANGE-LENGTH"],10):void 0}:null}function parseRenditionReport(attrs){var uri=attrs.URI;return uri?{uri:uri,lastMSN:attrs["LAST-MSN"]?parseInt(attrs["LAST-MSN"],10):void 0,lastPart:attrs["LAST-PART"]?parseInt(attrs["LAST-PART"],10):void 0}:null}function parseDateRange(attrs){var id=attrs.ID;return id?{id:id,class:attrs.CLASS,startDate:attrs["START-DATE"]||"",endDate:attrs["END-DATE"],duration:attrs.DURATION?parseFloat(attrs.DURATION):void 0,plannedDuration:attrs["PLANNED-DURATION"]?parseFloat(attrs["PLANNED-DURATION"]):void 0,endOnNext:"YES"===attrs["END-ON-NEXT"],attributes:attrs}:null}function parseStreamInf(attrs){var _parseResolution,bandwidth=parseInt(attrs.BANDWIDTH,10);return isNaN(bandwidth)?null:{bandwidth:bandwidth,averageBandwidth:attrs["AVERAGE-BANDWIDTH"]?parseInt(attrs["AVERAGE-BANDWIDTH"],10):void 0,codecs:attrs.CODECS,resolution:attrs.RESOLUTION&&null!=(_parseResolution=parseResolution(attrs.RESOLUTION))?_parseResolution:void 0,frameRate:attrs["FRAME-RATE"]?parseFloat(attrs["FRAME-RATE"]):void 0,hdcpLevel:attrs["HDCP-LEVEL"],audio:attrs.AUDIO,video:attrs.VIDEO,subtitles:attrs.SUBTITLES,closedCaptions:attrs["CLOSED-CAPTIONS"],score:attrs.SCORE?parseFloat(attrs.SCORE):void 0}}function parseM3U8(text,baseUrl){return function(text){return text.includes("#EXT-X-STREAM-INF")}(text)?{type:"master",playlist:parseMasterPlaylist(text,baseUrl)}:{type:"media",playlist:parseMediaPlaylist(text,baseUrl)}}function parseMediaPlaylist(text,baseUrl){for(var allowCache,independentSegments,startOffset,partTargetDuration,serverControl,preloadHint,currentKey,currentMap,currentByteRange,currentProgramDateTime,currentDateRange,currentBitrate,lines=text.split(/\r?\n/),segments=[],partialSegments=[],renditionReports=[],version=3,playlistType=PlaylistType.LIVE,targetDuration=0,mediaSequence=0,discontinuitySequence=0,iFramesOnly=!1,currentDiscontinuity=!1,currentGap=!1,totalDuration=0,segmentIndex=0,i=0;i<lines.length;){var line=lines[i].trim();if(!line||line.startsWith("#")&&!line.startsWith("#EXT"))i++;else{if(line.startsWith("#EXT")){var tagName=getTagName(line),attrStr=getTagAttributes(line),attrs=parseAttributes(attrStr);switch(tagName){case"#EXTM3U":break;case"#EXT-X-VERSION":version=parseInt(attrStr,10)||3;break;case"#EXT-X-PLAYLIST-TYPE":"VOD"===attrStr?playlistType=PlaylistType.VOD:"EVENT"===attrStr&&(playlistType=PlaylistType.LIVE);break;case"#EXT-X-TARGETDURATION":targetDuration=parseFloat(attrStr)||0;break;case"#EXT-X-MEDIA-SEQUENCE":mediaSequence=parseInt(attrStr,10)||0;break;case"#EXT-X-DISCONTINUITY-SEQUENCE":discontinuitySequence=parseInt(attrStr,10)||0;break;case"#EXT-X-ENDLIST":playlistType=PlaylistType.VOD;break;case"#EXT-X-ALLOW-CACHE":allowCache="YES"===attrStr;break;case"#EXT-X-INDEPENDENT-SEGMENTS":independentSegments=!0;break;case"#EXT-X-START":startOffset=attrs["TIME-OFFSET"]?parseFloat(attrs["TIME-OFFSET"]):void 0;break;case"#EXT-X-I-FRAMES-ONLY":iFramesOnly=!0;break;case"#EXT-X-PART-INF":partTargetDuration=attrs["PART-TARGET"]?parseFloat(attrs["PART-TARGET"]):void 0;break;case"#EXT-X-SERVER-CONTROL":serverControl=parseServerControl(attrs);break;case"#EXT-X-KEY":(currentKey=parseKeyAttributes(attrs))&&currentKey.uri&&baseUrl&&(currentKey.uri=resolveAgainstBase(currentKey.uri,baseUrl));break;case"#EXT-X-MAP":var _parseMapAttributes;(currentMap=null!=(_parseMapAttributes=parseMapAttributes(attrs))?_parseMapAttributes:void 0)&&currentMap.uri&&baseUrl&&(currentMap.uri=resolveAgainstBase(currentMap.uri,baseUrl));break;case"#EXT-X-DISCONTINUITY":currentDiscontinuity=!0,discontinuitySequence++;break;case"#EXT-X-GAP":currentGap=!0;break;case"#EXT-X-BITRATE":currentBitrate=parseInt(attrStr,10)||void 0;break;case"#EXT-X-PROGRAM-DATE-TIME":currentProgramDateTime=new Date(attrStr);break;case"#EXT-X-DATERANGE":var dateRange=parseDateRange(attrs);dateRange&&(currentDateRange=dateRange);break;case"#EXTINF":var info=parseExtInf(line);if(++i<lines.length){var uri=lines[i].trim();if(uri&&!uri.startsWith("#")){var _ref,resolvedUri=baseUrl?resolveAgainstBase(uri,baseUrl):uri,segment={sequence:mediaSequence+segmentIndex,duration:null!=(_ref=null==info?void 0:info.duration)?_ref:0,uri:resolvedUri,title:null==info?void 0:info.title,byteRange:currentByteRange,key:currentKey,map:currentMap,programDateTime:currentProgramDateTime,discontinuity:currentDiscontinuity,gap:currentGap,dateRange:currentDateRange,bitrate:currentBitrate};segments.push(segment),totalDuration+=segment.duration,segmentIndex++}}currentDiscontinuity=!1,currentGap=!1,currentByteRange=void 0,currentProgramDateTime=void 0,currentDateRange=void 0,currentBitrate=void 0;break;case"#EXT-X-BYTERANGE":var _parseByteRange;currentByteRange=null!=(_parseByteRange=parseByteRange(line))?_parseByteRange:void 0;break;case"#EXT-X-PART":var part=parsePartAttributes(attrs);part&&(part.uri=baseUrl?resolveAgainstBase(part.uri,baseUrl):part.uri,partialSegments.push(part));break;case"#EXT-X-PRELOAD-HINT":var hint=parsePreloadHint(attrs);hint&&(hint.uri=baseUrl?resolveAgainstBase(hint.uri,baseUrl):hint.uri,preloadHint=hint);break;case"#EXT-X-RENDITION-REPORT":var report=parseRenditionReport(attrs);report&&(report.uri=baseUrl?resolveAgainstBase(report.uri,baseUrl):report.uri,renditionReports.push(report))}}i++}}return{type:playlistType,version:version,targetDuration:targetDuration,mediaSequence:mediaSequence,discontinuitySequence:discontinuitySequence,segments:segments,partialSegments:partialSegments.length>0?partialSegments:void 0,preloadHint:preloadHint,renditionReports:renditionReports.length>0?renditionReports:void 0,serverControl:serverControl,allowCache:allowCache,independentSegments:independentSegments,startOffset:startOffset,iFramesOnly:iFramesOnly,partTargetDuration:partTargetDuration,duration:totalDuration,endTime:totalDuration,raw:text}}function parseMasterPlaylist(text,baseUrl){for(var independentSegments,lines=text.split(/\r?\n/),variants=[],mediaRenditions=[],sessionData={},sessionKeys=[],version=3,currentStreamAttrs=null,i=0;i<lines.length;i++){var line=lines[i].trim();if(line&&(!line.startsWith("#")||line.startsWith("#EXT"))&&line.startsWith("#EXT")){var tagName=getTagName(line),attrStr=getTagAttributes(line),attrs=parseAttributes(attrStr);switch(tagName){case"#EXTM3U":break;case"#EXT-X-VERSION":version=parseInt(attrStr,10)||3;break;case"#EXT-X-INDEPENDENT-SEGMENTS":independentSegments=!0;break;case"#EXT-X-STREAM-INF":if(currentStreamAttrs=attrs,++i<lines.length){var uri=lines[i].trim();if(uri&&!uri.startsWith("#")){var info=parseStreamInf(currentStreamAttrs);info&&variants.push({uri:baseUrl?resolveAgainstBase(uri,baseUrl):uri,bandwidth:info.bandwidth,averageBandwidth:info.averageBandwidth,codecs:info.codecs,resolution:info.resolution,frameRate:info.frameRate,hdcpLevel:info.hdcpLevel,audio:info.audio,video:info.video,subtitles:info.subtitles,closedCaptions:info.closedCaptions,score:info.score,attributes:currentStreamAttrs})}}currentStreamAttrs=null;break;case"#EXT-X-I-FRAME-STREAM-INF":var info1=parseStreamInf(attrs),uri1=attrs.URI;info1&&uri1&&variants.push({uri:baseUrl?resolveAgainstBase(uri1,baseUrl):uri1,bandwidth:info1.bandwidth,codecs:info1.codecs,resolution:info1.resolution,attributes:attrs});break;case"#EXT-X-MEDIA":var rendition={type:attrs.TYPE||"AUDIO",uri:attrs.URI?baseUrl?resolveAgainstBase(attrs.URI,baseUrl):attrs.URI:void 0,groupId:attrs["GROUP-ID"]||"",language:attrs.LANGUAGE,assocLanguage:attrs["ASSOC-LANGUAGE"],name:attrs.NAME||"",default:"YES"===attrs.DEFAULT,autoselect:"YES"===attrs.AUTOSELECT,forced:"YES"===attrs.FORCED,instreamId:attrs["INSTREAM-ID"],characteristics:attrs.CHARACTERISTICS,channels:attrs.CHANNELS};mediaRenditions.push(rendition);break;case"#EXT-X-SESSION-DATA":attrs["DATA-ID"]&&attrs.VALUE&&(sessionData[attrs["DATA-ID"]]=attrs.VALUE);break;case"#EXT-X-SESSION-KEY":var keyInfo=parseKeyAttributes(attrs);keyInfo&&keyInfo.uri&&baseUrl&&(keyInfo.uri=resolveAgainstBase(keyInfo.uri,baseUrl)),sessionKeys.push(keyInfo)}}}return{version:version,variants:variants,mediaRenditions:mediaRenditions.length>0?mediaRenditions:void 0,sessionData:Object.keys(sessionData).length>0?sessionData:void 0,sessionKeys:sessionKeys.length>0?sessionKeys:void 0,independentSegments:independentSegments,raw:text}}function resolveAgainstBase(uri,baseUrl){if(/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(uri))return uri;if(uri.startsWith("//"))return"https:"+uri;if(uri.startsWith("/"))try{var base=new URL(baseUrl);return base.protocol+"//"+base.host+uri}catch(unused){return uri}return baseUrl.substring(0,baseUrl.lastIndexOf("/")+1)+uri}function resolveUri(uri,baseUrl){if(!uri)return baseUrl;if(function(uri){return/^([a-zA-Z][a-zA-Z0-9+\-.]*:|\/\/)/.test(uri)}(uri))return uri;if(function(uri){return/^\/\//.test(uri)}(uri))return"undefined"!=typeof window&&window.location?window.location.protocol+uri:"https:"+uri;if(uri.startsWith("/")){var base=new URL(baseUrl);return base.protocol+"//"+base.host+uri}var resolved=baseUrl.substring(0,baseUrl.lastIndexOf("/")+1)+uri;if(resolved.includes("../")||resolved.includes("./"))try{return new URL(resolved).href}catch(unused){return resolved}return resolved}function segmentCacheKey(uri,byteRange){var _byteRange_offset,cleanUri=function(uri){return uri.split("?")[0].split("#")[0]}(uri);return byteRange?cleanUri+"#"+(null!=(_byteRange_offset=byteRange.offset)?_byteRange_offset:0)+"-"+byteRange.length:cleanUri}function asyncGeneratorStep$2$1(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$2$1(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$2$1(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$2$1(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _ts_generator$2$1(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var PlaylistManager=function(){function PlaylistManager(fetcher,config,callbacks,debug){void 0===debug&&(debug=!1),this._pollTimer=null,this._isDestroyed=!1,this._lastPlaylist=null,this._lastETag=null,this._lastModified=null,this._segmentUpdateSeq=0,this._pollCount=0,this._isPollRequestInFlight=!1,this._lastPollHadChanges=!1,this._fetcher=fetcher,this._config=config,this._logger=new Logger("HLS-IO:Playlist",debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),this._callbacks=callbacks,this._originalUrl=config.url,this._playlistUrl=config.url,this.playlistUrl=config.url}var _proto=PlaylistManager.prototype;return _proto.start=function(){return _async_to_generator$2$1(function(){var result,variant,variantUrl,mediaResult;return _ts_generator$2$1(this,function(_state){switch(_state.label){case 0:return this._logger.info("Loading playlist: "+this._playlistUrl),[4,this._loadPlaylist()];case 1:if("master"!==(result=_state.sent()).type)return[3,6];if(this._logger.info("Master playlist detected, selecting first variant"),!(result.playlist.variants.length>0))return[3,5];variant=result.playlist.variants[0],variantUrl=this._config.resolveRelativeUris?resolveUri(variant.uri,this._config.baseUrl||this._playlistUrl):variant.uri,this._playlistUrl=variantUrl,this.playlistUrl=variantUrl,_state.label=2;case 2:return _state.trys.push([2,,4,5]),[4,this._loadPlaylist()];case 3:return"media"===(mediaResult=_state.sent()).type?(this._handleMediaPlaylist(mediaResult.playlist),[2,mediaResult.playlist]):[3,5];case 4:return[7];case 5:return[2,result.playlist];case 6:return this._handleMediaPlaylist(result.playlist),[2,result.playlist]}})}).call(this)},_proto.destroy=function(){this._isDestroyed=!0,this._stopPolling(),this._lastPlaylist=null},_proto.refresh=function(){return _async_to_generator$2$1(function(){var result,error;return _ts_generator$2$1(this,function(_state){switch(_state.label){case 0:return _state.trys.push([0,2,,3]),[4,this._loadPlaylist()];case 1:return"media"===(result=_state.sent()).type?(this._handleMediaPlaylist(result.playlist),[2,result.playlist]):[3,3];case 2:return error=_state.sent(),this._logger.error("Refresh failed: "+error.message),[3,3];case 3:return[2,null]}})}).call(this)},_proto.getLastPlaylist=function(){return this._lastPlaylist},_proto._loadPlaylist=function(){return _async_to_generator$2$1(function(){var headers,result,text,baseUrl,error,lastError,err;return _ts_generator$2$1(this,function(_state){switch(_state.label){case 0:return _state.trys.push([0,2,,3]),headers={},this._lastETag&&(headers["If-None-Match"]=this._lastETag),this._lastModified&&(headers["If-Modified-Since"]=this._lastModified),[4,this._fetcher.fetch(this._playlistUrl,{headers:headers})];case 1:return result=_state.sent(),this._config.followRedirectUrl&&(null==result?void 0:result.url)!==this._playlistUrl&&(this._logger.info("Playlist URL redirected: "+this._playlistUrl+" → "+result.url),this._playlistUrl=result.url),text=(new TextDecoder).decode(result.data),baseUrl=this._config.resolveRelativeUris?this._config.baseUrl||this._playlistUrl:void 0,[2,parseM3U8(text,baseUrl)];case 2:throw error=_state.sent(),lastError=error,this._logger.warn("Playlist fetch failed: "+lastError.message),this._playlistUrl!==this._originalUrl&&(this._logger.info("Resetting URL to original: "+this._originalUrl),this._playlistUrl=this._originalUrl),err={type:"NETWORK",subType:"M3U8",message:"Failed to load playlist: "+lastError.message,originalError:lastError,playlistUrl:this._playlistUrl},this._callbacks.onError(err),this._stopPolling(),lastError;case 3:return[2]}})}).call(this)},_proto._handleMediaPlaylist=function(playlist){var _this__lastPlaylist,isFirst=!this._lastPlaylist;if((isFirst||(null==(_this__lastPlaylist=this._lastPlaylist)?void 0:_this__lastPlaylist.type)!==playlist.type)&&this._callbacks.onPlaylistTypeDetected(playlist.type),!isFirst&&this._lastPlaylist){var newSegments=this._detectNewSegments(this._lastPlaylist.segments,playlist.segments);this._lastPollHadChanges=newSegments.length>0,this._lastPollHadChanges&&(this._logger.info("Detected "+newSegments.length+" new segments"),this._segmentUpdateSeq++,this._callbacks.onSegmentsUpdated(newSegments,playlist)),playlist.partialSegments&&playlist.partialSegments.length>0&&this._callbacks.onPartialSegments(playlist.partialSegments)}this._lastPlaylist=playlist,this._callbacks.onPlaylistLoaded(playlist),playlist.type!==PlaylistType.LIVE||this._isDestroyed||this._schedulePoll(playlist),playlist.type===PlaylistType.VOD&&this._callbacks.onEnded()},_proto._detectNewSegments=function(oldSegments,newSegments){var oldSeqSet=new Set(oldSegments.map(function(s){return s.sequence}));return newSegments.filter(function(s){return!oldSeqSet.has(s.sequence)})},_proto._schedulePoll=function(playlist){var _this=this;this._stopPolling();var interval=this._config.playlistRefreshInterval;if(!Number.isFinite(interval)||interval<=0){var baseInterval=this._lastPollHadChanges?1e3*playlist.targetDuration:500*playlist.targetDuration;interval=Math.max(250,Math.min(baseInterval,2e3*playlist.targetDuration)),playlist.targetDuration<=2&&(interval=this._lastPollHadChanges?Math.max(250,1e3*playlist.targetDuration):Math.max(250,500*playlist.targetDuration))}this._logger.debug("Polling every "+interval+"ms (targetDuration="+playlist.targetDuration+")"),this._pollTimer=setInterval(function(){return _async_to_generator$2$1(function(){var result;return _ts_generator$2$1(this,function(_state){switch(_state.label){case 0:if(this._isDestroyed)return[2];if(this._isPollRequestInFlight)return this._logger.debug("Skip poll tick: previous playlist request still in flight"),[2];this._pollCount++,this._isPollRequestInFlight=!0,_state.label=1;case 1:return _state.trys.push([1,3,4,5]),[4,this._loadPlaylist()];case 2:return"media"===(result=_state.sent()).type&&this._handleMediaPlaylist(result.playlist),[3,5];case 3:return _state.sent(),[3,5];case 4:return this._isPollRequestInFlight=!1,[7];case 5:return[2]}})}).call(_this)},interval)},_proto._stopPolling=function(){this._pollTimer&&(clearInterval(this._pollTimer),this._pollTimer=null)},PlaylistManager}();function _array_like_to_array$2(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _extends$2$1(){return _extends$2$1=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$2$1.apply(this,arguments)}var SegmentCache=function(){function SegmentCache(maxSize,policy){void 0===maxSize&&(maxSize=50),void 0===policy&&(policy="lru"),this._cache=new Map,this._accessOrder=[],this._maxSize=Number.isFinite(maxSize)?Math.max(1,Math.floor(maxSize)):50,this._policy=policy,this._stats={size:0,hits:0,misses:0,evictions:0}}var Constructor,protoProps,_proto=SegmentCache.prototype;return _proto.set=function(segment,data){var key=segmentCacheKey(segment.uri,segment.byteRange);if(this._cache.has(key)){var entry=this._cache.get(key);return entry.data=data,entry.segment=segment,entry.timestamp=Date.now(),void this._updateAccess(key)}this._cache.size>=this._maxSize&&this._evict();var entry1={segment:segment,data:data,timestamp:Date.now(),key:key};this._cache.set(key,entry1),this._accessOrder.push(key),this._stats.size=this._cache.size},_proto.get=function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange),entry=this._cache.get(key);return entry?(this._stats.hits++,"lru"===this._policy&&this._updateAccess(key),entry.data):(this._stats.misses++,null)},_proto.has=function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange);return this._cache.has(key)},_proto.delete=function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange),deleted=this._cache.delete(key);return deleted&&(this._accessOrder=this._accessOrder.filter(function(k){return k!==key}),this._stats.size=this._cache.size),deleted},_proto.clear=function(){this._cache.clear(),this._accessOrder=[],this._stats.size=0},_proto.getStats=function(){return _extends$2$1({},this._stats)},_proto.evictBeforeSequence=function(sequence){for(var _step,_this=this,removed=0,_iterator=function(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o){if(o){if("string"==typeof o)return _array_like_to_array$2(o,void 0);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array$2(o,void 0):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._cache);!(_step=_iterator()).done;){var _step_value=_step.value,key=_step_value[0];_step_value[1].segment.sequence<sequence&&(this._cache.delete(key),removed++)}return this._accessOrder=this._accessOrder.filter(function(key){return _this._cache.has(key)}),this._stats.size=this._cache.size,this._stats.evictions+=removed,removed},_proto.getSegmentsInOrder=function(){return[].concat(this._cache.values()).map(function(entry){return entry.segment}).sort(function(a,b){return a.sequence-b.sequence})},_proto._evict=function(){if(0!==this._cache.size){var firstKey=this._cache.keys().next().value;void 0!==firstKey&&(this._cache.delete(firstKey),this._accessOrder=this._accessOrder.filter(function(k){return k!==firstKey}),this._stats.evictions++,this._stats.size=this._cache.size)}},_proto._updateAccess=function(key){if("lru"===this._policy){var entry=this._cache.get(key);entry&&(this._cache.delete(key),this._cache.set(key,entry))}},Constructor=SegmentCache,(protoProps=[{key:"size",get:function(){return this._cache.size}},{key:"keys",get:function(){return[].concat(this._accessOrder)}}])&&function(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}(Constructor.prototype,protoProps),SegmentCache}(),LookAheadPrefetchStrategy=function(){function LookAheadPrefetchStrategy(){}return LookAheadPrefetchStrategy.prototype.getNextSegments=function(currentSequence,allSegments,bufferAhead){var sorted=[].concat(allSegments).sort(function(a,b){return a.sequence-b.sequence}),startIndex=sorted.findIndex(function(s){return s.sequence>currentSequence});return-1===startIndex?[]:sorted.slice(startIndex,startIndex+bufferAhead)},LookAheadPrefetchStrategy}();function _array_like_to_array$1(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function asyncGeneratorStep$1$2(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$1$1(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$1$2(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$1$2(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _extends$1$1(){return _extends$1$1=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$1$1.apply(this,arguments)}function _create_for_of_iterator_helper_loose$1(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o){if(o){if("string"==typeof o)return _array_like_to_array$1(o,void 0);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array$1(o,void 0):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}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 _ts_generator$1$2(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var SegmentManager=function(){function SegmentManager(fetcher,decryptor,config,callbacks,debug){void 0===debug&&(debug=!1),this._segments=[],this._currentSequence=-1,this._fetchQueue=new Set,this._loadedSegmentKeys=new Set,this._mapDataCache=new Map,this._MAX_MAP_CACHE=10,this._isDestroyed=!1,this._pendingPartials=[],this._pendingFetchQueue=[],this._isFetchLoopRunning=!1;var normalizedMaxCacheSize=Number.isFinite(config.maxCacheSize)?Math.max(1,Math.floor(config.maxCacheSize)):50,normalizedBufferAheadRaw=Number.isFinite(config.bufferAhead)?Math.max(1,Math.floor(config.bufferAhead)):1,normalizedBufferAhead=Math.min(normalizedBufferAheadRaw,normalizedMaxCacheSize);this._fetcher=fetcher,this._cache=new SegmentCache(normalizedMaxCacheSize,config.cachePolicy),this._decryptor=decryptor,this._config=_extends$1$1({},config,{bufferAhead:normalizedBufferAhead,maxCacheSize:normalizedMaxCacheSize}),this._logger=new Logger("HLS-IO:Segment",debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),this._callbacks=callbacks,this._prefetchStrategy=new LookAheadPrefetchStrategy}var Constructor,protoProps,_proto=SegmentManager.prototype;return _proto.updateSegments=function(newSegments,partialSegments){if(!this._isDestroyed){var oldSegmentCount=this._segments.length;if(this._segments=newSegments,partialSegments){this._pendingPartials=partialSegments;for(var _step,_iterator=_create_for_of_iterator_helper_loose$1(partialSegments);!(_step=_iterator()).done;){var part=_step.value;this._callbacks.onPartSegment(part)}}this._config.playlistType===PlaylistType.LIVE?this._handleLiveSegments():this._handleVODSegments(),this._logger.debug("Segments updated: "+oldSegmentCount+" -> "+newSegments.length+", type: "+this._config.playlistType)}},_proto.fetchSegment=function(sequence){return _async_to_generator$1$1(function(){var segment;return _ts_generator$1$2(this,function(_state){return(segment=this._segments.find(function(s){return s.sequence===sequence}))?[2,this._loadSegment(segment)]:[2,null]})}).call(this)},_proto.getNextSegment=function(){var _this=this,sorted=this.getSortedSegments(),idx=sorted.findIndex(function(s){return s.sequence>_this._currentSequence});return-1===idx?null:sorted[idx]},_proto.advanceToNext=function(){var next=this.getNextSegment();return next&&(this._currentSequence=next.sequence,this._cache.evictBeforeSequence(this._currentSequence-this._config.maxCacheSize),this._config.playlistType===PlaylistType.LIVE?this._handleLiveSegments():this._handleVODSegments()),next},_proto.getCachedSegment=function(segment){return this._cache.get(segment)},_proto.getSortedSegments=function(){return[].concat(this._segments).sort(function(a,b){return a.sequence-b.sequence})},_proto.getCacheStats=function(){return this._cache.getStats()},_proto.getLastSegment=function(){var sorted=this.getSortedSegments();return sorted.length>0?sorted[sorted.length-1]:null},_proto.setPlaylistType=function(type){this._config.playlistType=type},_proto.destroy=function(){this._isDestroyed=!0,this._cache.clear(),this._segments=[],this._fetchQueue.clear(),this._loadedSegmentKeys.clear(),this._mapDataCache.clear(),this._pendingFetchQueue=[]},_proto._handleLiveSegments=function(){var _sorted_,sorted=this.getSortedSegments();if(0!==sorted.length){if(-1===this._currentSequence){for(var td=this._config.targetDuration||sorted[0].duration||6,acc=0,i=sorted.length-1;i>=0;i--)if((acc+=sorted[i].duration)>=3*td){this._currentSequence=sorted[i].sequence-1;break}-1===this._currentSequence&&(this._currentSequence=sorted[0].sequence-1)}for(var _step,_iterator=_create_for_of_iterator_helper_loose$1(sorted.slice(-this._config.bufferAhead));!(_step=_iterator()).done;){var segment=_step.value;this._cache.has(segment)||this._enqueueFetch(segment)}var oldestToKeep=(null==(_sorted_=sorted[sorted.length-1])?void 0:_sorted_.sequence)-this._config.maxCacheSize;oldestToKeep>0&&this._cache.evictBeforeSequence(oldestToKeep)}},_proto._handleVODSegments=function(){var _this=this,sorted=this.getSortedSegments();if(0!==sorted.length){for(var _step,_iterator=_create_for_of_iterator_helper_loose$1(this._prefetchStrategy.getNextSegments(this._currentSequence,sorted,this._config.bufferAhead));!(_step=_iterator()).done;){var segment=_step.value;this._cache.has(segment)||this._enqueueFetch(segment)}var buffered=sorted.filter(function(s){return s.sequence>_this._currentSequence&&_this._cache.has(s)}).length,remaining=sorted.filter(function(s){return s.sequence>_this._currentSequence}).length,needed=Math.min(this._config.bufferAhead,remaining);needed>0&&buffered<needed&&this._currentSequence>=0&&this._callbacks.onBufferStall({buffered:buffered,needed:needed})}},_proto._enqueueFetch=function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange);this._loadedSegmentKeys.has(key)||this._fetchQueue.has(key)||(this._fetchQueue.add(key),this._pendingFetchQueue.push(segment),this._processFetchQueue())},_proto._processFetchQueue=function(){return _async_to_generator$1$1(function(){var segment,key,err;return _ts_generator$1$2(this,function(_state){switch(_state.label){case 0:if(this._isFetchLoopRunning)return[2];this._isFetchLoopRunning=!0,_state.label=1;case 1:_state.trys.push([1,5,6,7]),_state.label=2;case 2:return this._pendingFetchQueue.length>0&&!this._isDestroyed?(segment=this._pendingFetchQueue.shift(),key=segmentCacheKey(segment.uri,segment.byteRange),this._loadedSegmentKeys.has(key)?(this._fetchQueue.delete(key),[3,2]):[4,this._loadSegment(segment)]):[3,4];case 3:return _state.sent(),[3,2];case 4:return[3,7];case 5:return err=_state.sent(),this._logger.error("Fetch queue processing error: "+err.message),[3,7];case 6:return this._isFetchLoopRunning=!1,[7];case 7:return[2]}})}).call(this)},_proto._loadSegment=function(segment){return _async_to_generator$1$1(function(){var queueKey,_this__config_segmentRetryCount,_this__config_segmentRetryDelay,_this__config_segmentRetryBackoff,mapData,keyErr,url,result,attempt,maxRetries,delay,backoff,_this__config_segmentTimeout,err,data,decrypted,decryptErr,format,_sorted_,sorted,lastSeq,error,lastError;return _ts_generator$1$2(this,function(_state){switch(_state.label){case 0:if(queueKey=segmentCacheKey(segment.uri,segment.byteRange),this._loadedSegmentKeys.has(queueKey))return this._fetchQueue.delete(queueKey),[2,segment];if(this._isDestroyed)return[2,null];_state.label=1;case 1:return _state.trys.push([1,19,,20]),this._logger.debug("Fetching segment seq="+segment.sequence+" uri="+segment.uri),segment.map?[4,this._loadMap(segment.map)]:[3,3];case 2:if(!(mapData=_state.sent()))return this._fetchQueue.delete(queueKey),[2,null];segment.mapData=mapData,_state.label=3;case 3:if(!this._decryptor.needsDecryption(segment))return[3,7];_state.label=4;case 4:return _state.trys.push([4,6,,7]),[4,this._decryptor.prefetchKey(segment)];case 5:return _state.sent(),[3,7];case 6:return keyErr=_state.sent(),this._callbacks.onError({type:"DECRYPT",message:"Key fetch failed for segment "+segment.uri+": "+keyErr.message,originalError:keyErr,segmentUri:segment.uri}),this._fetchQueue.delete(queueKey),[2,null];case 7:url=this._config.resolveRelativeUris&&this._config.baseUrl?resolveUri(segment.uri,this._config.baseUrl):segment.uri,attempt=0,maxRetries=this._config.playlistType===PlaylistType.LIVE?0:null!=(_this__config_segmentRetryCount=this._config.segmentRetryCount)?_this__config_segmentRetryCount:5,delay=null!=(_this__config_segmentRetryDelay=this._config.segmentRetryDelay)?_this__config_segmentRetryDelay:500,backoff=null!=(_this__config_segmentRetryBackoff=this._config.segmentRetryBackoff)?_this__config_segmentRetryBackoff:2,_state.label=8;case 8:_state.label=9;case 9:return _state.trys.push([9,11,,13]),[4,this._fetcher.fetchSegment(url,segment.byteRange,{timeout:null!=(_this__config_segmentTimeout=this._config.segmentTimeout)?_this__config_segmentTimeout:void 0})];case 10:return result=_state.sent(),[3,14];case 11:if(err=_state.sent(),++attempt>maxRetries||this._isDestroyed)throw err;return this._logger.warn("Segment fetch failed sequence="+segment.sequence+", retrying ("+attempt+"/"+maxRetries+") in "+delay+"ms"),[4,new Promise(function(resolve){return setTimeout(resolve,delay)})];case 12:return _state.sent(),delay*=backoff,[3,13];case 13:return[3,8];case 14:if(this._isDestroyed)return[2,null];if(data=result.data,segment.data=data,!this._decryptor.needsDecryption(segment))return[3,18];this._callbacks.onDecrypting(segment),_state.label=15;case 15:return _state.trys.push([15,17,,18]),[4,this._decryptor.decrypt(segment,data)];case 16:return decrypted=_state.sent(),this._isDestroyed?[2,null]:(data=decrypted.data,segment.data=data,this._callbacks.onDecrypted(segment),[3,18]);case 17:return decryptErr=_state.sent(),this._isDestroyed||(this._callbacks.onError({type:"DECRYPT",message:"Decryption failed for "+segment.uri+": "+decryptErr.message,originalError:decryptErr,segmentUri:segment.uri}),this._fetchQueue.delete(queueKey)),[2,null];case 18:return this._isDestroyed?[2,null]:(this._cache.set(segment,data),this._loadedSegmentKeys.add(queueKey),uri=segment.uri,clean=uri.split("?")[0].split("#")[0],format=clean.endsWith(".ts")||clean.endsWith(".TS")?"ts":clean.endsWith(".m4s")||clean.endsWith(".mp4")||clean.endsWith(".m4v")||clean.endsWith(".cmfv")||clean.endsWith(".cmfa")?"fmp4":"unknown",this._logger.debug("Segment "+segment.sequence+" loaded ("+format+", "+data.byteLength+" bytes)"),this._callbacks.onSegmentReady(segment),segment.discontinuity&&this._callbacks.onDiscontinuity(segment),this._config.playlistType===PlaylistType.VOD&&(sorted=this.getSortedSegments(),lastSeq=null==(_sorted_=sorted[sorted.length-1])?void 0:_sorted_.sequence,segment.sequence===lastSeq&&(this._logger.info("Last segment fetched: seq="+segment.sequence),this._callbacks.onLastSegment(segment))),this._fetchQueue.delete(queueKey),[2,segment]);case 19:return error=_state.sent(),this._isDestroyed?(this._fetchQueue.delete(queueKey),[2,null]):"AbortError"===(lastError=error).name?(this._callbacks.onError({type:"TIMEOUT",subType:"SEGMENT",message:"Segment fetch timed out: "+segment.uri,originalError:lastError,segmentUri:segment.uri}),this._fetchQueue.delete(queueKey),[2,null]):(this._logger.warn("Segment fetch failed for "+segment.uri+": "+lastError.message),this._callbacks.onError({type:"NETWORK",subType:"SEGMENT",message:"Segment fetch failed: "+lastError.message,originalError:lastError,segmentUri:segment.uri}),this._fetchQueue.delete(queueKey),[2,null]);case 20:return[2]}var uri,clean})}).call(this)},_proto._loadMap=function(map){return _async_to_generator$1$1(function(){var mapKey,cached,_this__config_segmentRetryCount,_this__config_segmentRetryDelay,_this__config_segmentRetryBackoff,mapUrl,result,attempt,maxRetries,delay,backoff,_this__config_segmentTimeout,err,oldestKey,error,lastError;return _ts_generator$1$2(this,function(_state){switch(_state.label){case 0:if(mapKey=segmentCacheKey(map.uri,map.byteRange),cached=this._mapDataCache.get(mapKey))return[2,cached];if(this._isDestroyed)return[2,null];_state.label=1;case 1:_state.trys.push([1,9,,10]),this._logger.debug("Fetching EXT-X-MAP uri="+map.uri),mapUrl=this._config.resolveRelativeUris&&this._config.baseUrl?resolveUri(map.uri,this._config.baseUrl):map.uri,attempt=0,maxRetries=this._config.playlistType===PlaylistType.LIVE?0:null!=(_this__config_segmentRetryCount=this._config.segmentRetryCount)?_this__config_segmentRetryCount:5,delay=null!=(_this__config_segmentRetryDelay=this._config.segmentRetryDelay)?_this__config_segmentRetryDelay:500,backoff=null!=(_this__config_segmentRetryBackoff=this._config.segmentRetryBackoff)?_this__config_segmentRetryBackoff:2,_state.label=2;case 2:_state.label=3;case 3:return _state.trys.push([3,5,,7]),[4,this._fetcher.fetchSegment(mapUrl,map.byteRange,{timeout:null!=(_this__config_segmentTimeout=this._config.segmentTimeout)?_this__config_segmentTimeout:void 0})];case 4:return result=_state.sent(),[3,8];case 5:if(err=_state.sent(),++attempt>maxRetries||this._isDestroyed)throw err;return this._logger.warn("EXT-X-MAP fetch failed uri="+map.uri+", retrying ("+attempt+"/"+maxRetries+") in "+delay+"ms"),[4,new Promise(function(resolve){return setTimeout(resolve,delay)})];case 6:return _state.sent(),delay=Math.min(delay*backoff,5e3),[3,7];case 7:return[3,2];case 8:return this._isDestroyed?[2,null]:(this._mapDataCache.size>=this._MAX_MAP_CACHE&&(oldestKey=this._mapDataCache.keys().next().value)&&this._mapDataCache.delete(oldestKey),this._mapDataCache.set(mapKey,result.data),this._callbacks.onMapLoaded({mapUri:mapUrl,data:result.data}),[2,result.data]);case 9:return error=_state.sent(),this._isDestroyed?[2,null]:"AbortError"===(lastError=error).name?(this._callbacks.onError({type:"TIMEOUT",subType:"MAP",message:"EXT-X-MAP fetch timed out: "+map.uri,originalError:lastError,segmentUri:map.uri}),[2,null]):(this._logger.warn("EXT-X-MAP fetch failed for "+map.uri+": "+lastError.message),this._callbacks.onError({type:"NETWORK",subType:"MAP",message:"EXT-X-MAP fetch failed: "+lastError.message,originalError:lastError,segmentUri:map.uri}),[2,null]);case 10:return[2]}})}).call(this)},Constructor=SegmentManager,(protoProps=[{key:"totalDuration",get:function(){return this._segments.reduce(function(sum,s){return sum+s.duration},0)}},{key:"bufferedDuration",get:function(){return this._cache.getSegmentsInOrder().reduce(function(sum,segment){return sum+segment.duration},0)}}])&&function(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}(Constructor.prototype,protoProps),SegmentManager}();function _array_like_to_array$3(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function asyncGeneratorStep$c(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _async_to_generator$c(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep$c(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep$c(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}function _extends$7(){return _extends$7=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends$7.apply(this,arguments)}function _set_prototype_of$4(o,p){return _set_prototype_of$4=Object.setPrototypeOf||function(o,p){return o.__proto__=p,o},_set_prototype_of$4(o,p)}function _create_for_of_iterator_helper_loose$3(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o){if(o){if("string"==typeof o)return _array_like_to_array$3(o,void 0);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array$3(o,void 0):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}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 _ts_generator$c(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),d=Object.defineProperty;return d(g,"next",{value:verb(0)}),d(g,"throw",{value:verb(1)}),d(g,"return",{value:verb(2)}),"function"==typeof Symbol&&d(g,Symbol.iterator,{value:function(){return this}}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!((t=(t=_.trys).length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}var HlsIO=function(EventEmitter){function HlsIO(config){var _this;return(_this=EventEmitter.call(this)||this)._playlistManager=null,_this._segmentManager=null,_this._currentPlaylist=null,_this._isRunning=!1,_this._isDestroyed=!1,_this._duration=0,_this._bufferedTime=0,_this._durationSegmentKeys=new Set,_this._downloadedSegmentKeys=new Set,_this._config=deepmerge.all([DEFAULT_CONFIG,config],{clone:!1}),_this._logger=new Logger("HLS-IO",_this._config.debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),_this._logger.info("Initializing HlsIO with config:",_this._config),_this._fetcher=new Fetcher(_extends$7({},_this._config.fetchOptions),_this._config.debug,_this._config.timeout),_this._decryptor=new Decryptor({useWebCrypto:!0}),_this._logger.info("HlsIO initialized"),_this}!function(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),superClass&&_set_prototype_of$4(subClass,superClass)}(HlsIO,EventEmitter);var Constructor,protoProps,_proto=HlsIO.prototype;return _proto.start=function(url){return _async_to_generator$c(function(){var _this,result,mediaPlaylist,error;return _ts_generator$c(this,function(_state){switch(_state.label){case 0:if(_this=this,this._isDestroyed)throw new Error("HlsIO has been destroyed");if(this._isRunning)return this._logger.warn("HlsIO is already running"),[2];if(this._isRunning=!0,this._logger.info("Starting HlsIO..."),url&&(this._config.url=url),!this._config.url)throw new Error("HlsIO: url is required");_state.label=1;case 1:return _state.trys.push([1,3,,4]),this._config.heartbeatInterval,this._playlistManager=new PlaylistManager(this._fetcher,{url:this._config.url,playlistType:this._config.playlistType,playlistRefreshInterval:this._config.playlistRefreshInterval,lowLatencyMode:this._config.lowLatencyMode,resolveRelativeUris:this._config.resolveRelativeUris,baseUrl:this._config.baseUrl||this._config.url,followRedirectUrl:this._config.followRedirectUrl},{onPlaylistLoaded:function(playlist){return _this._onPlaylistLoaded(playlist)},onSegmentsUpdated:function(segments,playlist){return _this._onSegmentsUpdated(segments,playlist)},onPartialSegments:function(parts){return _this._onPartialSegments(parts)},onPlaylistTypeDetected:function(type){return _this.emit(HlsIOEvents.PLAYLIST_TYPE_DETECTED,type)},onEnded:function(){return _this._onEnded()},onError:function(error){return _this.emit(HlsIOEvents.ERROR,error)}},this._config.debug),[4,this._playlistManager.start()];case 2:return result=_state.sent(),this._isMediaPlaylist(result)?this._onPlaylistLoaded(result):(mediaPlaylist=this._playlistManager.getLastPlaylist())&&this._onPlaylistLoaded(mediaPlaylist),[3,4];case 3:throw error=_state.sent(),this._logger.error("Start failed: "+error.message),this.emit(HlsIOEvents.ERROR,{type:"NETWORK",message:"Failed to start: "+error.message,originalError:error,playlistUrl:this._config.url}),this._isRunning=!1,error;case 4:return[2]}})}).call(this)},_proto.stop=function(){this._logger.info("Stopping HlsIO..."),this._isRunning=!1,this._fetcher.stopHeartbeat(),this._fetcher.cancelAll(),this._playlistManager&&(this._playlistManager.destroy(),this._playlistManager=null),this._segmentManager&&(this._segmentManager.destroy(),this._segmentManager=null),this._currentPlaylist=null,this._setDuration(0),this._setBufferedTime(0),this._durationSegmentKeys.clear(),this._downloadedSegmentKeys.clear()},_proto.destroy=function(){this.stop(),this._isDestroyed=!0,this.removeAllListeners(),this._logger.info("HlsIO destroyed")},_proto.switchUrl=function(newUrl){return _async_to_generator$c(function(){return _ts_generator$c(this,function(_state){switch(_state.label){case 0:if(this._isDestroyed)throw new Error("HlsIO has been destroyed — cannot switch URL");return this._logger.info("Switching URL to "+newUrl),this.stop(),this._currentPlaylist=null,[4,this.start(newUrl)];case 1:return _state.sent(),[2]}})}).call(this)},_proto.advanceByTime=function(seconds){for(var consumed=[],remaining=seconds,maxIterations=Math.max(this.segments.length,1),iterations=0;remaining>0&&iterations<maxIterations;){iterations++;var next=this.advance();if(!next)break;consumed.push(next),remaining-=next.duration}return consumed},_proto.getNextSegment=function(){var _this__segmentManager;return(null==(_this__segmentManager=this._segmentManager)?void 0:_this__segmentManager.getNextSegment())||null},_proto.advance=function(){var _this__segmentManager;return(null==(_this__segmentManager=this._segmentManager)?void 0:_this__segmentManager.advanceToNext())||null},_proto.fetchSegment=function(sequence){return _async_to_generator$c(function(){return _ts_generator$c(this,function(_state){return this._segmentManager?[2,this._segmentManager.fetchSegment(sequence)]:[2,null]})}).call(this)},_proto.getCacheStats=function(){var _this__segmentManager;return(null==(_this__segmentManager=this._segmentManager)?void 0:_this__segmentManager.getCacheStats())||null},_proto.setDebug=function(debug){this._config.debug=debug,this._logger.setLevel(debug?Logger.LEVEL.DEBUG:Logger.LEVEL.WARN),this._decryptor.setDebug(debug)},_proto.setCorsMode=function(mode,credentials){var _this__config_fetchOptions;this._fetcher.updateFetchOptions({mode:mode,credentials:credentials||(null==(_this__config_fetchOptions=this._config.fetchOptions)?void 0:_this__config_fetchOptions.credentials)})},_proto.setKeyProvider=function(keyProvider){this._decryptor.updateConfig({keyProvider:keyProvider})},_proto._accumulateDurationFromSegments=function(segments){for(var _step,addedDuration=0,_iterator=_create_for_of_iterator_helper_loose$3(segments);!(_step=_iterator()).done;){var segment=_step.value,key=segmentCacheKey(segment.uri,segment.byteRange);this._durationSegmentKeys.has(key)||(this._durationSegmentKeys.add(key),addedDuration+=segment.duration)}addedDuration>0&&this._setDuration(this._duration+addedDuration)},_proto._setDuration=function(nextDuration){this._duration!==nextDuration&&(this._duration=nextDuration,this.emit(HlsIOEvents.DURATION_UPDATED,this._duration))},_proto._setBufferedTime=function(nextBufferedTime){this._bufferedTime!==nextBufferedTime&&(this._bufferedTime=nextBufferedTime,this.emit(HlsIOEvents.BUFFERED_TIME_UPDATED,this._bufferedTime))},_proto._pruneDedupSets=function(segments){for(var _step,currentKeys=new Set(segments.map(function(s){return segmentCacheKey(s.uri,s.byteRange)})),_iterator=_create_for_of_iterator_helper_loose$3(this._durationSegmentKeys);!(_step=_iterator()).done;){var key=_step.value;currentKeys.has(key)||this._durationSegmentKeys.delete(key)}for(var _step1,_iterator1=_create_for_of_iterator_helper_loose$3(this._downloadedSegmentKeys);!(_step1=_iterator1()).done;){var key1=_step1.value;currentKeys.has(key1)||this._downloadedSegmentKeys.delete(key1)}},_proto._onPlaylistLoaded=function(playlist){var _this__currentPlaylist,_this=this,previousType=null==(_this__currentPlaylist=this._currentPlaylist)?void 0:_this__currentPlaylist.type,isFirstLoad=!this._segmentManager;this._currentPlaylist=playlist,this._pruneDedupSets(playlist.segments),this._accumulateDurationFromSegments(playlist.segments),this._segmentManager?this._segmentManager.setPlaylistType(playlist.type):this._segmentManager=new SegmentManager(this._fetcher,this._decryptor,{playlistType:playlist.type,bufferAhead:this._config.bufferAhead,maxCacheSize:this._config.maxCacheSize,cachePolicy:this._config.cachePolicy,resolveRelativeUris:this._config.resolveRelativeUris,baseUrl:this._config.baseUrl||this._config.url,segmentRetryCount:this._config.segmentRetryCount,segmentRetryDelay:this._config.segmentRetryDelay,segmentRetryBackoff:this._config.segmentRetryBackoff,segmentTimeout:this._config.segmentTimeout||this._config.timeout,targetDuration:playlist.targetDuration},{onSegmentReady:function(segment){var key=segmentCacheKey(segment.uri,segment.byteRange);_this._downloadedSegmentKeys.has(key)||(_this._downloadedSegmentKeys.add(key),_this._setBufferedTime(_this._bufferedTime+segment.duration)),_this.emit(HlsIOEvents.SEGMENT_READY,segment)},onLastSegment:function(segment){_this.emit(HlsIOEvents.LAST_SEGMENT,segment),_this._config.onLastSegment&&_this._config.onLastSegment()},onDiscontinuity:function(segment){_this.emit(HlsIOEvents.DISCONTINUITY,segment)},onPartSegment:function(part){_this.emit(HlsIOEvents.PART_SEGMENT,part)},onMapLoaded:function(info){_this.emit(HlsIOEvents.MAP_LOADED,info)},onBufferStall:function(info){_this.emit(HlsIOEvents.BUFFER_STALL,info)},onError:function(error){"TIMEOUT"===error.type&&_this.emit(HlsIOEvents.TIMEOUT,error),_this.emit(HlsIOEvents.ERROR,error)},onDecrypting:function(segment){_this.emit(HlsIOEvents.DECRYPTING,segment)},onDecrypted:function(segment){_this.emit(HlsIOEvents.DECRYPTED,segment)}},this._config.debug),(isFirstLoad||playlist.type!==PlaylistType.LIVE||previousType!==playlist.type)&&this._segmentManager.updateSegments(playlist.segments,playlist.partialSegments),this.emit(HlsIOEvents.PLAYLIST_LOADED,playlist),this.emit(HlsIOEvents.MANIFEST_PARSED,playlist)},_proto._onSegmentsUpdated=function(newSegments,playlist){this._currentPlaylist=playlist,this._pruneDedupSets(playlist.segments),this._accumulateDurationFromSegments(newSegments),this.emit(HlsIOEvents.SEGMENTS_UPDATED,newSegments),this._segmentManager&&this._segmentManager.updateSegments(playlist.segments,playlist.partialSegments)},_proto._onPartialSegments=function(parts){for(var _step,_iterator=_create_for_of_iterator_helper_loose$3(parts);!(_step=_iterator()).done;){var part=_step.value;this.emit(HlsIOEvents.PART_SEGMENT,part)}},_proto._onEnded=function(){this._fetcher.stopHeartbeat(),this.emit(HlsIOEvents.ENDED)},_proto._isMediaPlaylist=function(playlist){return"segments"in playlist&&Array.isArray(playlist.segments)},Constructor=HlsIO,(protoProps=[{key:"duration",get:function(){return this._duration}},{key:"bufferedTime",get:function(){return this._bufferedTime}},{key:"playlistType",get:function(){var _this__currentPlaylist;return(null==(_this__currentPlaylist=this._currentPlaylist)?void 0:_this__currentPlaylist.type)||this._config.playlistType}},{key:"playlist",get:function(){return this._currentPlaylist}},{key:"segments",get:function(){var _this__currentPlaylist;return(null==(_this__currentPlaylist=this._currentPlaylist)?void 0:_this__currentPlaylist.segments)||[]}},{key:"running",get:function(){return this._isRunning}}])&&function(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}(Constructor.prototype,protoProps),HlsIO}(EventEmitter);HlsIO.VERSION="0.1.0-beta.2",HlsIO.EVENTS=HlsIOEvents;