@playkit-js/playkit-js-hls
Version:
[](https://github.com/kaltura/playkit-js-hls/actions/workflows/run_canary_full_flow.yaml) [{"object"==typeof exports&&"object"==typeof module?module.exports=r(require("@playkit-js/playkit-js"),require("hls.js")):"function"==typeof define&&define.amd?define("playkit",["@playkit-js/playkit-js","hls.js"],r):"object"==typeof exports?exports.playkit=r(require("@playkit-js/playkit-js"),require("hls.js")):(e.playkit=e.playkit||{},e.playkit.hls=r(e.playkit.core,e.Hls))}(self,(function(e,r){return function(){"use strict";var t={230:function(r){r.exports=e},85:function(e){e.exports=r}},i={};function o(e){var r=i[e];if(void 0!==r)return r.exports;var a=i[e]={exports:{}};return t[e](a,a.exports,o),a.exports}o.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(r,{a:r}),r},o.d=function(e,r){for(var t in r)o.o(r,t)&&!o.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},o.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};return function(){o.r(a),o.d(a,{NAME:function(){return L},VERSION:function(){return O},default:function(){return C}});var e=o(230);function r(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,i=new Array(r);t<r;t++)i[t]=e[t];return i}function t(e,t){if(e){if("string"==typeof e)return r(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}function i(e,r){return function(e){if(Array.isArray(e))return e}(e)||function(e,r){var t=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=t){var i,o,a,n,s=[],l=!0,c=!1;try{if(a=(t=t.call(e)).next,0===r){if(Object(t)!==t)return;l=!1}else for(;!(l=(i=a.call(t)).done)&&(s.push(i.value),s.length!==r);l=!0);}catch(e){c=!0,o=e}finally{try{if(!l&&null!=t.return&&(n=t.return(),Object(n)!==n))return}finally{if(c)throw o}}return s}}(e,r)||t(e,r)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function l(e){var r=function(e,r){if("object"!==s(e)||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var i=t.call(e,"string");if("object"!==s(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"===s(r)?r:String(r)}function c(e,r){for(var t=0;t<r.length;t++){var i=r[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,l(i.key),i)}}function u(e,r,t){return r&&c(e.prototype,r),t&&c(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function d(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}function f(){return f="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,r,t){var i=function(e,r){for(;!Object.prototype.hasOwnProperty.call(e,r)&&null!==(e=h(e)););return e}(e,r);if(i){var o=Object.getOwnPropertyDescriptor(i,r);return o.get?o.get.call(arguments.length<3?e:t):o.value}},f.apply(this,arguments)}function _(e,r){return _=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,r){return e.__proto__=r,e},_(e,r)}function E(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),r&&_(e,r)}function g(e,r){if(r&&("object"===s(r)||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined");return d(e)}function v(e,r,t){return(r=l(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var y,p=o(85),T=o.n(p),R=JSON.parse('{"recoverDecodingErrorDelay":3000,"recoverSwapAudioCodecDelay":3000,"abr":{"enabled":true,"restrictions":{}},"hlsConfig":{"fragLoadingMaxRetry":4,"maxMaxBufferLength":60,"stretchShortVideoTrack":true},"network":{}}'),m=(v(v(v(v(v(v(v(v(v(v(y={},T().ErrorDetails.MANIFEST_LOAD_ERROR,{category:e.Error.Category.MANIFEST,code:e.Error.Code.HTTP_ERROR}),T().ErrorDetails.MANIFEST_LOAD_TIMEOUT,{category:e.Error.Category.MANIFEST,code:e.Error.Code.TIMEOUT}),T().ErrorDetails.MANIFEST_PARSING_ERROR,{category:e.Error.Category.MANIFEST,code:e.Error.Code.HLSJS_CANNOT_PARSE}),T().ErrorDetails.LEVEL_LOAD_ERROR,{category:e.Error.Category.NETWORK,code:e.Error.Code.HTTP_ERROR}),T().ErrorDetails.LEVEL_LOAD_TIMEOUT,{category:e.Error.Category.NETWORK,code:e.Error.Code.TIMEOUT}),T().ErrorDetails.LEVEL_SWITCH_ERROR,{category:e.Error.Category.PLAYER,code:e.Error.Code.BITRATE_SWITCH_ISSUE}),T().ErrorDetails.FRAG_LOAD_ERROR,{category:e.Error.Category.NETWORK,code:e.Error.Code.HTTP_ERROR}),T().ErrorDetails.FRAG_LOAD_TIMEOUT,{category:e.Error.Category.NETWORK,code:e.Error.Code.TIMEOUT}),T().ErrorDetails.FRAG_PARSING_ERROR,{category:e.Error.Category.MEDIA,code:e.Error.Code.HLS_FRAG_PARSING_ERROR}),T().ErrorDetails.BUFFER_APPEND_ERROR,{category:e.Error.Category.MEDIA,code:e.Error.Code.HLS_BUFFER_APPEND_ISSUE}),v(v(y,T().ErrorDetails.BUFFER_APPENDING_ERROR,{category:e.Error.Category.MEDIA,code:e.Error.Code.HLS_BUFFER_APPENDING_ISSUE}),T().ErrorDetails.BUFFER_STALLED_ERROR,{category:e.Error.Category.MEDIA,code:e.Error.Code.HLS_BUFFER_STALLED_ERROR}));var b=function(e){E(o,e);var r,t,i=(r=o,t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,i=h(r);if(t){var o=h(this).constructor;e=Reflect.construct(i,arguments,o)}else e=i.apply(this,arguments);return g(this,e)});function o(e){var r;return n(this,o),r=i.call(this,e),e&&e.readystatechange&&(r.readystatechange=e.readystatechange),r}return u(o,[{key:"loadInternal",value:function(){var e,r=this,t=this.context;e=this.loader=new XMLHttpRequest;var i=this.stats;i.tfirst=0,i.loaded=0;var o,a=this.xhrSetup;try{if(a)try{o=a(e,t.url,t)}catch(r){e.open("GET",t.url,!0),o=a(e,t.url,t)}e.readyState||e.open("GET",t.url,!0)}catch(e){o=Promise.reject(e)}(o=o||Promise.resolve()).then((function(){t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=r.readystatechange.bind(r),e.onprogress=r.loadprogress.bind(r),e.responseType=t.responseType,r.requestTimeout=window.setTimeout(r.loadtimeout.bind(r),r.config.timeout),e.send()})).catch((function(i){r.callbacks.onError({code:e.status,text:i.message},t,e)}))}}]),o}(T().DefaultConfig.loader);var A,k=function(r){E(a,r);var t,i,o=(t=a,i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,r=h(t);if(i){var o=h(this).constructor;e=Reflect.construct(r,arguments,o)}else e=r.apply(this,arguments);return g(this,e)});function a(r){var t;n(this,a);var i=(t=o.call(this,r)).load.bind(d(t)),s=a.redirectExternalStreamsHandler;return t.load=function(r,t,o){var n=r.url;"manifest"===r.type?e.Utils.Http.jsonp(n,s,{timeout:a.redirectExternalStreamsTimeout}).then((function(e){r.url=e,i(r,t,o)})).catch((function(){return i(r,t,o)})):i(r,t,o)},t}return u(a)}(b);function D(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,i=new Array(r);t<r;t++)i[t]=e[t];return i}v(k,"redirectExternalStreamsHandler",(function(e,r){return r}));var S=function(o){E(c,o);var a,s,l=(a=c,s=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,r=h(a);if(s){var t=h(this).constructor;e=Reflect.construct(r,arguments,t)}else e=r.apply(this,arguments);return g(this,e)});function c(r,t,i){var o;return n(this,c),v(d(o=l.call(this,r,t,i)),"_hlsjsLib",T()),v(d(o),"_triedReloadWithRedirect",!1),v(d(o),"_playerTracks",[]),v(d(o),"_startTime",0),v(d(o),"_requestFilterError",!1),v(d(o),"_responseFilterError",!1),v(d(o),"_nativeTextTracksMap",{}),v(d(o),"_lastLoadedFragSN",-1),v(d(o),"_sameFragSNLoadedCount",0),v(d(o),"_waitForSubtitleLoad",!0),v(d(o),"_adapterEventsBindings",v(v(v(v(v(v(v(v(v({},T().Events.ERROR,(function(e,r){return o._onError(r)})),T().Events.MANIFEST_LOADED,(function(e,r){return o._onManifestLoaded(r)})),T().Events.LEVEL_SWITCHED,(function(e,r){return o._onLevelSwitched(e,r)})),T().Events.AUDIO_TRACK_SWITCHED,(function(e,r){return o._onAudioTrackSwitched(e,r)})),T().Events.FPS_DROP,(function(e,r){return o._onFpsDrop(r)})),T().Events.FRAG_PARSING_METADATA,(function(e,r){return o._onFragParsingMetadata(r)})),T().Events.FRAG_LOADED,(function(e,r){return o._onFragLoaded(r)})),T().Events.MEDIA_ATTACHED,(function(){return o._onMediaAttached()})),T().Events.LEVEL_LOADED,(function(e,r){return o._onLevelLoaded(e,r)}))),v(d(o),"_onLevelLoaded",(function(r,t){if(o.isLive()){var i=t.details.endSN;if(o._lastLoadedFragSN===i){if(o._sameFragSNLoadedCount++,c._logger.debug("Same frag SN. Count is: ".concat(o._sameFragSNLoadedCount,", Max is: ").concat(o._config.network.maxStaleLevelReloads)),o._sameFragSNLoadedCount>=o._config.network.maxStaleLevelReloads){c._logger.error("Same frag loading reached max count");var a=new e.Error(e.Error.Severity.CRITICAL,e.Error.Category.NETWORK,e.Error.Code.LIVE_MANIFEST_REFRESH_ERROR,{fragSN:i});return o._trigger(e.EventType.ERROR,a),o.destroy()}c._logger.debug("Last frag SN is: ".concat(i))}else o._sameFragSNLoadedCount=0;o._lastLoadedFragSN=i}})),c._logger.debug("Creating adapter. Hls version: "+T().version),o._config=e.Utils.Object.mergeDeep({},R,o._config),o._init(),o}return u(c,[{key:"_init",value:function(){this._config.forceRedirectExternalStreams&&(this._config.hlsConfig.pLoader=k),this._maybeSetFilters(),this._hls=new(T())(this._config.hlsConfig),this._capabilities.fpsControl=!0,this._hls.subtitleDisplay=this._config.subtitleDisplay,this._addBindings()}},{key:"_maybeSetFilters",value:function(){var i=this;if("function"==typeof e.Utils.Object.getPropertyPath(this._config,"network.requestFilter")&&(c._logger.debug("Register request filter"),e.Utils.Object.mergeDeep(this._config.hlsConfig,{loader:b,xhrSetup:function(o,a,n){var s,l={url:a,body:null,headers:{}};try{"manifest"===n.type&&(s=i._config.network.requestFilter(e.RequestType.MANIFEST,l)),n.frag&&"subtitle"!==n.frag.type&&(s=i._config.network.requestFilter(e.RequestType.SEGMENT,l))}catch(e){s=Promise.reject(e)}return(s=s||Promise.resolve(l)).then((function(e){n.url=e.url,o.open("GET",e.url,!0),Object.entries(e.headers).forEach((function(e){var i;o.setRequestHeader.apply(o,function(e){if(Array.isArray(e))return r(e)}(i=e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(i)||t(i)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())})),"boolean"==typeof e.withCredentials&&(o.withCredentials=e.withCredentials)})).catch((function(e){throw i._requestFilterError=!0,e}))}})),"function"==typeof e.Utils.Object.getPropertyPath(this._config,"network.responseFilter")){var o=this;c._logger.debug("Register response filter"),e.Utils.Object.mergeDeep(this._config.hlsConfig,{loader:b,readystatechange:function(r){var t=this,i=r.currentTarget,a=i.readyState,n=this.stats,s=this.context,l=this.config;if(!n.aborted&&a>=2){window.clearTimeout(this.requestTimeout);var u=n.loading;if(0===u.first&&(u.first=Math.max(performance.now(),u.start)),4===a){var d=i.status;if(d>=200&&d<300){var h,f;u.end=Math.max(n.tfirst,performance.now()),f="arraybuffer"===s.responseType?(h=i.response).byteLength:(h=i.responseText).length,n.loaded=n.total=f;var _,E={url:i.responseURL,originalUrl:s.url,data:h,headers:e.Utils.Http.convertHeadersToDictionary(i.getAllResponseHeaders())};try{"manifest"===s.type&&(_=o._config.network.responseFilter(e.RequestType.MANIFEST,E)),s.frag&&"subtitle"!==s.frag.type&&(_=o._config.network.responseFilter(e.RequestType.SEGMENT,E))}catch(e){_=Promise.reject(e)}return(_=_||Promise.resolve(E)).then((function(e){t.callbacks.onSuccess(e,n,s,i)})).catch((function(e){o._responseFilterError=!0,t.callbacks.onError({code:d,text:e.message},s,i)}))}n.retry>=l.maxRetry||d>=400&&d<499?(c._logger.error("".concat(d," while loading ").concat(s.url)),this.callbacks.onError({code:d,text:i.statusText},s,i)):(c._logger.warn("".concat(d," while loading ").concat(s.url,", retrying in ").concat(this.retryDelay,"...")),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,l.maxRetryDelay),n.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),l.timeout)}}})}}},{key:"_addBindings",value:function(){var e=this;this._mediaAttachedPromise=new Promise((function(r){return e._onMediaAttached=r}));for(var r=0,t=Object.entries(this._adapterEventsBindings);r<t.length;r++){var o=i(t[r],2),a=o[0],n=o[1];this._hls.on(a,n)}this._onRecoveredCallback=function(){return e._onRecovered()},this._onAddTrack=this._onAddTrack.bind(this),this._eventManager.listen(this._videoElement,"addtrack",this._onAddTrack),this._videoElement.textTracks.onaddtrack=this._onAddTrack}},{key:"_onFpsDrop",value:function(r){this._trigger(e.EventType.FPS_DROP,r)}},{key:"_onFragParsingMetadata",value:function(r){var t;this._trigger("hlsFragParsingMetadata",r);var i=Array.from(null===(t=this._videoElement)||void 0===t?void 0:t.textTracks).find((function(e){return"id3"===e.label})),o=Array.from((null==i?void 0:i.cues)||[]),a=[];null==r||r.samples.forEach((function(r){var t=e.Utils.binarySearch(o,(function(e){return e.startTime-r.pts}));if(t){var i=(0,e.createTimedMetadata)(t);a.push(i)}})),a.length&&this._trigger(e.EventType.TIMED_METADATA_ADDED,{cues:a})}},{key:"_onAddTrack",value:function(r){if(!this._hls.subtitleTracks.length){var t=this._parseCEATextTrack(r.track);t&&(c._logger.debug("A CEA 608/708 caption has been found",t),this._playerTracks.push(t),this._trigger(e.EventType.TRACKS_CHANGED,{tracks:this._playerTracks}))}}},{key:"attachMediaSource",value:function(){this._hls||(this._videoElement&&this._videoElement.src&&(e.Utils.Dom.setAttribute(this._videoElement,"src",""),e.Utils.Dom.removeAttribute(this._videoElement,"src")),this._init())}},{key:"detachMediaSource",value:function(){var r;this._hls&&(0===Math.floor(this.duration-this.currentTime)?this._config.hlsConfig.startPosition=0:this.currentTime>0&&(this._config.hlsConfig.startPosition=this.currentTime),this._reset(),null===(r=this._loadPromiseHandlers)||void 0===r||r.reject(new e.Error(e.Error.Severity.CRITICAL,e.Error.Category.PLAYER,e.Error.Code.HLS_FATAL_MEDIA_ERROR,"media detached while loading")),this._loadPromiseHandlers=null,this._loadPromise=void 0,this._hls=null)}},{key:"handleMediaError",value:function(e){return e.code===e.MEDIA_ERR_DECODE&&(c._logger.debug("The video playback was aborted due to a corruption problem or because the video used features your browser did not support.",e.message),this._handleMediaError(T().ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR))}},{key:"load",value:function(e){var r=this;return this._loadPromise||(this._startTime=e,this._loadPromise=new Promise((function(e,t){r._loadPromiseHandlers={resolve:e,reject:t},r._loadInternal()}))),this._loadPromise}},{key:"_loadInternal",value:function(){var r;this._hls&&this._sourceObj&&this._sourceObj.url?(this._hls.loadSource(this._sourceObj.url),this._hls.attachMedia(this._videoElement),this._trigger(e.EventType.ABR_MODE_CHANGED,{mode:this.isAdaptiveBitrateEnabled()?"auto":"manual"})):null===(r=this._loadPromiseHandlers)||void 0===r||r.reject(new e.Error(e.Error.Severity.CRITICAL,e.Error.Category.PLAYER,e.Error.Code.HLS_FATAL_MEDIA_ERROR,"no url provided"))}},{key:"_reloadWithDirectManifest",value:function(){this._triedReloadWithRedirect=!0,this._reset(),this._config.hlsConfig.pLoader=k,this._hls=new(T())(this._config.hlsConfig),this._addBindings(),this._loadInternal()}},{key:"destroy",value:function(){var r=this;return new Promise((function(t,i){f(h(c.prototype),"destroy",r).call(r).then((function(){var i;c._logger.debug("destroy"),r._playerTracks=[],r._nativeTextTracksMap={},r._sameFragSNLoadedCount=0,r._lastLoadedFragSN=-1,null===(i=r._loadPromiseHandlers)||void 0===i||i.reject(new e.Error(e.Error.Severity.CRITICAL,e.Error.Category.PLAYER,e.Error.Code.HLS_FATAL_MEDIA_ERROR,"The adapter has been destroyed while loading")),r._loadPromiseHandlers=null,r._loadPromise=void 0,r._reset(),t()}),(function(){return i()}))}))}},{key:"_reset",value:function(){this._removeBindings(),this._requestFilterError=!1,this._responseFilterError=!1,this._hls.detachMedia(),this._hls.destroy()}},{key:"_parseTracks",value:function(){var e=this._parseAudioTracks(this._hls.audioTracks||[]),r=this._parseVideoTracks(this._hls.levels||[]),t=this._parseTextTracks(this._hls.subtitleTracks||[]);return e.concat(r).concat(t)}},{key:"_parseAudioTracks",value:function(r){for(var t=[],i=0;i<r.length;i++){var o={id:r[i].id,active:this._hls.audioTrack===r[i].id,label:r[i].name,language:r[i].lang,index:i,kind:r[i].characteristics?e.AudioTrackKind.DESCRIPTION:e.AudioTrackKind.MAIN};t.push(new e.AudioTrack(o))}return t}},{key:"_parseVideoTracks",value:function(r){for(var t=[],i=0;i<r.length;i++){var o={active:this._hls.startLevel===i,bandwidth:r[i].bitrate,width:r[i].width,height:r[i].height,language:"",index:i};t.push(new e.VideoTrack(o))}return t}},{key:"_parseTextTracks",value:function(r){var t,i=[],o=function(e,r){var t="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!t){if(Array.isArray(e)||(t=function(e,r){if(e){if("string"==typeof e)return D(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?D(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){t&&(e=t);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,n=!0,s=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return n=e.done,e},e:function(e){s=!0,a=e},f:function(){try{n||null==t.return||t.return()}finally{if(s)throw a}}}}(r);try{for(o.s();!(t=o.n()).done;){var a=t.value,n={id:a.id,active:!1,default:a.default,label:a.name,kind:this._captionsOrSubtitlesFromCharacteristics(a),language:a.lang};i.push(new e.TextTrack(n))}}catch(e){o.e(e)}finally{o.f()}return i}},{key:"_captionsOrSubtitlesFromCharacteristics",value:function(r){var t=r.characteristics;return t&&/transcribes-spoken-dialog/gi.test(t)&&/describes-music-and-sound/gi.test(t)?e.TextTrack.KIND.CAPTIONS:e.TextTrack.KIND.SUBTITLES}},{key:"_parseCEATextTrack",value:function(r){var t=null;if("captions"===r.kind){var i={id:r.id,active:"showing"===r.mode,label:r.label,kind:r.kind,language:r.language};t=new e.TextTrack(i),this._nativeTextTracksMap[t.index]=r}return t}},{key:"selectAudioTrack",value:function(r){r instanceof e.AudioTrack&&!r.active&&this._hls.audioTracks&&(this._hls.audioTrack=r.id)}},{key:"selectVideoTrack",value:function(r){r instanceof e.VideoTrack&&(!r.active||this.isAdaptiveBitrateEnabled())&&this._hls.levels&&(this.isAdaptiveBitrateEnabled()&&this._trigger(e.EventType.ABR_MODE_CHANGED,{mode:"manual"}),this._hls.currentLevel=r.index)}},{key:"selectTextTrack",value:function(r){r instanceof e.TextTrack&&!r.active&&this._hls&&(this._hls.subtitleTracks.length?(this._hls.subtitleTrack=r.id,this._notifyTrackChanged(r)):this._selectNativeTextTrack(r))}},{key:"_selectNativeTextTrack",value:function(e){var r=this._nativeTextTracksMap[e.index];r&&(this.disableNativeTextTracks(),r.mode=this._config.subtitleDisplay?"showing":"hidden",this._notifyTrackChanged(e))}},{key:"_notifyTrackChanged",value:function(e){this._onTrackChanged(e)}},{key:"hideTextTrack",value:function(){this._hls&&!this._hls.subtitleTracks.length&&this.disableNativeTextTracks()}},{key:"enableAdaptiveBitrate",value:function(){this.isAdaptiveBitrateEnabled()||(this._trigger(e.EventType.ABR_MODE_CHANGED,{mode:"auto"}),this._hls.nextLevel=-1)}},{key:"isAdaptiveBitrateEnabled",value:function(){return!!this._hls&&this._hls.autoLevelEnabled}},{key:"applyABRRestriction",value:function(r){e.Utils.Object.createPropertyPath(this._config,"abr.restrictions",r),this._hls.capLevelToPlayerSize||this._maybeApplyAbrRestrictions(r)}},{key:"_getLevelDetails",value:function(){var e=this._hls.levels[this._hls.currentLevel]||this._hls.levels[this._hls.nextLevel]||this._hls.levels[this._hls.nextAutoLevel]||this._hls.levels[this._hls.nextLoadLevel];return e&&e.details?e.details:{}}},{key:"_getLiveEdge",value:function(){try{var e;return(e=this._hls.liveSyncPosition?this._hls.liveSyncPosition:this._hls.config.liveSyncDuration?this._videoElement.duration-this._hls.config.liveSyncDuration:this._videoElement.duration-this._hls.config.liveSyncDurationCount*this._getLevelDetails().targetduration)>0?e:this._videoElement.duration}catch(e){return c._logger.debug("Live edge calculation failed, fall back to duration"),this._videoElement.duration}}},{key:"seekToLiveEdge",value:function(){try{this._videoElement.currentTime=this._getLiveEdge()}catch(e){return}}},{key:"getSegmentDuration",value:function(){var r=e.Utils.Object.getPropertyPath(this._hls,"streamController.fragCurrent");return r?r.duration:0}},{key:"liveDuration",get:function(){return this._getLiveEdge()+this.getSegmentDuration()}},{key:"isLive",value:function(){try{return!!this._getLevelDetails().live}catch(e){return!1}}},{key:"_onManifestLoaded",value:function(r){var t=this;c._logger.debug("The source has been loaded successfully"),this._hls.config.autoStartLoad||this._hls.startLoad(this._startTime),this._playerTracks=this._parseTracks(),this._config.abr.enabled||(this._hls.currentLevel=0),this._mediaAttachedPromise.then((function(){var e;null===(e=t._loadPromiseHandlers)||void 0===e||e.resolve({tracks:t._playerTracks}),t._loadPromiseHandlers=null}));var i=r.stats.loading,o=i.end-i.start;this._trigger(e.EventType.MANIFEST_LOADED,{miliSeconds:o})}},{key:"_maybeApplyAbrRestrictions",value:function(r){var t=this._playerTracks.filter((function(r){return r instanceof e.VideoTrack})),i=(0,e.filterTracksByRestriction)(t,r);if(i.length){var o=i[0],a=i.pop();this._hls.config.minAutoBitrate=o.bandwidth,this._hls.autoLevelCapping=a.index;var n=i.some((function(e){return e.active}));this.isAdaptiveBitrateEnabled()||n||this.selectVideoTrack(o)}else c._logger.warn("Invalid restrictions, there are not tracks within the restriction range")}},{key:"_onLevelSwitched",value:function(r,t){var i=this._playerTracks.find((function(r){return r instanceof e.VideoTrack&&r.index===t.level}));this._onTrackChanged(i)}},{key:"_onAudioTrackSwitched",value:function(r,t){var i=this._playerTracks.find((function(r){return r instanceof e.AudioTrack&&r.id===t.id}));this._onTrackChanged(i),this._handleWaitingUponAudioTrackSwitch()}},{key:"_handleWaitingUponAudioTrackSwitch",value:function(){var r=this;["IE","Edge"].includes(e.Env.browser.name)&&this._eventManager.listenOnce(this._videoElement,e.EventType.TIME_UPDATE,(function(){r._trigger(e.EventType.PLAYING)}))}},{key:"_getErrorDataObject",value:function(e){var r={};switch(r.name=e.details,r.name){case T().ErrorDetails.MANIFEST_LOAD_ERROR:case T().ErrorDetails.LEVEL_LOAD_ERROR:case T().ErrorDetails.AUDIO_TRACK_LOAD_ERROR:r.url=e.url,r.responseCode=e.response?e.response.code:null;break;case T().ErrorDetails.MANIFEST_LOAD_TIMEOUT:case T().ErrorDetails.LEVEL_LOAD_TIMEOUT:case T().ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:r.url=e.url;break;case T().ErrorDetails.MANIFEST_PARSING_ERROR:r.url=e.url,r.reason=e.reason;break;case T().ErrorDetails.LEVEL_SWITCH_ERROR:r.level=e.level,r.reason=e.reason;break;case T().ErrorDetails.FRAG_LOAD_ERROR:r.fragUrl=e.frag?e.frag.url:null,r.responseCode=e.response?e.response.code:null;break;case T().ErrorDetails.FRAG_LOAD_TIMEOUT:r.fragUrl=e.frag?e.frag.url:null;break;case T().ErrorDetails.FRAG_DECRYPT_ERROR:case T().ErrorDetails.FRAG_PARSING_ERROR:r.reason=e.reason;break;case T().ErrorDetails.KEY_LOAD_ERROR:r.fragDecryptedDataUri=e.frag&&e.frag.decryptdata?e.frag.decryptdata.uri:null,r.responseCode=e.response?e.response.code:null;break;case T().ErrorDetails.KEY_LOAD_TIMEOUT:r.fragDecryptedDataUri=e.frag&&e.frag.decryptdata?e.frag.decryptdata.uri:null;break;case T().ErrorDetails.BUFFER_ADD_CODEC_ERROR:r.mimeType=e.mimeType,r.errorMsg=e.err?e.err.message:null;break;case T().ErrorDetails.BUFFER_STALLED_ERROR:r.buffer=e.buffer}return(this._requestFilterError||this._responseFilterError)&&(r.reason=e.response.text),r}},{key:"_onError",value:function(r){var t=r.type,i=r.details,o=r.fatal,a=this._getErrorDataObject(r);if(o){var n,s;switch(t){case T().ErrorTypes.NETWORK_ERROR:var l;l=this._requestFilterError?e.Error.Code.REQUEST_FILTER_ERROR:this._responseFilterError?e.Error.Code.RESPONSE_FILTER_ERROR:e.Error.Code.HTTP_ERROR,![T().ErrorDetails.MANIFEST_LOAD_ERROR,T().ErrorDetails.MANIFEST_LOAD_TIMEOUT].includes(i)||this._triedReloadWithRedirect||this._config.forceRedirectExternalStreams||this._requestFilterError||this._responseFilterError?n=new e.Error(e.Error.Severity.CRITICAL,e.Error.Category.NETWORK,l,a):(n=new e.Error(e.Error.Severity.RECOVERABLE,e.Error.Category.NETWORK,l,a),this._reloadWithDirectManifest());break;case T().ErrorTypes.MEDIA_ERROR:n=this._handleMediaError(i)?new e.Error(e.Error.Severity.RECOVERABLE,e.Error.Category.MEDIA,e.Error.Code.HLS_FATAL_MEDIA_ERROR,a):new e.Error(e.Error.Severity.CRITICAL,e.Error.Category.MEDIA,e.Error.Code.HLS_FATAL_MEDIA_ERROR,a);break;default:n=new e.Error(e.Error.Severity.CRITICAL,e.Error.Category.PLAYER,e.Error.Code.HLS_FATAL_MEDIA_ERROR,a)}if(this._trigger(e.EventType.ERROR,n),n&&n.severity===e.Error.Severity.CRITICAL)this._loadPromiseHandlers&&(null===(s=this._loadPromiseHandlers)||void 0===s||s.reject(n),this._loadPromiseHandlers=null,this._loadPromise=void 0),this.destroy()}else{var u=this._requestFilterError||this._responseFilterError?{category:e.Error.Category.NETWORK,code:this._requestFilterError?e.Error.Code.REQUEST_FILTER_ERROR:e.Error.Code.RESPONSE_FILTER_ERROR}:m[i]||{category:0,code:0},d=u.category,h=u.code;c._logger.warn(new e.Error(e.Error.Severity.RECOVERABLE,d,h,a))}this._requestFilterError=!1,this._responseFilterError=!1}},{key:"_handleMediaError",value:function(r){c._logger.error("_handleMediaError mediaErrorName:",r);var t=performance.now(),i=!0;if(r===T().ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR)c._logger.error("recover aborted due to: MANIFEST_INCOMPATIBLE_CODECS_ERROR"),i=!1;else if(this._checkTimeDeltaHasPassed(t,this._recoverDecodingErrorDate,this._config.recoverDecodingErrorDelay)){if(r===T().ErrorDetails.FRAG_PARSING_ERROR)return c._logger.error("Manifest parsing error on "+this._videoElement.currentTime+". Try to recover"),i;this._eventManager.listen(this._videoElement,e.EventType.LOADED_METADATA,this._onRecoveredCallback),c._logger.debug("try to recover using: _recoverDecodingError()"),this._recoverDecodingError()}else this._checkTimeDeltaHasPassed(t,this._recoverSwapAudioCodecDate,this._config.recoverSwapAudioCodecDelay)?(this._eventManager.listen(this._videoElement,e.EventType.LOADED_METADATA,this._onRecoveredCallback),c._logger.debug("try to recover using: _recoverSwapAudioCodec()"),this._recoverSwapAudioCodec()):(c._logger.error("cannot recover, last media error recovery failed error: ",r),i=!1);return i}},{key:"_onRecovered",value:function(){this._trigger(e.EventType.MEDIA_RECOVERED),this._videoElement.removeEventListener(e.EventType.LOADED_METADATA,this._onRecoveredCallback)}},{key:"_checkTimeDeltaHasPassed",value:function(e,r,t){return!r||e-r>t}},{key:"_recoverDecodingError",value:function(){this._recoverDecodingErrorDate=performance.now(),c._logger.warn("try to recover media Error"),this._hls.recoverMediaError()}},{key:"_recoverSwapAudioCodec",value:function(){this._recoverSwapAudioCodecDate=performance.now(),c._logger.warn("try to swap Audio Codec and recover media Error"),this._hls.swapAudioCodec(),this._hls.recoverMediaError()}},{key:"_removeBindings",value:function(){for(var e=0,r=Object.entries(this._adapterEventsBindings);e<r.length;e++){var t=i(r[e],2),o=t[0],a=t[1];this._hls.off(o,a)}this._videoElement.textTracks.onaddtrack=null,this._onRecoveredCallback=null,this._eventManager&&this._eventManager.removeAll()}},{key:"getStartTimeOfDvrWindow",value:function(){if(!this.isLive())return 0;try{var e=this._hls.levels[this._hls.nextLoadLevel].details,r=e.fragments,t=r.length,i=r[0].start+r[0].duration,o=r[t-1].start+r[t-1].duration,a=void 0!==this._hls.config.liveMaxLatencyDuration?this._hls.config.liveMaxLatencyDuration:this._hls.config.liveMaxLatencyDurationCount*e.targetduration;return Math.max(i-this._hls.config.maxFragLookUpTolerance,o-a)}catch(e){return c._logger.debug("Unable obtain the start of DVR window"),0}}},{key:"_onFragLoaded",value:function(r){if(e.Utils.Object.hasPropertyPath(r,"frag.stats.loading")){var t=r.frag.stats,i=t.loading.end-t.loading.start;this._trigger(e.EventType.FRAG_LOADED,{miliSeconds:i,bytes:t.loaded,url:r.frag.url})}}},{key:"targetBuffer",get:function(){var e=NaN;return this._hls?(e=this.isLive()?this._getLiveTargetBuffer()-(this._videoElement.currentTime-this._getLiveEdge()):this._videoElement.duration-this._videoElement.currentTime,e=Math.min(e,this._hls.config.maxMaxBufferLength+this._getLevelDetails().targetduration)):NaN}},{key:"_getLiveTargetBuffer",value:function(){return this._hls.config.liveSyncDuration?this._hls.config.liveSyncDuration:this._hls.config.liveSyncDurationCount*this._getLevelDetails().targetduration}}],[{key:"createAdapter",value:function(r,t,i){var o=e.Utils.Object.copyDeep(R);if(e.Utils.Object.hasPropertyPath(i,"sources.options")){var a=i.sources.options;o.forceRedirectExternalStreams=a.forceRedirectExternalStreams,o.redirectExternalStreamsHandler=a.redirectExternalStreamsHandler,o.redirectExternalStreamsTimeout=a.redirectExternalStreamsTimeout,k.redirectExternalStreamsHandler=o.redirectExternalStreamsHandler,k.redirectExternalStreamsTimeout=o.redirectExternalStreamsTimeout}if(e.Utils.Object.hasPropertyPath(i,"sources.startTime")&&e.Utils.Object.getPropertyPath(i,"sources.startTime")>-1&&(o.hlsConfig.startPosition=i.sources.startTime),e.Utils.Object.hasPropertyPath(i,"text.useNativeTextTrack")&&(o.subtitleDisplay=e.Utils.Object.getPropertyPath(i,"text.useNativeTextTrack")),e.Utils.Object.hasPropertyPath(i,"abr.fpsDroppedFramesInterval")&&(o.hlsConfig.fpsDroppedFramesInterval=i.abr.fpsDroppedFramesInterval),e.Utils.Object.hasPropertyPath(i,"abr.fpsDroppedMonitoringThreshold")&&(o.hlsConfig.fpsDroppedMonitoringThreshold=i.abr.fpsDroppedMonitoringThreshold),e.Utils.Object.hasPropertyPath(i,"abr.capLevelOnFPSDrop")&&(c._logger.debug("capLevelOnFPSDrop = ",i.abr.capLevelOnFPSDrop),o.hlsConfig.capLevelOnFPSDrop=i.abr.capLevelOnFPSDrop),e.Utils.Object.hasPropertyPath(i,"text")&&(o.hlsConfig.enableCEA708Captions=i.text.enableCEA708Captions,o.hlsConfig.captionsTextTrack1Label=i.text.captionsTextTrack1Label,o.hlsConfig.captionsTextTrack1LanguageCode=i.text.captionsTextTrack1LanguageCode,o.hlsConfig.captionsTextTrack2Label=i.text.captionsTextTrack2Label,o.hlsConfig.captionsTextTrack2LanguageCode=i.text.captionsTextTrack2LanguageCode),e.Utils.Object.hasPropertyPath(i,"abr")){var n=i.abr;"boolean"==typeof n.enabled&&(o.abr.enabled=n.enabled),"boolean"==typeof n.capLevelToPlayerSize&&(o.hlsConfig.capLevelToPlayerSize=n.capLevelToPlayerSize),n.defaultBandwidthEstimate&&(o.hlsConfig.abrEwmaDefaultEstimate=n.defaultBandwidthEstimate),n.restrictions&&e.Utils.Object.createPropertyPath(o,"abr.restrictions",n.restrictions)}return e.Utils.Object.hasPropertyPath(i,"streaming.lowLatencyMode")&&(o.hlsConfig.lowLatencyMode=e.Utils.Object.getPropertyPath(i,"streaming.lowLatencyMode")),e.Utils.Object.hasPropertyPath(i,"playback.options.html5.hls")&&e.Utils.Object.mergeDeep(o.hlsConfig,i.playback.options.html5.hls),o.network=i.network,new this(r,t,o)}},{key:"canPlayType",value:function(e){var r="string"==typeof e&&c._hlsMimeTypes.includes(e.toLowerCase())&&c.isMSESupported();return c._logger.debug("canPlayType result for mimeType:"+e+" is "+r.toString()),r}},{key:"canPlayDrm",value:function(){return c._logger.warn("canPlayDrm result is false"),!1}},{key:"isSupported",value:function(){var e=T().isSupported();return c._logger.debug("isSupported:"+e),e}}]),c}(e.BaseMediaSourceAdapter);A=S,v(S,"id","HlsAdapter"),v(S,"_logger",e.BaseMediaSourceAdapter.getLogger(A.id)),v(S,"_hlsMimeTypes",["application/x-mpegurl","application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"]);var O="1.32.21",L="@playkit-js/playkit-js-hls",C=S;S.isSupported()&&(0,e.registerMediaSourceAdapter)(S)}(),a}()}));
//# sourceMappingURL=playkit-hls.js.map