@tempots/beatui 0.54.2 → 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{2019-DzVg1z5j.cjs → 2019-B4jrQ2Q8.cjs} +1 -1
- package/dist/{2019-ByDeUdzE.js → 2019-DH5GYJC9.js} +2 -2
- package/dist/{2020-C2cAo3Kx.cjs → 2020-BVrVGeh-.cjs} +1 -1
- package/dist/{2020-P72Z0RIB.js → 2020-C3vh26yT.js} +2 -2
- package/dist/{ar-jKiWO1bA.js → ar-CKheF7Rb.js} +21 -13
- package/dist/{ar-128v2WAg.cjs → ar-x9O6JsRN.cjs} +1 -1
- package/dist/auth/index.cjs.js +1 -1
- package/dist/auth/index.es.js +4 -4
- package/dist/beatui.css +425 -2
- package/dist/beatui.tailwind.css +425 -2
- package/dist/{de-Doo_UynL.cjs → de-C0nhZh4a.cjs} +1 -1
- package/dist/{de-CsZH8Z4V.js → de-CqFnIl0Y.js} +16 -8
- package/dist/{es-C6ksQm_M.cjs → es-C3c1-2iA.cjs} +1 -1
- package/dist/{es-DHzABlc2.js → es-Cv9ZSjqz.js} +16 -8
- package/dist/{fa-C0ZVnkuX.cjs → fa-BbV4_mYi.cjs} +1 -1
- package/dist/{fa-Rlsar6Fo.js → fa-CG8B9M9O.js} +21 -13
- package/dist/{fr-DzrAiW9Q.js → fr-B2f1Pmal.js} +16 -8
- package/dist/{fr-eyQiRZu8.cjs → fr-DlFsnCqK.cjs} +1 -1
- package/dist/{he-B3ehch8T.js → he-BmHa696l.js} +21 -13
- package/dist/{he-fifXa9Ks.cjs → he-DwQ2QMJE.cjs} +1 -1
- package/dist/{hi-B90ZON10.js → hi-DNII_Adz.js} +19 -11
- package/dist/{hi-BBbV2iwE.cjs → hi-DaHMe_1C.cjs} +1 -1
- package/dist/{hls-C6lKM-CG.cjs → hls-B5PliUq8.cjs} +4 -4
- package/dist/{hls-B7ZdiUxL.js → hls-DLd3ClAs.js} +28 -21
- package/dist/{index-BQear_Jy.js → index-BYflP18C.js} +172 -164
- package/dist/{index-BwkYjXhr.cjs → index-COM8WyaG.cjs} +1 -1
- package/dist/{index-BWMybo2K.js → index-DCOaDJ8f.js} +1 -1
- package/dist/{index-CSv_TMiz.js → index-Dd3PocYl.js} +1 -1
- package/dist/{index-Be-6-fQW.cjs → index-Dhaodhgr.cjs} +2 -2
- package/dist/{index-aFA1CLKZ.cjs → index-DjLKVVL-.cjs} +1 -1
- package/dist/{index-Cj2zgGLp.cjs → index-ZRQP8j2O.cjs} +4 -4
- package/dist/{index-Kox58YHG.js → index-gZaps7_A.js} +5 -5
- package/dist/index.cjs.js +4 -4
- package/dist/index.es.js +2283 -2034
- package/dist/{it-WOitrlIv.js → it-894w7K0i.js} +16 -8
- package/dist/{it-CEM-R_5J.cjs → it-Cli1u40l.cjs} +1 -1
- package/dist/{ja-CWzwG1fp.cjs → ja-DY7Zij7O.cjs} +1 -1
- package/dist/{ja-jVLb-kyU.js → ja-j4AV8eVy.js} +22 -14
- package/dist/json-schema/index.cjs.js +1 -1
- package/dist/json-schema/index.es.js +1 -1
- package/dist/{ko-DV2NgunR.cjs → ko-CHlprpVP.cjs} +1 -1
- package/dist/{ko-CUpM9wfr.js → ko-CNZqypvW.js} +18 -10
- package/dist/{modal-C4x5C70f.js → modal-1Y-q1wDn.js} +2 -2
- package/dist/{modal-C5xWtKaZ.cjs → modal-D765-SiT.cjs} +1 -1
- package/dist/{nl-C_MHm9AB.cjs → nl-CgMv4O0P.cjs} +1 -1
- package/dist/{nl-BFLwQeEn.js → nl-CzTp9ds0.js} +19 -11
- package/dist/{notice-BhxWf3Dh.cjs → notice-D8w_39td.cjs} +1 -1
- package/dist/{notice-DdYpd69I.js → notice-DJ-olOQx.js} +1 -1
- package/dist/{pl-Dcgxv0xK.cjs → pl-Cm8Lerxg.cjs} +1 -1
- package/dist/{pl-dlo59Xei.js → pl-DQid7ctL.js} +17 -9
- package/dist/prosemirror/index.cjs.js +1 -1
- package/dist/prosemirror/index.es.js +1 -1
- package/dist/{pt-CqkhyKon.js → pt-BAU0nrtN.js} +16 -8
- package/dist/{pt-As8BblbM.cjs → pt-k6sIkC0v.cjs} +1 -1
- package/dist/{ru-DOl7nkP-.js → ru-CtYj3NlJ.js} +21 -13
- package/dist/{ru-Du4sI8M1.cjs → ru-Dioznrt_.cjs} +1 -1
- package/dist/{toolbar-BnaquvB9.cjs → toolbar-BMzapKW0.cjs} +1 -1
- package/dist/{toolbar-Czc8cSjl.js → toolbar-Bo4GA6tM.js} +1 -1
- package/dist/{tr-DTLlM4Pf.cjs → tr-CwCsfbe5.cjs} +1 -1
- package/dist/{tr-3O7PDT8q.js → tr-wS-zWzvh.js} +21 -13
- package/dist/{translations-BH2Dg5AP.cjs → translations-CD_Qi9EQ.cjs} +1 -1
- package/dist/{translations-CsO0g7yz.js → translations-Dm7vjy7D.js} +1 -1
- package/dist/{translations-B3P1v3E6.js → translations-Do71ycSR.js} +53 -45
- package/dist/translations-t-neYabN.cjs +1 -0
- package/dist/types/beatui-i18n/default.d.ts +7 -0
- package/dist/types/beatui-i18n/locales/en.d.ts +7 -0
- package/dist/types/beatui-i18n/translations.d.ts +7 -0
- package/dist/types/components/media/index.d.ts +1 -0
- package/dist/types/components/media/pdf-page-viewer.d.ts +64 -0
- package/dist/types/pdfjs/lazy-loader.d.ts +2 -0
- package/dist/{ur-DB8mA3fq.js → ur-8NSFWrMo.js} +21 -13
- package/dist/{ur-DRhqXQpq.cjs → ur-D3nkqfyQ.cjs} +1 -1
- package/dist/{utils-CPZHwfiH.js → utils-DzKhEJ__.js} +2 -2
- package/dist/{utils-DCa_lhhW.cjs → utils-dY__yBXk.cjs} +1 -1
- package/dist/{vi-D_MzLijT.cjs → vi-BAAJHs3a.cjs} +1 -1
- package/dist/{vi-vGJhQVsV.js → vi-CngHpCNM.js} +18 -10
- package/dist/{zh-C_OkXlxM.js → zh-Bkxc6ZmR.js} +21 -13
- package/dist/{zh-CFMBeH1A.cjs → zh-CRWrZhUp.cjs} +1 -1
- package/package.json +7 -6
- package/dist/translations-DZWe3znu.cjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},eo=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=to},to=Number.MAX_SAFE_INTEGER||9007199254740991;let V=function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a}({}),R=function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a}({}),m=function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a}({});var Q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},B={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class ut{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class so{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ut(e),this.fast_=new ut(t),this.defaultTTFB_=i,this.ttfb_=new ut(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new ut(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new ut(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new ut(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function io(a,e,t){return(e=no(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function ie(){return ie=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},ie.apply(null,arguments)}function ji(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function te(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ji(Object(t),!0).forEach(function(s){io(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):ji(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function ro(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function no(a){var e=ro(a,"string");return typeof e=="symbol"?e:e+""}class Ce{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Qe,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Qe=function(){},ao={trace:Qe,debug:Qe,log:Qe,warn:Qe,info:Qe,error:Qe};function Zs(){return ie({},ao)}function oo(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):Qe}function Xi(a,e,t){return e[a]?e[a].bind(e):oo(a,t)}const Js=Zs();function lo(a,e,t){const s=Zs();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Xi(r,a,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.13`)}catch{return Zs()}i.forEach(r=>{Js[r]=Xi(r,a)})}else ie(Js,s);return s}const se=Js;function je(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function co(a){return typeof self<"u"&&a===self.ManagedMediaSource}function hn(a,e){const t=Object.keys(a),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(n=>s.indexOf(n)===-1)}function Re(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=a.length;let s,i,r,n="",o=0;for(;o<t;){if(s=a[o++],s===0&&e)return n;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(s);break;case 12:case 13:i=a[o++],n+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=a[o++],r=a[o++],n+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return n}function Ee(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function un(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function ho(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Ds={exports:{}},zi;function uo(){return zi||(zi=1,function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var y={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(y.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)y.path=f.path,d.params||(y.params=f.params,d.query||(y.query=f.query));else{var p=f.path,E=p.substring(0,p.lastIndexOf("/")+1)+d.path;y.path=o.normalizePath(E)}return y.path===null&&(y.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(y)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(n,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};a.exports=o})()}(Ds)),Ds.exports}var Ti=uo();class Ts{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var re={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Si{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,fo(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[re.AUDIO]:null,[re.VIDEO]:null,[re.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Ts),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ti.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[re.AUDIO]=null,e[re.VIDEO]=null,e[re.AUDIOVIDEO]=null}}function ce(a){return a.sn!=="initSegment"}class es extends Si{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(M(e)&&M(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=M(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!M(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ce(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class dn extends Si{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function fn(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||fn(t,e)}}function fo(a,e){const t=fn(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const Qi=Math.pow(2,32)-1,go=[].push,gn={video:1,audio:2,id3:3,text:4};function he(a){return String.fromCharCode.apply(null,a)}function mn(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function W(a,e){const t=pn(a,e);return t<0?4294967296+t:t}function Zi(a,e){let t=W(a,e);return t*=Math.pow(2,32),t+=W(a,e+4),t}function pn(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function mo(a){const e=a.byteLength;for(let t=0;t<e;){const s=W(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function z(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=W(a,i),n=he(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const c=z(a.subarray(i+8,o),e.slice(1));c.length&&go.apply(t,c)}i=o}return t}function po(a){const e=[],t=a[0];let s=8;const i=W(a,s);s+=4;let r=0,n=0;t===0?(r=W(a,s),n=W(a,s+4),s+=8):(r=Zi(a,s),n=Zi(a,s+8),s+=16),s+=2;let o=a.length+n;const c=mn(a,s);s+=2;for(let l=0;l<c;l++){let h=s;const u=W(a,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return se.warn("SIDX has hierarchical references (not supported)"),null;const g=W(a,h);h+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function yn(a){const e=[],t=z(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=z(r,["tkhd"])[0];if(n){let o=n[0];const c=W(n,o===0?12:20),l=z(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=W(l,o===0?12:20),u=z(r,["mdia","hdlr"])[0];if(u){const d=he(u.subarray(8,12)),f={soun:re.AUDIO,vide:re.VIDEO}[d],g=z(r,["mdia","minf","stbl","stsd"])[0],y=yo(g);f?(e[c]={timescale:h,type:f,stsd:y},e[f]=te({timescale:h,id:c},y)):e[c]={timescale:h,type:d,stsd:y}}}}}return z(a,["moov","mvex","trex"]).forEach(i=>{const r=W(i,4),n=e[r];n&&(n.default={duration:W(i,12),flags:W(i,20)})}),e}function yo(a){const e=a.subarray(8),t=e.subarray(86),s=he(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=z(e,[s])[0].subarray(s==="enca"?28:78);z(l,["sinf"]).forEach(u=>{const d=z(u,["schm"])[0];if(d){const f=he(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=z(u,["frma"])[0];g&&(i=he(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=z(t,["avcC"])[0];c&&c.length>3&&(i+="."+Ut(c[1])+Ut(c[2])+Ut(c[3]),r=Bt(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=z(e,[s])[0],l=z(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=Cs(l,h),h+=2;const u=l[h++];if(u&128&&(h+=2),u&64&&(h+=l[h++]),l[h++]!==4)break;h=Cs(l,h);const d=l[h++];if(d===64)i+="."+Ut(d);else break;if(h+=12,l[h++]!==5)break;h=Cs(l,h);const f=l[h++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const c=z(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],u=l&31,d=W(c,2),f=(l&32)>>5?"H":"L",g=c[12],y=c.subarray(6,12);i+="."+h+u,i+="."+Eo(d).toString(16).toUpperCase(),i+="."+f+g;let p="";for(let E=y.length;E--;){const T=y[E];(T||p)&&(p="."+T.toString(16).toUpperCase()+p)}i+=p}r=Bt(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Bt(i,t)||i;break}case"vp09":{const c=z(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],u=c[6]>>4&15;i+="."+Be(l)+"."+Be(h)+"."+Be(u)}break}case"av01":{const c=z(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,u=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,f=(c[2]&32)>>5,g=l===2&&d?f?12:10:d?10:8,y=(c[2]&16)>>4,p=(c[2]&8)>>3,E=(c[2]&4)>>2,T=c[2]&3;i+="."+l+"."+Be(h)+u+"."+Be(g)+"."+y+"."+p+E+T+"."+Be(1)+"."+Be(1)+"."+Be(1)+"."+0,r=Bt("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function Bt(a,e){const t=z(e,["dvvC"]),s=t.length?t[0]:z(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+Be(i)+"."+Be(r)}}function Eo(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<31-t;return e>>>0}function Cs(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function Ut(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function Be(a){return(a<10?"0":"")+a}function To(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&En(a,(s,i)=>{const r=s.subarray(8,24);r.some(n=>n!==0)||(se.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Ee(r)} -> ${Ee(t)}`),s.set(t,8))})}function So(a){const e=[];return En(a,t=>e.push(t.subarray(8,24))),e}function En(a,e){z(a,["moov","trak"]).forEach(s=>{const i=z(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=z(r,["enca"]);const o=n.length>0;o||(n=z(r,["encv"])),n.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);z(l,["sinf"]).forEach(u=>{const d=Tn(u);d&&e(d,o)})})})}function Tn(a){const e=z(a,["schm"])[0];if(e){const t=he(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=z(a,["schi","tenc"])[0];if(s)return s}}}function vo(a,e,t){const s={},i=z(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=z(n,["tfhd"])[0],c=W(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],u=z(n,["tfdt"])[0];if(u){const S=u[0];let v=W(u,4);S===1&&(v===Qi?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(v*=Qi+1,v+=W(u,8))),M(v)&&(!M(h.start)||v<h.start)&&(h.start=v)}const d=l.default,f=W(o,0)|d?.flags;let g=d?.duration||0;f&8&&(f&2?g=W(o,12):g=W(o,8));const y=z(n,["trun"]);let p=h.start||0,E=0,T=g;for(let S=0;S<y.length;S++){const v=y[S],x=W(v,4),D=h.sampleCount;h.sampleCount+=x;const A=v[3]&1,_=v[3]&4,b=v[2]&1,I=v[2]&2,P=v[2]&4,F=v[2]&8;let U=8,H=x;for(A&&(U+=4),_&&x&&(!(v[U+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=D),U+=4,b?(T=W(v,U),U+=4):T=g,I&&(U+=4),F&&(U+=4),p+=T,E+=T,H--);H--;)b?(T=W(v,U),U+=4):T=g,I&&(U+=4),P&&(v[U+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(H+1),h.keyFrameStart=p),U+=4),F&&(U+=4),p+=T,E+=T;!E&&g&&(E+=g*x)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=z(a,["sidx"]);for(let c=0;c<o.length;c++){const l=po(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((u,d)=>u+d.info.duration||0,0);n=Math.max(n,h+l.earliestPresentationTime/l.timescale)}}n&&M(n)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=n*s[c].timescale-s[c].start)})}return s}function xo(a){const e={valid:null,remainder:null},t=z(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=a.slice(0,s.byteOffset-8),e.remainder=a.slice(s.byteOffset-8),e}function De(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Ji(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return z(s,["moof"]).map(c=>{const l=c.byteOffset-8;z(c,["traf"]).map(u=>{const d=z(u,["tfdt"]).map(f=>{const g=f[0];let y=W(f,4);return g===1&&(y*=Math.pow(2,32),y+=W(f,8)),y/i})[0];return d!==void 0&&(a=d),z(u,["tfhd"]).map(f=>{const g=W(f,4),y=W(f,0)&16777215,p=(y&1)!==0,E=(y&2)!==0,T=(y&8)!==0;let S=0;const v=(y&16)!==0;let x=0;const D=(y&32)!==0;let A=8;g===r&&(p&&(A+=8),E&&(A+=4),T&&(S=W(f,A),A+=4),v&&(x=W(f,A),A+=4),D&&(A+=4),e.type==="video"&&(n=Ss(e.codec)),z(u,["trun"]).map(_=>{const b=_[0],I=W(_,0)&16777215,P=(I&1)!==0;let F=0;const U=(I&4)!==0,H=(I&256)!==0;let $=0;const k=(I&512)!==0;let G=0;const N=(I&1024)!==0,K=(I&2048)!==0;let Y=0;const w=W(_,4);let O=8;P&&(F=W(_,O),O+=4),U&&(O+=4);let j=F+l;for(let ee=0;ee<w;ee++){if(H?($=W(_,O),O+=4):$=S,k?(G=W(_,O),O+=4):G=x,N&&(O+=4),K&&(b===0?Y=W(_,O):Y=pn(_,O),O+=4),e.type===re.VIDEO){let X=0;for(;X<G;){const Z=W(s,j);if(j+=4,Ao(n,s[j])){const pe=s.subarray(j,j+Z);vi(pe,n?2:1,a+Y/i,t)}j+=Z,X+=Z+4}}a+=$/i}}))})})}),t}function Ss(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Ao(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function vi(a,e,t,s){const i=Sn(a);let r=0;r+=e;let n=0,o=0,c=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;c=i[r++],n+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){se.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(n===4){if(i[h++]===181){const d=mn(i,h);if(h+=2,d===49){const f=W(i,h);if(h+=4,f===1195456820){const g=i[h++];if(g===3){const y=i[h++],p=31&y,E=64&y,T=E?2+p*3:0,S=new Uint8Array(T);if(E){S[0]=y;for(let v=1;v<T;v++)S[v]=i[h++]}s.push({type:g,payloadType:n,pts:t,bytes:S})}}}}}else if(n===5&&o>16){const u=[];for(let g=0;g<16;g++){const y=i[h++].toString(16);u.push(y.length==1?"0"+y:y),(g===3||g===5||g===7||g===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[h++];s.push({payloadType:n,pts:t,uuid:u.join(""),userData:Re(f),userDataBytes:f})}}}function Sn(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function Io(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,c=0,l=0;if(e===0){for(;he(a.subarray(l,l+1))!=="\0";)t+=he(a.subarray(l,l+1)),l+=1;for(t+=he(a.subarray(l,l+1)),l+=1;he(a.subarray(l,l+1))!=="\0";)s+=he(a.subarray(l,l+1)),l+=1;s+=he(a.subarray(l,l+1)),l+=1,i=W(a,12),r=W(a,16),o=W(a,20),c=W(a,24),l=28}else if(e===1){l+=4,i=W(a,l),l+=4;const u=W(a,l);l+=4;const d=W(a,l);for(l+=4,n=2**32*u+d,eo(n)||(n=Number.MAX_SAFE_INTEGER,se.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=W(a,l),l+=4,c=W(a,l),l+=4;he(a.subarray(l,l+1))!=="\0";)t+=he(a.subarray(l,l+1)),l+=1;for(t+=he(a.subarray(l,l+1)),l+=1;he(a.subarray(l,l+1))!=="\0";)s+=he(a.subarray(l,l+1)),l+=1;s+=he(a.subarray(l,l+1)),l+=1}const h=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function Lo(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function Ro(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),Lo([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t)}function bo(a){const e=[];if(a instanceof ArrayBuffer){const t=a.byteLength;let s=0;for(;s+32<t;){const i=new DataView(a,s),r=_o(i);e.push(r),s+=r.size}}return e}function _o(a){const e=a.getUint32(0),t=a.byteOffset,s=a.byteLength;if(s<e)return{offset:t,size:s};if(a.getUint32(4)!==1886614376)return{offset:t,size:e};const r=a.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=a.buffer,o=Ee(new Uint8Array(n,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const d=a.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let f=0;f<d;f++)c.push(new Uint8Array(n,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=a.getUint32(h);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(n,t+h+4,u),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const vn=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),St={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function xi(a,e){const t=St[e];return!!t&&!!t[a.slice(0,4)]}function Pt(a,e,t=!0){return!a.split(",").some(s=>!Ai(s,e,t))}function Ai(a,e,t=!0){var s;const i=je(t);return(s=i?.isTypeSupported(kt(a,e)))!=null?s:!1}function kt(a,e){return`${e}/mp4;codecs=${a}`}function er(a){if(a){const e=a.substring(0,4);return St.video[e]}return 2}function ls(a){const e=vn();return a.split(",").reduce((t,s)=>{const r=e&&Ss(s)?9:St.video[s];return r?(r*2+t)/(t?3:2):(St.audio[s]+t)/(t?2:1)},0)}const Ps={};function Do(a,e=!0){if(Ps[a])return Ps[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let i=0;i<t.length;i++){var s;if(Ai(t[i],"audio",e))return Ps[a]=t[i],t[i];if(t[i]==="mp3"&&(s=je(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const Co=/flac|opus|mp4a\.40\.34/i;function cs(a,e=!0){return a.replace(Co,t=>Do(t.toLowerCase(),e))}function Po(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)xi(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function ts(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(tr(a,"audio")||tr(a,"video")))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let s=t.length;s--;)if(t[s].substring(0,4)===a.substring(0,4))return t[s]}return t[0]}}return e||a}function tr(a,e){return xi(a,e)&&Ai(a,e)}function ko(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function wo(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return a}function sr(a){const e=je(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ei(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Oo={supported:!0,powerEfficient:!0,smooth:!0},Fo={supported:!1,smooth:!1,powerEfficient:!1},xn={supported:!0,configurations:[],decodingInfoResults:[Oo]};function An(a,e){return{supported:!1,configurations:e,decodingInfoResults:[Fo],error:a}}function Mo(a,e,t,s,i,r){const n=a.videoCodec,o=a.audioCodec?a.audioGroups:null,c=r?.audioCodec,l=r?.channels,h=l?parseInt(l):c?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(y=>{d[y]=(d[y]||0)+g.channels[y]})}return d},{2:0})}catch{return!0}return n!==void 0&&(n.split(",").some(d=>Ss(d))||a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!u&&M(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function In(a,e,t,s={}){const i=a.videoCodec;if(!i&&!a.audioCodec||!t)return Promise.resolve(xn);const r=[],n=No(a),o=n.length,c=Bo(a,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const u={type:"media-source"};if(o&&(u.video=n[h%o]),l){u.audio=c[h%l];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>Ss(u))&&vn())return Promise.resolve(An(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=$o(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function No(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),s=Ln(a),i=a.width||640,r=a.height||480,n=a.frameRate||30,o=a.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:kt(wo(c),"video"),width:i,height:r,bitrate:s,framerate:n};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function Bo(a,e,t){var s;const i=(s=a.audioCodec)==null?void 0:s.split(","),r=Ln(a);return i&&a.audioGroups?a.audioGroups.reduce((n,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(f=>{const g={contentType:kt(f,"audio"),bitrate:t?Uo(f,r):r};d&&(g.channels=""+d),h.push(g)})}return h},n):n},[]):[]}function Uo(a,e){if(e<=1)return 1;let t=128e3;return a==="ec-3"?t=768e3:a==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Ln(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function $o(a){let e="";const{audio:t,video:s}=a;if(s){const i=ei(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=ei(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const ti=["NONE","TYPE-0","TYPE-1",null];function Go(a){return ti.indexOf(a)>-1}const hs=["SDR","PQ","HLG"];function Ko(a){return!!a&&hs.indexOf(a)>-1}var bt={No:"",Yes:"YES",v2:"v2"};function ir(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?bt.v2:bt.Yes:bt.No}class si{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class vt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return rr(this._audioGroups,e)}hasSubtitleGroup(e){return rr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function rr(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function Vo(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function Ho(a,e){let t=!1,s=[];if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||hs.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Vo(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Yo=a=>{const e=new WeakSet;return(t,s)=>{if(a&&(s=a(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ne=(a,e)=>JSON.stringify(a,Yo(e));function Wo(a,e,t,s,i){const r=Object.keys(a),n=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=n&&parseInt(n)===2;let h=!1,u=!1,d=1/0,f=1/0,g=1/0,y=1/0,p=0,E=[];const{preferHDR:T,allowedVideoRanges:S}=Ho(e,i);for(let _=r.length;_--;){const b=a[r[_]];h||(h=b.channels[2]>0),d=Math.min(d,b.minHeight),f=Math.min(f,b.minFramerate),g=Math.min(g,b.minBitrate),S.filter(P=>b.videoRanges[P]>0).length>0&&(u=!0)}d=M(d)?d:0,f=M(f)?f:0;const v=Math.max(1080,d),x=Math.max(30,f);g=M(g)?g:t,t=Math.max(g,t),u||(e=void 0);const D=r.length>1;return{codecSet:r.reduce((_,b)=>{const I=a[b];if(b===_)return _;if(E=u?S.filter(P=>I.videoRanges[P]>0):[],D){if(I.minBitrate>t)return Me(b,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),_;if(!I.hasDefaultAudio)return Me(b,"no renditions with default or auto-select sound found"),_;if(o&&b.indexOf(o.substring(0,4))%5!==0)return Me(b,`audio codec preference "${o}" not found`),_;if(n&&!l){if(!I.channels[n])return Me(b,`no renditions with ${n} channel sound found (channels options: ${Object.keys(I.channels)})`),_}else if((!o||l)&&h&&I.channels[2]===0)return Me(b,"no renditions with stereo sound found"),_;if(I.minHeight>v)return Me(b,`min resolution of ${I.minHeight} > maximum of ${v}`),_;if(I.minFramerate>x)return Me(b,`min framerate of ${I.minFramerate} > maximum of ${x}`),_;if(!E.some(P=>I.videoRanges[P]>0))return Me(b,`no variants with VIDEO-RANGE of ${ne(E)} found`),_;if(c&&b.indexOf(c.substring(0,4))%5!==0)return Me(b,`video codec preference "${c}" not found`),_;if(I.maxScore<p)return Me(b,`max score of ${I.maxScore} < selected max of ${p}`),_}return _&&(ls(b)>=ls(_)||I.fragmentError>a[_].fragmentError)?_:(y=I.minIndex,p=I.maxScore,b)},void 0),videoRanges:E,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:y}}function Me(a,e){se.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function Rn(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function qo(a,e,t,s){return a.slice(t,s+1).reduce((i,r,n)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,n),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+u.channels[d]}))}),i},{})}function nr(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=a;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function $e(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(ot(a,i,t))return s}return-1}function ot(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,default:o}=a,c=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||jo(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in a)||Xo(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function jo(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function Xo(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function at(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function zo(a,e,t,s,i){const r=e[s],o=e.reduce((d,f,g)=>{const y=f.uri;return(d[y]||(d[y]=[])).push(g),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),u=ar(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return $e(a,g,i)>-1});return u>-1?u:ar(e,s,d=>{const f=d.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return $e(a,g,i)>-1})}function ar(a,e,t){for(let s=e;s>-1;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}function us(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class bn extends Ce{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:c}=n;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=l-h.loading.start,f=n.minAutoLevel,g=i.level,y=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const p=y>-1&&y!==g,E=!!t||p;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const T=n.mainForwardBufferInfo;if(!E&&T===null)return;const S=this.bwEstimator.getEstimateTTFB(),v=Math.abs(c.playbackRate);if(d<=Math.max(S,1e3*(u/(v*2))))return;const x=T?T.len/v:0,D=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&D>-1,_=this.getBwEstimate(),b=n.levels,I=b[g],P=Math.max(h.loaded,Math.round(u*(i.bitrate||I.averageBitrate)/8));let F=A?d-D:d;F<1&&A&&(F=Math.min(d,h.loaded*8/_));const U=A?h.loaded*1e3/F:0,H=S/1e3,$=U?(P-h.loaded)/U:P*8/_+H;if($<=x)return;const k=U?U*8:_,G=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,N=this.hls.config.abrBandWidthUpFactor;let K=Number.POSITIVE_INFINITY,Y;for(Y=g-1;Y>f;Y--){const ee=b[Y].maxBitrate,X=!b[Y].details||G;if(K=this.getTimeToLoadFrag(H,k,u*ee,X),K<Math.min(x,u+H))break}if(K>=$||K>u*10)return;A?this.bwEstimator.sample(d-Math.min(S,D),h.loaded):this.bwEstimator.sampleTTFB(d);const w=b[Y].maxBitrate;this.getBwEstimate()*N>w&&this.resetEstimator(w);const O=this.findBestLevel(w,f,Y,0,x,1,1);O>-1&&(Y=O),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},eo=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=to},to=Number.MAX_SAFE_INTEGER||9007199254740991;let V=function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a}({}),R=function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a}({}),m=function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a}({});var Q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},B={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class ut{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class so{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ut(e),this.fast_=new ut(t),this.defaultTTFB_=i,this.ttfb_=new ut(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new ut(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new ut(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new ut(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function io(a,e,t){return(e=no(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function ie(){return ie=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},ie.apply(null,arguments)}function ji(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function te(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ji(Object(t),!0).forEach(function(s){io(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):ji(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function ro(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function no(a){var e=ro(a,"string");return typeof e=="symbol"?e:e+""}class Ce{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Qe,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const Qe=function(){},ao={trace:Qe,debug:Qe,log:Qe,warn:Qe,info:Qe,error:Qe};function Zs(){return ie({},ao)}function oo(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):Qe}function Xi(a,e,t){return e[a]?e[a].bind(e):oo(a,t)}const Js=Zs();function lo(a,e,t){const s=Zs();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Xi(r,a,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.14`)}catch{return Zs()}i.forEach(r=>{Js[r]=Xi(r,a)})}else ie(Js,s);return s}const se=Js;function je(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function co(a){return typeof self<"u"&&a===self.ManagedMediaSource}function hn(a,e){const t=Object.keys(a),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(n=>s.indexOf(n)===-1)}function Re(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=a.length;let s,i,r,n="",o=0;for(;o<t;){if(s=a[o++],s===0&&e)return n;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(s);break;case 12:case 13:i=a[o++],n+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=a[o++],r=a[o++],n+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return n}function Ee(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function un(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function ho(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Ds={exports:{}},zi;function uo(){return zi||(zi=1,function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var y={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(y.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)y.path=f.path,d.params||(y.params=f.params,d.query||(y.query=f.query));else{var p=f.path,E=p.substring(0,p.lastIndexOf("/")+1)+d.path;y.path=o.normalizePath(E)}return y.path===null&&(y.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(y)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(n,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};a.exports=o})()}(Ds)),Ds.exports}var Ti=uo();class Ts{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var re={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Si{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,fo(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[re.AUDIO]:null,[re.VIDEO]:null,[re.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Ts),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ti.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[re.AUDIO]=null,e[re.VIDEO]=null,e[re.AUDIOVIDEO]=null}}function ce(a){return a.sn!=="initSegment"}class es extends Si{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(M(e)&&M(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=M(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!M(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ce(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class dn extends Si{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function fn(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||fn(t,e)}}function fo(a,e){const t=fn(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const Qi=Math.pow(2,32)-1,go=[].push,gn={video:1,audio:2,id3:3,text:4};function he(a){return String.fromCharCode.apply(null,a)}function mn(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function W(a,e){const t=pn(a,e);return t<0?4294967296+t:t}function Zi(a,e){let t=W(a,e);return t*=Math.pow(2,32),t+=W(a,e+4),t}function pn(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function mo(a){const e=a.byteLength;for(let t=0;t<e;){const s=W(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function z(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=W(a,i),n=he(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const c=z(a.subarray(i+8,o),e.slice(1));c.length&&go.apply(t,c)}i=o}return t}function po(a){const e=[],t=a[0];let s=8;const i=W(a,s);s+=4;let r=0,n=0;t===0?(r=W(a,s),n=W(a,s+4),s+=8):(r=Zi(a,s),n=Zi(a,s+8),s+=16),s+=2;let o=a.length+n;const c=mn(a,s);s+=2;for(let l=0;l<c;l++){let h=s;const u=W(a,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return se.warn("SIDX has hierarchical references (not supported)"),null;const g=W(a,h);h+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function yn(a){const e=[],t=z(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=z(r,["tkhd"])[0];if(n){let o=n[0];const c=W(n,o===0?12:20),l=z(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=W(l,o===0?12:20),u=z(r,["mdia","hdlr"])[0];if(u){const d=he(u.subarray(8,12)),f={soun:re.AUDIO,vide:re.VIDEO}[d],g=z(r,["mdia","minf","stbl","stsd"])[0],y=yo(g);f?(e[c]={timescale:h,type:f,stsd:y},e[f]=te({timescale:h,id:c},y)):e[c]={timescale:h,type:d,stsd:y}}}}}return z(a,["moov","mvex","trex"]).forEach(i=>{const r=W(i,4),n=e[r];n&&(n.default={duration:W(i,12),flags:W(i,20)})}),e}function yo(a){const e=a.subarray(8),t=e.subarray(86),s=he(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=z(e,[s])[0].subarray(s==="enca"?28:78);z(l,["sinf"]).forEach(u=>{const d=z(u,["schm"])[0];if(d){const f=he(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=z(u,["frma"])[0];g&&(i=he(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=z(t,["avcC"])[0];c&&c.length>3&&(i+="."+Ut(c[1])+Ut(c[2])+Ut(c[3]),r=Bt(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=z(e,[s])[0],l=z(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=Cs(l,h),h+=2;const u=l[h++];if(u&128&&(h+=2),u&64&&(h+=l[h++]),l[h++]!==4)break;h=Cs(l,h);const d=l[h++];if(d===64)i+="."+Ut(d);else break;if(h+=12,l[h++]!==5)break;h=Cs(l,h);const f=l[h++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const c=z(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],u=l&31,d=W(c,2),f=(l&32)>>5?"H":"L",g=c[12],y=c.subarray(6,12);i+="."+h+u,i+="."+Eo(d).toString(16).toUpperCase(),i+="."+f+g;let p="";for(let E=y.length;E--;){const T=y[E];(T||p)&&(p="."+T.toString(16).toUpperCase()+p)}i+=p}r=Bt(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Bt(i,t)||i;break}case"vp09":{const c=z(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],u=c[6]>>4&15;i+="."+Be(l)+"."+Be(h)+"."+Be(u)}break}case"av01":{const c=z(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,u=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,f=(c[2]&32)>>5,g=l===2&&d?f?12:10:d?10:8,y=(c[2]&16)>>4,p=(c[2]&8)>>3,E=(c[2]&4)>>2,T=c[2]&3;i+="."+l+"."+Be(h)+u+"."+Be(g)+"."+y+"."+p+E+T+"."+Be(1)+"."+Be(1)+"."+Be(1)+"."+0,r=Bt("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function Bt(a,e){const t=z(e,["dvvC"]),s=t.length?t[0]:z(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+Be(i)+"."+Be(r)}}function Eo(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<31-t;return e>>>0}function Cs(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function Ut(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function Be(a){return(a<10?"0":"")+a}function To(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&En(a,(s,i)=>{const r=s.subarray(8,24);r.some(n=>n!==0)||(se.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Ee(r)} -> ${Ee(t)}`),s.set(t,8))})}function So(a){const e=[];return En(a,t=>e.push(t.subarray(8,24))),e}function En(a,e){z(a,["moov","trak"]).forEach(s=>{const i=z(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=z(r,["enca"]);const o=n.length>0;o||(n=z(r,["encv"])),n.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);z(l,["sinf"]).forEach(u=>{const d=Tn(u);d&&e(d,o)})})})}function Tn(a){const e=z(a,["schm"])[0];if(e){const t=he(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=z(a,["schi","tenc"])[0];if(s)return s}}}function vo(a,e,t){const s={},i=z(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=z(n,["tfhd"])[0],c=W(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],u=z(n,["tfdt"])[0];if(u){const S=u[0];let v=W(u,4);S===1&&(v===Qi?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(v*=Qi+1,v+=W(u,8))),M(v)&&(!M(h.start)||v<h.start)&&(h.start=v)}const d=l.default,f=W(o,0)|d?.flags;let g=d?.duration||0;f&8&&(f&2?g=W(o,12):g=W(o,8));const y=z(n,["trun"]);let p=h.start||0,E=0,T=g;for(let S=0;S<y.length;S++){const v=y[S],x=W(v,4),D=h.sampleCount;h.sampleCount+=x;const A=v[3]&1,_=v[3]&4,b=v[2]&1,I=v[2]&2,P=v[2]&4,F=v[2]&8;let U=8,H=x;for(A&&(U+=4),_&&x&&(!(v[U+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=D),U+=4,b?(T=W(v,U),U+=4):T=g,I&&(U+=4),F&&(U+=4),p+=T,E+=T,H--);H--;)b?(T=W(v,U),U+=4):T=g,I&&(U+=4),P&&(v[U+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(H+1),h.keyFrameStart=p),U+=4),F&&(U+=4),p+=T,E+=T;!E&&g&&(E+=g*x)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=z(a,["sidx"]);for(let c=0;c<o.length;c++){const l=po(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((u,d)=>u+d.info.duration||0,0);n=Math.max(n,h+l.earliestPresentationTime/l.timescale)}}n&&M(n)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=n*s[c].timescale-s[c].start)})}return s}function xo(a){const e={valid:null,remainder:null},t=z(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=a.slice(0,s.byteOffset-8),e.remainder=a.slice(s.byteOffset-8),e}function De(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Ji(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return z(s,["moof"]).map(c=>{const l=c.byteOffset-8;z(c,["traf"]).map(u=>{const d=z(u,["tfdt"]).map(f=>{const g=f[0];let y=W(f,4);return g===1&&(y*=Math.pow(2,32),y+=W(f,8)),y/i})[0];return d!==void 0&&(a=d),z(u,["tfhd"]).map(f=>{const g=W(f,4),y=W(f,0)&16777215,p=(y&1)!==0,E=(y&2)!==0,T=(y&8)!==0;let S=0;const v=(y&16)!==0;let x=0;const D=(y&32)!==0;let A=8;g===r&&(p&&(A+=8),E&&(A+=4),T&&(S=W(f,A),A+=4),v&&(x=W(f,A),A+=4),D&&(A+=4),e.type==="video"&&(n=Ss(e.codec)),z(u,["trun"]).map(_=>{const b=_[0],I=W(_,0)&16777215,P=(I&1)!==0;let F=0;const U=(I&4)!==0,H=(I&256)!==0;let $=0;const k=(I&512)!==0;let G=0;const N=(I&1024)!==0,K=(I&2048)!==0;let Y=0;const w=W(_,4);let O=8;P&&(F=W(_,O),O+=4),U&&(O+=4);let j=F+l;for(let ee=0;ee<w;ee++){if(H?($=W(_,O),O+=4):$=S,k?(G=W(_,O),O+=4):G=x,N&&(O+=4),K&&(b===0?Y=W(_,O):Y=pn(_,O),O+=4),e.type===re.VIDEO){let X=0;for(;X<G;){const Z=W(s,j);if(j+=4,Ao(n,s[j])){const pe=s.subarray(j,j+Z);vi(pe,n?2:1,a+Y/i,t)}j+=Z,X+=Z+4}}a+=$/i}}))})})}),t}function Ss(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Ao(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function vi(a,e,t,s){const i=Sn(a);let r=0;r+=e;let n=0,o=0,c=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;c=i[r++],n+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){se.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(n===4){if(i[h++]===181){const d=mn(i,h);if(h+=2,d===49){const f=W(i,h);if(h+=4,f===1195456820){const g=i[h++];if(g===3){const y=i[h++],p=31&y,E=64&y,T=E?2+p*3:0,S=new Uint8Array(T);if(E){S[0]=y;for(let v=1;v<T;v++)S[v]=i[h++]}s.push({type:g,payloadType:n,pts:t,bytes:S})}}}}}else if(n===5&&o>16){const u=[];for(let g=0;g<16;g++){const y=i[h++].toString(16);u.push(y.length==1?"0"+y:y),(g===3||g===5||g===7||g===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[h++];s.push({payloadType:n,pts:t,uuid:u.join(""),userData:Re(f),userDataBytes:f})}}}function Sn(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function Io(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,c=0,l=0;if(e===0){for(;he(a.subarray(l,l+1))!=="\0";)t+=he(a.subarray(l,l+1)),l+=1;for(t+=he(a.subarray(l,l+1)),l+=1;he(a.subarray(l,l+1))!=="\0";)s+=he(a.subarray(l,l+1)),l+=1;s+=he(a.subarray(l,l+1)),l+=1,i=W(a,12),r=W(a,16),o=W(a,20),c=W(a,24),l=28}else if(e===1){l+=4,i=W(a,l),l+=4;const u=W(a,l);l+=4;const d=W(a,l);for(l+=4,n=2**32*u+d,eo(n)||(n=Number.MAX_SAFE_INTEGER,se.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=W(a,l),l+=4,c=W(a,l),l+=4;he(a.subarray(l,l+1))!=="\0";)t+=he(a.subarray(l,l+1)),l+=1;for(t+=he(a.subarray(l,l+1)),l+=1;he(a.subarray(l,l+1))!=="\0";)s+=he(a.subarray(l,l+1)),l+=1;s+=he(a.subarray(l,l+1)),l+=1}const h=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function Lo(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function Ro(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),Lo([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t)}function bo(a){const e=[];if(a instanceof ArrayBuffer){const t=a.byteLength;let s=0;for(;s+32<t;){const i=new DataView(a,s),r=_o(i);e.push(r),s+=r.size}}return e}function _o(a){const e=a.getUint32(0),t=a.byteOffset,s=a.byteLength;if(s<e)return{offset:t,size:s};if(a.getUint32(4)!==1886614376)return{offset:t,size:e};const r=a.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=a.buffer,o=Ee(new Uint8Array(n,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const d=a.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let f=0;f<d;f++)c.push(new Uint8Array(n,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=a.getUint32(h);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(n,t+h+4,u),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const vn=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),St={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function xi(a,e){const t=St[e];return!!t&&!!t[a.slice(0,4)]}function Pt(a,e,t=!0){return!a.split(",").some(s=>!Ai(s,e,t))}function Ai(a,e,t=!0){var s;const i=je(t);return(s=i?.isTypeSupported(kt(a,e)))!=null?s:!1}function kt(a,e){return`${e}/mp4;codecs=${a}`}function er(a){if(a){const e=a.substring(0,4);return St.video[e]}return 2}function ls(a){const e=vn();return a.split(",").reduce((t,s)=>{const r=e&&Ss(s)?9:St.video[s];return r?(r*2+t)/(t?3:2):(St.audio[s]+t)/(t?2:1)},0)}const Ps={};function Do(a,e=!0){if(Ps[a])return Ps[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let i=0;i<t.length;i++){var s;if(Ai(t[i],"audio",e))return Ps[a]=t[i],t[i];if(t[i]==="mp3"&&(s=je(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const Co=/flac|opus|mp4a\.40\.34/i;function cs(a,e=!0){return a.replace(Co,t=>Do(t.toLowerCase(),e))}function Po(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)xi(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function ts(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(tr(a,"audio")||tr(a,"video")))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let s=t.length;s--;)if(t[s].substring(0,4)===a.substring(0,4))return t[s]}return t[0]}}return e||a}function tr(a,e){return xi(a,e)&&Ai(a,e)}function ko(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function wo(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return a}function sr(a){const e=je(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ei(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Oo={supported:!0,powerEfficient:!0,smooth:!0},Fo={supported:!1,smooth:!1,powerEfficient:!1},xn={supported:!0,configurations:[],decodingInfoResults:[Oo]};function An(a,e){return{supported:!1,configurations:e,decodingInfoResults:[Fo],error:a}}function Mo(a,e,t,s,i,r){const n=a.videoCodec,o=a.audioCodec?a.audioGroups:null,c=r?.audioCodec,l=r?.channels,h=l?parseInt(l):c?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(y=>{d[y]=(d[y]||0)+g.channels[y]})}return d},{2:0})}catch{return!0}return n!==void 0&&(n.split(",").some(d=>Ss(d))||a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!u&&M(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function In(a,e,t,s={}){const i=a.videoCodec;if(!i&&!a.audioCodec||!t)return Promise.resolve(xn);const r=[],n=No(a),o=n.length,c=Bo(a,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const u={type:"media-source"};if(o&&(u.video=n[h%o]),l){u.audio=c[h%l];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>Ss(u))&&vn())return Promise.resolve(An(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=$o(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function No(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),s=Ln(a),i=a.width||640,r=a.height||480,n=a.frameRate||30,o=a.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:kt(wo(c),"video"),width:i,height:r,bitrate:s,framerate:n};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function Bo(a,e,t){var s;const i=(s=a.audioCodec)==null?void 0:s.split(","),r=Ln(a);return i&&a.audioGroups?a.audioGroups.reduce((n,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(f=>{const g={contentType:kt(f,"audio"),bitrate:t?Uo(f,r):r};d&&(g.channels=""+d),h.push(g)})}return h},n):n},[]):[]}function Uo(a,e){if(e<=1)return 1;let t=128e3;return a==="ec-3"?t=768e3:a==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Ln(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function $o(a){let e="";const{audio:t,video:s}=a;if(s){const i=ei(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=ei(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const ti=["NONE","TYPE-0","TYPE-1",null];function Go(a){return ti.indexOf(a)>-1}const hs=["SDR","PQ","HLG"];function Ko(a){return!!a&&hs.indexOf(a)>-1}var bt={No:"",Yes:"YES",v2:"v2"};function ir(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?bt.v2:bt.Yes:bt.No}class si{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class vt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return rr(this._audioGroups,e)}hasSubtitleGroup(e){return rr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function rr(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function Vo(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function Ho(a,e){let t=!1,s=[];if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||hs.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Vo(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Yo=a=>{const e=new WeakSet;return(t,s)=>{if(a&&(s=a(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ne=(a,e)=>JSON.stringify(a,Yo(e));function Wo(a,e,t,s,i){const r=Object.keys(a),n=s?.channels,o=s?.audioCodec,c=i?.videoCodec,l=n&&parseInt(n)===2;let h=!1,u=!1,d=1/0,f=1/0,g=1/0,y=1/0,p=0,E=[];const{preferHDR:T,allowedVideoRanges:S}=Ho(e,i);for(let _=r.length;_--;){const b=a[r[_]];h||(h=b.channels[2]>0),d=Math.min(d,b.minHeight),f=Math.min(f,b.minFramerate),g=Math.min(g,b.minBitrate),S.filter(P=>b.videoRanges[P]>0).length>0&&(u=!0)}d=M(d)?d:0,f=M(f)?f:0;const v=Math.max(1080,d),x=Math.max(30,f);g=M(g)?g:t,t=Math.max(g,t),u||(e=void 0);const D=r.length>1;return{codecSet:r.reduce((_,b)=>{const I=a[b];if(b===_)return _;if(E=u?S.filter(P=>I.videoRanges[P]>0):[],D){if(I.minBitrate>t)return Me(b,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),_;if(!I.hasDefaultAudio)return Me(b,"no renditions with default or auto-select sound found"),_;if(o&&b.indexOf(o.substring(0,4))%5!==0)return Me(b,`audio codec preference "${o}" not found`),_;if(n&&!l){if(!I.channels[n])return Me(b,`no renditions with ${n} channel sound found (channels options: ${Object.keys(I.channels)})`),_}else if((!o||l)&&h&&I.channels[2]===0)return Me(b,"no renditions with stereo sound found"),_;if(I.minHeight>v)return Me(b,`min resolution of ${I.minHeight} > maximum of ${v}`),_;if(I.minFramerate>x)return Me(b,`min framerate of ${I.minFramerate} > maximum of ${x}`),_;if(!E.some(P=>I.videoRanges[P]>0))return Me(b,`no variants with VIDEO-RANGE of ${ne(E)} found`),_;if(c&&b.indexOf(c.substring(0,4))%5!==0)return Me(b,`video codec preference "${c}" not found`),_;if(I.maxScore<p)return Me(b,`max score of ${I.maxScore} < selected max of ${p}`),_}return _&&(ls(b)>=ls(_)||I.fragmentError>a[_].fragmentError)?_:(y=I.minIndex,p=I.maxScore,b)},void 0),videoRanges:E,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:y}}function Me(a,e){se.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function Rn(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function qo(a,e,t,s){return a.slice(t,s+1).reduce((i,r,n)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,n),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+u.channels[d]}))}),i},{})}function nr(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=a;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function $e(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(ot(a,i,t))return s}return-1}function ot(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,default:o}=a,c=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||jo(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in a)||Xo(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function jo(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function Xo(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function at(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function zo(a,e,t,s,i){const r=e[s],o=e.reduce((d,f,g)=>{const y=f.uri;return(d[y]||(d[y]=[])).push(g),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),u=ar(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return $e(a,g,i)>-1});return u>-1?u:ar(e,s,d=>{const f=d.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return $e(a,g,i)>-1})}function ar(a,e,t){for(let s=e;s>-1;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}function us(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class bn extends Ce{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:c}=n;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=l-h.loading.start,f=n.minAutoLevel,g=i.level,y=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const p=y>-1&&y!==g,E=!!t||p;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const T=n.mainForwardBufferInfo;if(!E&&T===null)return;const S=this.bwEstimator.getEstimateTTFB(),v=Math.abs(c.playbackRate);if(d<=Math.max(S,1e3*(u/(v*2))))return;const x=T?T.len/v:0,D=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&D>-1,_=this.getBwEstimate(),b=n.levels,I=b[g],P=Math.max(h.loaded,Math.round(u*(i.bitrate||I.averageBitrate)/8));let F=A?d-D:d;F<1&&A&&(F=Math.min(d,h.loaded*8/_));const U=A?h.loaded*1e3/F:0,H=S/1e3,$=U?(P-h.loaded)/U:P*8/_+H;if($<=x)return;const k=U?U*8:_,G=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,N=this.hls.config.abrBandWidthUpFactor;let K=Number.POSITIVE_INFINITY,Y;for(Y=g-1;Y>f;Y--){const ee=b[Y].maxBitrate,X=!b[Y].details||G;if(K=this.getTimeToLoadFrag(H,k,u*ee,X),K<Math.min(x,u+H))break}if(K>=$||K>u*10)return;A?this.bwEstimator.sample(d-Math.min(S,D),h.loaded):this.bwEstimator.sampleTTFB(d);const w=b[Y].maxBitrate;this.getBwEstimate()*N>w&&this.resetEstimator(w);const O=this.findBestLevel(w,f,Y,0,x,1,1);O>-1&&(Y=O),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
|
|
2
2
|
Fragment duration: ${i.duration.toFixed(3)}
|
|
3
3
|
Time to underbuffer: ${x.toFixed(3)} s
|
|
4
4
|
Estimated load time for current fragment: ${$.toFixed(3)} s
|
|
@@ -13,7 +13,7 @@ Playlist starting @${e.startSN}
|
|
|
13
13
|
${e.m3u8}
|
|
14
14
|
|
|
15
15
|
Playlist starting @${t.startSN}
|
|
16
|
-
${t.m3u8}`)}function Gn(a,e,t=!0){const s=e.startSN+e.skippedSegments-a.startSN,i=a.fragments,r=s>=0;let n=0;if(r&&s<i.length)n=i[s].start;else if(r&&e.startSN===a.endSN+1)n=a.fragmentEnd;else if(r&&t)n=a.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)n=a.fragmentStart;else return;oi(e,n)}function oi(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function Kn(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Vn(a,e,t){if(!a)return null;let s=a.fragments[e-a.startSN];return s||(s=a.fragmentHint,s&&s.sn===e)?s:e<a.startSN&&t&&t.sn===e?t:null}function Cr(a,e,t){return a?Hn(a.partList,e,t):null}function Hn(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Yn(a){a.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function Cl(a,e){return a!==e&&e?Pr(a)!==Pr(e):!1}function Pr(a){return a.replace(/\?[^?]*$/,"")}function _t(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function Pl(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function kr(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function Wn(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)kr(t[s],a);e.fragmentHint&&kr(e.fragmentHint,a),e.alignedSliding=!0}function kl(a,e){a&&(qn(e,a),e.alignedSliding||ps(e,a),!e.alignedSliding&&!e.skippedSegments&&Gn(a,e,!1))}function qn(a,e){if(!Pl(e,a))return;const t=Math.min(e.endCC,a.endCC),s=_t(e.fragments,t),i=_t(a.fragments,t);if(!s||!i)return;se.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;Wn(r,a)}function ps(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=_t(s,n),r=_t(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=_t(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);Wn(l,a)}function Te(a,e,t){Ae(a,e,t),a.addEventListener(e,t)}function Ae(a,e,t){a.removeEventListener(e,t)}const wl={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},C={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class xs extends wn{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,u=c?c.currentTime:0,d=q.bufferInfo(l||c,u,n.maxBufferHole),f=!d.len;if(this.log(`Media seeking to ${M(u)?u.toFixed(3):u}, state: ${h}, ${f?"out of":"in"} buffer`),this.state===C.ENDED)this.resetLoadingState();else if(o){const g=n.maxFragLookUpTolerance,y=o.start-g,p=o.start+o.duration+g;if(f||p<d.start||y>d.end){const E=u>p;(u<y||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(u>g&&(this.lastCurrentTime=u),!this.loadingParts){const y=Math.max(d.end,u),p=this.shouldLoadParts(this.getLevelDetails(),y);p&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${y.toFixed(2)}`),this.loadingParts=p)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===C.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new ll(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Li(e.config)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=q.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return q.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Te(s,"seeking",this.onMediaSeeking),Te(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ae(i,"seeking",this.onMediaSeeking),Ae(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=C.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,o=r.frag;if(this.fragContextChanged(o)){(n===C.FRAG_LOADING||!this.fragCurrent&&n===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===de.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===de.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,o=r.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&Et(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,bi(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==C.STOPPED&&(this.state=C.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(o.message),!n||n.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?wl.toString(q.getBuffered(s)):"(detached)"})`),ce(e)){var i;if(e.type!==B.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=C.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=C.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(c=>!c),o=new vs(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===C.KEY_LOADING&&(this.state=C.IDLE),d}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(ce(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&ce(e)){const d=n.partList;if(d&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const f=this.getNextPart(d,e,s);if(f>-1){const g=d[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${d.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=C.FRAG_LOADING;let y;return o?y=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(p=>this.handleFragLoadError(p)):y=this.doFragPartsLoad(e,g,t,i).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):y}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(ce(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),M(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;const h=this.config.progressive;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([d])=>(!h&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{c[u.index]=d;const f=d.part;this.hls.trigger(m.FRAG_LOADED,d);const g=Cr(s.details,e.sn,u.index+1)||Hn(l,e.sn,u.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:c})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===V.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===B.SUBTITLE)return!1;const n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=n>-1?Cr(c,r,n):null,h=l?l.fragment:Vn(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==C.PARSING)return;const{data1:n,data2:o}=e;let c=n;if(o&&(c=De(n,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=q.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!M(i))return null;const n=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}getFwdBufferInfoAtPos(e,t,s,i){const r=q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(r.nextStart,n.end)-t,i);return q.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=B.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,f=this.hls.liveSyncPosition,g=c?(d!==-1&&d>=n?d:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=n&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const u=c.sn-t.startSN;h=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===de.OK||s===de.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=n.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(wr(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(wr(this.config)&&e.type!==B.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s?.playerQueue;if(r)for(let n=r.length;n--;){const o=r[n].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Qo(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Dn(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&c);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(n=n.concat(c),o=c.sn);let d;if(e<t){var f;const y=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;d=ct(r,n,e,y)}else d=n[n.length-1];if(d){const g=d.sn-s.startSN,y=this.fragmentTracker.getState(d);if((y===de.OK||y===de.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!s.live)&&d.level===r.level){const E=n[g+1];d.sn<o&&this.fragmentTracker.getState(E)!==de.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,o=e.alignedSliding&&M(r);if(n||!o&&!r){kl(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&M(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ce(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===R.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=C.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&c===ue.RetryRequest,g=d&&!o.resolved&&l===ve.MoveAllAlternatesMatchingHost,y=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&ce(i)&&!i.endList&&y&&!Pn(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var p;const E=ii((p=t.response)==null?void 0:p.code),T=Ii(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=C.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${T}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!n&&c!==ue.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===ue.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!ii(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=C.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===B.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const d=i?0:$n(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;if(s.fragmentError===0&&this.treatAsGap(e,s),((o=this.transmuxer)==null?void 0:o.error)===null){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===B.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function wr(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class jn{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Ol(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Ol(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}var Fs={exports:{}},Or;function Fl(){return Or||(Or=1,function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,u||c,d),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function n(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,u;if(this._eventsCount===0)return l;for(u in h=this._events)e.call(h,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},o.prototype.listenerCount=function(l){var h=t?t+l:l,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,h,u,d,f,g){var y=t?t+l:l;if(!this._events[y])return!1;var p=this._events[y],E=arguments.length,T,S;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),E){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,h),!0;case 3:return p.fn.call(p.context,h,u),!0;case 4:return p.fn.call(p.context,h,u,d),!0;case 5:return p.fn.call(p.context,h,u,d,f),!0;case 6:return p.fn.call(p.context,h,u,d,f,g),!0}for(S=1,T=new Array(E-1);S<E;S++)T[S-1]=arguments[S];p.fn.apply(p.context,T)}else{var v=p.length,x;for(S=0;S<v;S++)switch(p[S].once&&this.removeListener(l,p[S].fn,void 0,!0),E){case 1:p[S].fn.call(p[S].context);break;case 2:p[S].fn.call(p[S].context,h);break;case 3:p[S].fn.call(p[S].context,h,u);break;case 4:p[S].fn.call(p[S].context,h,u,d);break;default:if(!T)for(x=1,T=new Array(E-1);x<E;x++)T[x-1]=arguments[x];p[S].fn.apply(p[S].context,T)}}return!0},o.prototype.on=function(l,h,u){return r(this,l,h,u,!1)},o.prototype.once=function(l,h,u){return r(this,l,h,u,!0)},o.prototype.removeListener=function(l,h,u,d){var f=t?t+l:l;if(!this._events[f])return this;if(!h)return n(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!d||g.once)&&(!u||g.context===u)&&n(this,f);else{for(var y=0,p=[],E=g.length;y<E;y++)(g[y].fn!==h||d&&!g[y].once||u&&g[y].context!==u)&&p.push(g[y]);p.length?this._events[f]=p.length===1?p[0]:p:n(this,f)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o}(Fs)),Fs.exports}var Ml=Fl(),Ci=ho(Ml);const wt="1.6.13",xt={};function Nl(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Bl(){const a=xt[wt];if(a)return a.clientCount++,a;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return xt[wt]=i,i}function Ul(a){const e=xt[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return xt[a]=i,i}function $l(a){const e=xt[a||wt];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete xt[a||wt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Xn(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Pi(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function As(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function Ot(a,e){const t=e;let s=0;for(;Pi(a,e);){s+=10;const i=As(a,e+6);s+=i,Xn(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function Gl(a,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],n=r>>2&15;if(n>12){const f=new Error(`invalid ADTS sampling index:${n}`);a.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[n];let u=n;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return se.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${n})`),{config:d,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function zn(a,e){return a[e]===255&&(a[e+1]&246)===240}function Qn(a,e){return a[e+1]&1?7:9}function ki(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function Kl(a,e){return e+5<a.length}function ys(a,e){return e+1<a.length&&zn(a,e)}function Vl(a,e){return Kl(a,e)&&zn(a,e)&&ki(a,e)<=a.length-e}function Hl(a,e){if(ys(a,e)){const t=Qn(a,e);if(e+t>=a.length)return!1;const s=ki(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||ys(a,i)}return!1}function Zn(a,e,t,s,i){if(!a.samplerate){const r=Gl(e,t,s,i);if(!r)return;ie(a,r)}}function Jn(a){return 1024*9e4/a}function Yl(a,e){const t=Qn(a,e);if(e+t<=a.length){const s=ki(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function ea(a,e,t,s,i){const r=Jn(a.samplerate),n=s+i*r,o=Yl(e,t);let c;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+f);const y={unit:c,pts:n};return g||a.samples.push(y),{sample:y,length:f,missing:g}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:n},length:l,missing:-1}}function Wl(a,e){return Pi(a,e)&&As(a,e+6)+10<=a.length-e}function ql(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function Ms(a,e=0,t=1/0){return jl(a,e,t,Uint8Array)}function jl(a,e,t,s){const i=Xl(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=zl(a)?a.byteOffset:0,o=(n+a.byteLength)/r,c=(n+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function Xl(a){return a instanceof ArrayBuffer?a:a.buffer}function zl(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function Ql(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=a.data.subarray(1).indexOf(0);if(s===-1)return;const i=Re(Ms(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=Re(Ms(a.data,3+s,n));let c;return i==="-->"?c=Re(Ms(a.data,4+s+n)):c=ql(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Zl(a){if(a.size<2)return;const e=Re(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function Jl(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=Re(a.data.subarray(t),!0);t+=s.length+1;const i=Re(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Re(a.data.subarray(1));return{key:a.type,info:"",data:e}}function ec(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=Re(a.data.subarray(t),!0);t+=s.length+1;const i=Re(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Re(a.data);return{key:a.type,info:"",data:e}}function tc(a){return a.type==="PRIV"?Zl(a):a.type[0]==="W"?ec(a):a.type==="APIC"?Ql(a):Jl(a)}function sc(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=As(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const Vt=10,ic=10;function ta(a){let e=0;const t=[];for(;Pi(a,e);){const s=As(a,e+6);a[e+5]>>6&1&&(e+=Vt),e+=Vt;const i=e+s;for(;e+ic<i;){const r=sc(a.subarray(e)),n=tc(r);n&&t.push(n),e+=r.size+Vt}Xn(a,e)&&(e+=Vt)}return t}function sa(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function rc(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function wi(a){const e=ta(a);for(let t=0;t<e.length;t++){const s=e[t];if(sa(s))return rc(s)}}let xe=function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a}({});function Ue(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Oi{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=De(this.cachedData,e),this.cachedData=null);let s=Ot(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,c=s?wi(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&M(c))&&(this.basePTS=nc(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:xe.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else Wl(e,i)?(s=Ot(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:xe.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=De(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:Ue(),id3Track:o,textTrack:Ue()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ue(),id3Track:this._id3Track,textTrack:Ue()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const nc=(a,e,t)=>{if(M(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let Ht=null;const ac=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],oc=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],lc=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cc=[0,1,1,4];function ia(a,e,t,s,i){if(t+24>e.length)return;const r=ra(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function ra(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,c=t===3?3-s:s===3?3:4,l=ac[c*14+i-1]*1e3,u=oc[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=lc[t][s],g=cc[s],y=f*8*g,p=Math.floor(f*l/u+n)*g;if(Ht===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ht=S?parseInt(S[1]):0}return!!Ht&&Ht<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:u,channelCount:d,frameLength:p,samplesPerFrame:y}}}function Fi(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function na(a,e){return e+1<a.length&&Fi(a,e)}function hc(a,e){return Fi(a,e)&&4<=a.length-e}function aa(a,e){if(e+1<a.length&&Fi(a,e)){const s=ra(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||na(a,r)}return!1}class uc extends Oi{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Ot(e,0);let i=s?.length||0;if(aa(e,i))return!1;for(let r=e.length;i<r;i++)if(Hl(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Vl(e,t)}appendFrame(e,t,s){Zn(e,this.observer,t,s,e.manifestCodec);const i=ea(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const oa=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(n[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class dc extends Oi{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=la(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Ot(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&wi(t)!==void 0&&oa(e,s)<16}}function la(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,y=[2,1,2,3,3,4,4,5][u]+f,p=e[t+5]>>3,E=e[t+5]&7,T=new Uint8Array([r<<6|p<<1|E>>2,(E&3)<<6|u<<3|f<<2|c>>4,c<<4&224]),S=1536/o*9e4,v=s+i*S,x=e.subarray(t,t+h);return a.config=T,a.channelCount=y,a.samplerate=o,a.samples.push({unit:x,pts:v}),h}class fc extends Oi{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Ot(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&wi(t)!==void 0&&oa(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(aa(e,s))return se.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return hc(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return ia(e,t,s,this.basePTS,this.frameIndex)}}const gc=/\/emsg[-/]ID3/i;class mc{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Ue("video",1),n=this.audioTrack=Ue("audio",1),o=this.txtTrack=Ue("text",1);if(this.id3Track=Ue("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=yn(e);if(c.video){const{id:l,timescale:h,codec:u,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(c.audio){const{id:l,timescale:h,codec:u}=c.audio;n.id=l,n.timescale=h,n.codec=u}o.id=gn.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return mo(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=De(this.remainderData,e));const o=xo(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Ji(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Ji(e,t),{videoTrack:t,audioTrack:Ue(),id3Track:i,textTrack:Ue()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=z(e.samples,["emsg"]);i&&i.forEach(r=>{const n=Io(r);if(gc.test(n.schemeIdUri)){const o=Fr(n,t);let c=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:xe.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Fr(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:xe.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function Fr(a,e){return M(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class pc{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Li(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,et.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=Sn(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(n,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}class ca{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,o=[];let c=0,l,h,u,d=-1,f=0;for(r===-1&&(d=0,f=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,d>=0){const g={data:t.subarray(d,h),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(n&&c<=4-n&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-n)),h>0&&(g.data=De(g.data,t.subarray(0,h)),g.state=0))}c<i?(u=this.getNALuType(t,c),d=c,f=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const g={data:t.subarray(d,i),type:f,state:r};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=De(g.data,t))}return e.naluState=r,o}}class Dt{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&se.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class yc extends ca{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 1:{let y=!1;o=!0;const p=l.data;if(c&&p.length>4){const E=this.readSliceType(p);(E===2||E===4||E===7||E===9)&&(y=!0)}if(y){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=y;break}case 5:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:{o=!0,vi(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const y=l.data,p=this.readSPS(y);if(!e.sps||e.width!==p.width||e.height!==p.height||((f=e.pixelRatio)==null?void 0:f[0])!==p.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[y];const E=y.subarray(1,4);let T="avc1.";for(let S=0;S<3;S++){let v=E[S].toString(16);v.length<2&&(v="0"+v),T+=v}e.codec=T}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Dt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new Dt(e);let s=0,i=0,r=0,n=0,o,c,l;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),y=t.skipEG.bind(t),p=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const T=h();if(u(5),g(3),h(),p(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){const _=d();if(_===3&&g(1),p(),p(),g(1),f())for(c=_!==3?8:12,l=0;l<c;l++)f()&&(l<6?E(16,t):E(64,t))}p();const S=d();if(S===0)d();else if(S===1)for(g(1),y(),y(),o=d(),l=0;l<o;l++)y();p(),g(1);const v=d(),x=d(),D=u(1);D===0&&g(1),g(1),f()&&(s=d(),i=d(),r=d(),n=d());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((v+1)*16-s*2-i*2),height:(2-D)*(x+1)*16-(D?2:4)*(r+n),pixelRatio:A}}}class Ec extends ca{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:o=!0,vi(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ie(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Dt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),y=t.readUByte(),p=t.readUByte(),E=t.readUByte(),T=[],S=[];for(let J=0;J<s;J++)T.push(t.readBoolean()),S.push(t.readBoolean());if(s>0)for(let J=s;J<8;J++)t.readBits(2);for(let J=0;J<s;J++)T[J]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[J]&&t.readUByte();t.readUEG();const v=t.readUEG();v==3&&t.skipBits(1);const x=t.readUEG(),D=t.readUEG(),A=t.readBoolean();let _=0,b=0,I=0,P=0;A&&(_+=t.readUEG(),b+=t.readUEG(),I+=t.readUEG(),P+=t.readUEG());const F=t.readUEG(),U=t.readUEG(),H=t.readUEG(),$=t.readBoolean();for(let J=$?0:s;J<=s;J++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let ye=0;ye<4;ye++)for(let _e=0;_e<(ye===3?2:6);_e++)if(!t.readBoolean())t.readUEG();else{const Pe=Math.min(64,1<<4+(ye<<1));ye>1&&t.readEG();for(let ht=0;ht<Pe;ht++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const N=t.readUEG();let K=0;for(let J=0;J<N;J++){let ye=!1;if(J!==0&&(ye=t.readBoolean()),ye){J===N&&t.readUEG(),t.readBoolean(),t.readUEG();let _e=0;for(let st=0;st<=K;st++){const Pe=t.readBoolean();let ht=!1;Pe||(ht=t.readBoolean()),(Pe||ht)&&_e++}K=_e}else{const _e=t.readUEG(),st=t.readUEG();K=_e+st;for(let Pe=0;Pe<_e;Pe++)t.readUEG(),t.readBoolean();for(let Pe=0;Pe<st;Pe++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const J=t.readUEG();for(let ye=0;ye<J;ye++){for(let _e=0;_e<H+4;_e++)t.readBits(1);t.readBits(1)}}let w=0,O=1,j=1,ee=!0,X=1,Z=0;t.readBoolean(),t.readBoolean();let pe=!1;if(t.readBoolean()){if(t.readBoolean()){const it=t.readUByte(),Vi=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Nt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];it>0&&it<16?(O=Vi[it-1],j=Nt[it-1]):it===255&&(O=t.readBits(16),j=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),pe=t.readBoolean(),pe&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(X=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Nt=t.readBoolean(),Hi=t.readBoolean();let At=!1;(Nt||Hi)&&(At=t.readBoolean(),At&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),At&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Yi=0;Yi<=s;Yi++){ee=t.readBoolean();const Ja=ee||t.readBoolean();let Wi=!1;Ja?t.readEG():Wi=t.readBoolean();const qi=Wi?1:t.readUEG()+1;if(Nt)for(let It=0;It<qi;It++)t.readUEG(),t.readUEG(),At&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Hi)for(let It=0;It<qi;It++)t.readUEG(),t.readUEG(),At&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),w=t.readUEG())}let be=x,Fe=D;if(A){let J=1,ye=1;v===1?J=ye=2:v==2&&(J=2),be=x-J*b-J*_,Fe=D-ye*P-ye*I}const tt=i?["A","B","C"][i]:"",Za=o<<24|c<<16|l<<8|h;let bs=0;for(let J=0;J<32;J++)bs=(bs|(Za>>J&1)<<31-J)>>>0;let _s=bs.toString(16);return n===1&&_s==="2"&&(_s="6"),{codecString:`hvc1.${tt}${n}.${_s}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[u,d,f,g,y,p],general_level_idc:E,bit_depth:F+8,bit_depth_luma_minus8:F,bit_depth_chroma_minus8:U,min_spatial_segmentation_idc:w,chroma_format_idc:v,frame_rate:{fixed:ee,fps:Z/X}},width:be,height:Fe,pixelRatio:[O,j]}}readPPS(e){const t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),r=t.readBoolean();let n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const fe=188;class Ze{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=Ze.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(fe*5,t-fe)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let c=i;c<t;c+=fe)if(e[c]===71&&(t-c===fe||e[c+fe]===71)){if(o++,n===-1&&(n=c,n!==0&&(s=Math.min(n+fe*99,e.length-fe)+1)),r||(r=li(e,c)===0),r&&o>1&&(n===0&&o>2||c+fe>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:gn[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ze.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Ze.createTrack("audio",i),this._id3Track=Ze.createTrack("id3"),this._txtTrack=Ze.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=n.pid,u=n.pesData,d=o.pid,f=c.pid,g=o.pesData,y=c.pesData,p=null,E=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(e=De(this.remainderData,e),S=e.length,this.remainderData=null),S<fe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};const v=Math.max(0,Ze.syncOffset(e));S-=(S-v)%fe,S<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let x=0;for(let A=v;A<S;A+=fe)if(e[A]===71){const _=!!(e[A+1]&64),b=li(e,A),I=(e[A+3]&48)>>4;let P;if(I>1){if(P=A+5+e[A+4],P===A+fe)continue}else P=A+4;switch(b){case h:_&&(u&&(r=ft(u,this.logger))&&(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(P,A+fe)),u.size+=A+fe-P);break;case d:if(_){if(g&&(r=ft(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(P,A+fe)),g.size+=A+fe-P);break;case f:_&&(y&&(r=ft(y,this.logger))&&this.parseID3PES(c,r),y={data:[],size:0}),y&&(y.data.push(e.subarray(P,A+fe)),y.size+=A+fe-P);break;case 0:_&&(P+=e[P]+1),T=this._pmtId=Tc(e,P);break;case T:{_&&(P+=e[P]+1);const F=Sc(e,P,this.typeSupported,s,this.observer,this.logger);h=F.videoPid,h>0&&(n.pid=h,n.segmentCodec=F.segmentVideoCodec),d=F.audioPid,d>0&&(o.pid=d,o.segmentCodec=F.segmentAudioCodec),f=F.id3Pid,f>0&&(c.pid=f),p!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${p}'. Backtracking to sync byte @${v} to parse all TS packets.`),p=null,A=v-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=b;break}}else x++;x>0&&ci(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=u,o.pesData=g,c.pesData=y;const D={audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(D),D}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,c=i.pesData;let l;if(n&&(l=ft(n,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,o&&(l=ft(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=ft(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new pc(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new yc:e==="hevc"&&(this.videoParser=new Ec))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=De(i.sample.unit,r);else{const f=d-u;i.sample.unit.set(r.subarray(0,u),f),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!ys(r,n);n++);if(n!==s){let u;const d=n<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${n}`:u="No ADTS header found in AAC PES",ci(this.observer,new Error(u),d,this.logger),!d)return}Zn(e,this.observer,r,n,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const u=Jn(e.samplerate);c=i.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;n<o;)if(h=ea(e,r,n,c,l),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;n<o-1&&!ys(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(na(s,n)){const c=ia(e,s,n,o,r);if(c)n+=c.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,c;for(;o<r&&(c=la(e,s,o,i,n++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ie({},t,{type:this._videoTrack?xe.emsg:xe.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function li(a,e){return((a[e+1]&31)<<8)+a[e+2]}function Tc(a,e){return(a[e+10]&31)<<8|a[e+11]}function Sc(a,e,t,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],c=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<c;){const h=li(a,e),u=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){Ns("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=h);break;case 21:n.id3Pid===-1&&(n.id3Pid=h);break;case 219:if(!s){Ns("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="mp3");break;case 193:if(!s){Ns("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&u>0){let d=e+5,f=u;for(;f>2;){switch(a[d]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=h,n.segmentAudioCodec="ac3");break}const y=a[d+1]+2;d+=y,f-=y}}break;case 194:case 135:return ci(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=h,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return n}function ci(a,e,t,s){s.warn(`parsing error: ${e.message}`),a.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Ns(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function ft(a,e){let t=0,s,i,r,n,o;const c=a.data;if(!a||a.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=De(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>a.size-6)return null;const h=s[7];h&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,n-o>60*9e4&&(e.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),r=s[8];let u=r+9;if(a.size<=u)return null;a.size-=u;const d=new Uint8Array(a.size);for(let f=0,g=c.length;f<g;f++){s=c[f];let y=s.byteLength;if(u)if(u>y){u-=y;continue}else s=s.subarray(u),y-=u,u=0;d.set(s,t),t+=y}return i&&(i-=r+3),{data:d,pts:n,dts:o,len:i}}return null}class vc{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Xe=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);L.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=r,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,n,c,n,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Xe+1)),i=Math.floor(t%(Xe+1));return L.box(L.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale||0,e.duration||0),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,s){return L.box(L.types.moof,L.mfhd(e),L.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(L.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Xe+1)),i=Math.floor(t%(Xe+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return L.box(L.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,s)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=L.box(L.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return L.box(L.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return L.box(L.types.mp4a,L.audioStsd(e),L.box(L.types.esds,L.esds(e)))}static mp3(e){return L.box(L.types[".mp3"],L.audioStsd(e))}static ac3(e){return L.box(L.types["ac-3"],L.audioStsd(e),L.box(L.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return L.box(L.types.stsd,L.STSD,L.mp4a(e));if(t==="ac3"&&e.config)return L.box(L.types.stsd,L.STSD,L.ac3(e));if(t==="mp3"&&e.codec==="mp3")return L.box(L.types.stsd,L.STSD,L.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return L.box(L.types.stsd,L.STSD,L.avc1(e));if(t==="hevc"&&e.vps)return L.box(L.types.stsd,L.STSD,L.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(Xe+1)),o=Math.floor(s%(Xe+1));return L.box(L.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=L.sdtp(e),i=e.id,r=Math.floor(t/(Xe+1)),n=Math.floor(t%(Xe+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),L.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,c,l,h,u,d;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,u=c.flags,d=c.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return L.box(L.types.trun,n)}static initSegment(e){L.types||L.init();const t=L.moov(e);return De(L.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let g=0;g<s.length;g+=1){n+=3;for(let y=0;y<s[g].length;y+=1)n+=2+s[g][y].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const c=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,s[g].length]),n),n+=3;for(let y=0;y<s[g].length;y+=1)o.set(new Uint8Array([s[g][y].length>>8,s[g][y].length&255]),n),n+=2,o.set(s[g][y],n),n+=s[g][y].length}const l=L.box(L.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return L.box(L.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}L.types=void 0;L.HDLR_TYPES=void 0;L.STTS=void 0;L.STSC=void 0;L.STCO=void 0;L.STSZ=void 0;L.VMHD=void 0;L.SMHD=void 0;L.STSD=void 0;L.FTYP=void 0;L.DINF=void 0;const ha=9e4;function Mi(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function xc(a,e,t=1,s=!1){return Mi(a,e,1/t,s)}function Lt(a,e=!1){return Mi(a,1e3,1/ha,e)}function Ac(a,e=1){return Mi(a,ha,1/e)}function Mr(a){const{baseTime:e,timescale:t,trackId:s}=a;return`${e/t} (${e}/${t}) trackId: ${s}`}const Ic=10*1e3,Lc=1024,Rc=1152,bc=1536;let gt=null,Bs=null;function Nr(a,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class is extends Ce{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,gt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);gt=n?parseInt(n[1]):0}if(Bs===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Bs=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Mr(t)} > ${e&&Mr(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,n)=>{let o=n.pts,c=o-r;return c<-4294967296&&(t=!0,o=Le(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,o,c){let l,h,u,d,f,g,y=r,p=r;const E=e.pid>-1,T=t.pid>-1,S=t.samples.length,v=e.samples.length>0,x=o&&S>0||S>1;if((!E||v)&&(!T||x)||this.ISGenerated||o){if(this.ISGenerated){var A,_,b,I;const H=this.videoTrackConfig;(H&&(t.width!==H.width||t.height!==H.height||((A=t.pixelRatio)==null?void 0:A[0])!==((_=H.pixelRatio)==null?void 0:_[0])||((b=t.pixelRatio)==null?void 0:b[1])!==((I=H.pixelRatio)==null?void 0:I[1]))||!H&&x||this.nextAudioTs===null&&v)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,n));const P=this.isVideoContiguous;let F=-1,U;if(x&&(F=_c(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,F>0){this.warn(`Dropped ${F} out of ${S} video samples due to a missing keyframe`);const H=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(F),t.dropped+=F,p+=(t.samples[0].pts-H)/t.inputTimeScale,U=p}else F===-1&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(v&&x){const H=this.getVideoStartPts(t.samples),k=(Le(e.samples[0].pts,H)-H)/t.inputTimeScale;y+=Math.max(0,k),p+=Math.max(0,-k)}if(v){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,y,this.isAudioContiguous,n,T||x||c===B.AUDIO?p:void 0),x){const H=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,p,P,H)}}else x&&(l=this.remuxVideo(t,p,P,0));l&&(l.firstKeyFrame=F,l.independent=F!==-1,l.firstKeyFramePTS=U)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=ua(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=da(i,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:g,text:d,id3:f}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Le(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,u="audio/mp4",d,f,g,y=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(y=e.id,g=e.inputTimeScale,!l||g!==l.timescale?d=f=this.computeInitPts(r[0].pts,g,s,"audio"):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(y=t.id,g=t.inputTimeScale,!l||g!==l.timescale){const p=this.getVideoStartPts(n),E=Le(n[0].dts,p),T=this.computeInitPts(E,g,s,"video"),S=this.computeInitPts(p,g,s,"video");f=Math.min(f,T),d=Math.min(d,S)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${y}`),this._initPTS={baseTime:d,timescale:g,trackId:y},this._initDTS={baseTime:f,timescale:g,trackId:y}):d=g=void 0,{tracks:c,initPTS:d,timescale:g,trackId:y}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],c=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let u=this.nextVideoTs,d=8,f=this.videoSampleDuration,g,y,p=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!s||u===null){const w=h+t*r,O=n[0].pts-Le(n[0].dts,n[0].pts);gt&&u!==null&&Math.abs(w-O-(u+h))<15e3?s=!0:u=w-O-h}const S=u+h;for(let w=0;w<c;w++){const O=n[w];O.pts=Le(O.pts,S),O.dts=Le(O.dts,S),O.dts<n[w>0?w-1:w].dts&&(T=!0)}T&&n.sort(function(w,O){const j=w.dts-O.dts,ee=w.pts-O.pts;return j||ee}),g=n[0].dts,y=n[n.length-1].dts;const v=y-g,x=v?Math.round(v/(c-1)):f||e.inputTimeScale/30;if(s){const w=g-S,O=w>x,j=w<-1;if((O||j)&&(O?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Lt(w,!0)} ms (${w}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Lt(-w,!0)} ms (${w}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||S>=n[0].pts||gt)){g=S;const ee=n[0].pts-w;if(O)n[0].dts=g,n[0].pts=ee;else{let X=!0;for(let Z=0;Z<n.length&&!(n[Z].dts>ee&&X);Z++){const pe=n[Z].pts;if(n[Z].dts-=w,n[Z].pts-=w,Z<n.length-1){const me=n[Z+1].pts,be=n[Z].pts,Fe=me<=be,tt=me<=pe;X=Fe==tt}}}this.log(`Video: Initial PTS/DTS adjusted: ${Lt(ee,!0)}/${Lt(g,!0)}, delta: ${Lt(w,!0)} ms`)}}g=Math.max(0,g);let D=0,A=0,_=g;for(let w=0;w<c;w++){const O=n[w],j=O.units,ee=j.length;let X=0;for(let Z=0;Z<ee;Z++)X+=j[Z].data.length;A+=X,D+=ee,O.length=X,O.dts<_?(O.dts=_,_+=x/4|0||1):_=O.dts,p=Math.min(O.pts,p),E=Math.max(O.pts,E)}y=n[c-1].dts;const b=A+4*D+8;let I;try{I=new Uint8Array(b)}catch(w){this.observer.emit(m.ERROR,m.ERROR,{type:V.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:b,reason:`fail allocating video mdat ${b}`});return}const P=new DataView(I.buffer);P.setUint32(0,b),I.set(L.types.mdat,4);let F=!1,U=Number.POSITIVE_INFINITY,H=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let w=0;w<c;w++){const O=n[w],j=O.units;let ee=0;for(let pe=0,me=j.length;pe<me;pe++){const be=j[pe],Fe=be.data,tt=be.data.byteLength;P.setUint32(d,tt),d+=4,I.set(Fe,d),d+=tt,ee+=4+tt}let X;if(w<c-1)f=n[w+1].dts-O.dts,X=n[w+1].pts-O.pts;else{const pe=this.config,me=w>0?O.dts-n[w-1].dts:x;if(X=w>0?O.pts-n[w-1].pts:x,pe.stretchShortVideoTrack&&this.nextAudioTs!==null){const be=Math.floor(pe.maxBufferHole*r),Fe=(i?p+i*r:this.nextAudioTs+h)-O.pts;Fe>be?(f=Fe-me,f<0?f=me:F=!0,this.log(`It is approximately ${Fe/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=me}else f=me}const Z=Math.round(O.pts-O.dts);U=Math.min(U,f),$=Math.max($,f),H=Math.min(H,X),k=Math.max(k,X),o.push(Nr(O.key,f,ee,Z))}if(o.length){if(gt){if(gt<70){const w=o[0].flags;w.dependsOn=2,w.isNonSync=0}}else if(Bs&&k-H<$-U&&x/$<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let w=g;for(let O=0,j=o.length;O<j;O++){const ee=w+o[O].duration,X=w+o[O].cts;if(O<j-1){const Z=ee+o[O+1].cts;o[O].duration=Z-X}else o[O].duration=O?o[O-1].duration:x;o[O].cts=0,w=ee}}}f=F||!f?x:f;const G=y+f;this.nextVideoTs=u=G-h,this.videoSampleDuration=f,this.isVideoContiguous=!0;const Y={data1:L.moof(e.sequenceNumber++,g,ie(e,{samples:o})),data2:I,startPTS:(p-h)/r,endPTS:(E+f-h)/r,startDTS:(g-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Rc;case"ac3":return bc;default:return Lc}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,c=n/o,l=this.getSamplesPerFrame(e),h=l*c,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let y=e.samples,p=d?0:8,E=this.nextAudioTs||-1;const T=u.baseTime*n/u.timescale,S=T+t*n;if(this.isAudioContiguous=s=s||y.length&&E>0&&(i&&Math.abs(S-(E+T))<9e3||Math.abs(Le(y[0].pts,S)-(E+T))<20*h),y.forEach(function(k){k.pts=Le(k.pts,S)}),!s||E<0){const k=y.length;if(y=y.filter(G=>G.pts>=0),k!==y.length&&this.warn(`Removed ${y.length-k} of ${k} samples (initPTS ${T} / ${n})`),!y.length)return;r===0?E=0:i&&!g?E=Math.max(0,S-T):E=y[0].pts-T}if(e.segmentCodec==="aac"){const k=this.config.maxAudioFramesDrift;for(let G=0,N=E+T;G<y.length;G++){const K=y[G],Y=K.pts,w=Y-N,O=Math.abs(1e3*w/n);if(w<=-k*h&&g)G===0&&(this.warn(`Audio frame @ ${(Y/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*w/n)} ms.`),this.nextAudioTs=E=Y-T,N=Y);else if(w>=k*h&&O<Ic&&g){let j=Math.round(w/h);for(N=Y-j*h;N<0&&j&&h;)j--,N+=h;G===0&&(this.nextAudioTs=E=N-T),this.warn(`Injecting ${j} audio frames @ ${((N-T)/n).toFixed(3)}s due to ${Math.round(1e3*w/n)} ms gap.`);for(let ee=0;ee<j;ee++){let X=vc.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);X||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),X=K.unit.subarray()),y.splice(G,0,{unit:X,pts:N}),N+=h,G++}}K.pts=N,N+=h}}let v=null,x=null,D,A=0,_=y.length;for(;_--;)A+=y[_].unit.byteLength;for(let k=0,G=y.length;k<G;k++){const N=y[k],K=N.unit;let Y=N.pts;if(x!==null){const O=f[k-1];O.duration=Math.round((Y-x)/c)}else if(s&&e.segmentCodec==="aac"&&(Y=E+T),v=Y,A>0){A+=p;try{D=new Uint8Array(A)}catch(O){this.observer.emit(m.ERROR,m.ERROR,{type:V.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(D.buffer).setUint32(0,A),D.set(L.types.mdat,4))}else return;D.set(K,p);const w=K.byteLength;p+=w,f.push(Nr(!0,l,w,0)),x=Y}const b=f.length;if(!b)return;const I=f[f.length-1];E=x-T,this.nextAudioTs=E+c*I.duration;const P=d?new Uint8Array(0):L.moof(e.sequenceNumber++,v/c,ie({},e,{samples:f}));e.samples=[];const F=(v-T)/n,U=E/n,$={data1:P,data2:D,startPTS:F,endPTS:U,startDTS:F,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,$}}function Le(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function _c(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function ua(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const c=a.samples[o];c.pts=Le(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=Le(c.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function da(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=Le(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class Dc extends Ce{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=yn(e);if(t)To(e,t);else{const c=r||n;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=Br(r,re.AUDIO,this)),n&&(i=Br(n,re.VIDEO,this));const o={};r&&n?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?o.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n){var o,c;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};M(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const y=vo(d,g,this),p=g.audio?y[g.audio.id]:null,E=g.video?y[g.video.id]:null,T=Yt(E,1/0),S=Yt(p,1/0),v=Yt(E,0,!0),x=Yt(p,0,!0);let D=r,A=0;const _=p&&(!E||!l&&S<T||l&&l.trackId===g.audio.id),b=_?p:E;if(b){const N=b.timescale,K=b.start-r*N,Y=_?g.audio.id:g.video.id;D=b.start/N,A=_?x-S:v-T,(n||!l)&&(Cc(l,D,r,A)||N!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${K/N} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${D-r} (${K}/${N}) trackId: ${Y}`),l=null,f.initPTS=K,f.timescale=N,f.trackId=Y)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const I=D-l.baseTime/l.timescale,P=I+A;A>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const F=!!g.audio,U=!!g.video;let H="";F&&(H+="audio"),U&&(H+="video");const $=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),k={data1:d,startPTS:I,startDTS:I,endPTS:P,endDTS:P,type:H,hasAudio:F,hasVideo:U,nb:1,dropped:0,encrypted:$};u.audio=F&&!U?k:void 0,u.video=U?k:void 0;const G=E?.sampleCount;if(G){const N=E.keyFrameIndex,K=N!==-1;k.nb=G,k.dropped=N===0||this.isVideoContiguous?0:K?N:G,k.independent=K,k.firstKeyFrame=N,K&&E.keyFrameStart&&(k.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),k.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${N}/${G} dropped: ${k.dropped} start: ${k.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=ua(s,r,l,l),i.samples.length&&(u.text=da(i,r,l)),u}}function Yt(a,e,t=!1){return a?.start!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function Cc(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function Br(a,e,t){const s=a.codec;return s&&s.length>4?s:e===re.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?cs(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let We;try{We=self.performance.now.bind(self.performance)}catch{We=Date.now}const rs=[{demux:mc,remux:Dc},{demux:Ze,remux:is},{demux:uc,remux:is},{demux:fc,remux:is}];rs.splice(2,0,{demux:dc,remux:is});class Ur{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=We();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:y,videoCodec:p,defaultInitPts:E,duration:T,initSegmentData:S}=c,v=Pc(n,t);if(v&&Et(v.method)){const _=this.getDecrypter(),b=bi(v.method);if(_.isSync()){let I=_.softwareDecrypt(n,v.key.buffer,v.iv.buffer,b);if(s.part>-1){const F=_.flush();I=F&&F.buffer}if(!I)return r.executeEnd=We(),Us(s);n=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=_.webCryptoDecrypt(n,v.key.buffer,v.iv.buffer,b).then(I=>{const P=this.push(I,null,s);return this.decryptionPromise=null,P}),this.decryptionPromise}const x=this.needsProbing(h,u);if(x){const _=this.configureTransmuxer(n);if(_)return this.logger.warn(`[transmuxer] ${_.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:_,reason:_.message}),r.executeEnd=We(),Us(s)}(h||u||g||x)&&this.resetInitSegment(S,y,p,T,t),(h||g||x)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const D=this.transmux(n,v,f,d,s);this.asyncResult=Ft(D);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=We(),D}flush(e){const t=e.transmuxing;t.executeStart=We();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&n.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=We();const u=[Us(e)];return this.asyncResult?Promise.resolve(u):u}const h=c.flush(o);return Ft(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(n,u,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===B.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=We()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let u=0,d=rs.length;u<d;u++){var n;if((n=rs[u].demux)!=null&&n.probe(e,this.logger)){r=rs[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Li(this.config)),e}}function Pc(a,e){let t=null;return a.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Us=a=>({remuxResult:{},chunkMeta:a});function Ft(a){return"then"in a&&a.then instanceof Function}class kc{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class wc{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let $r=0;class fa{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=$r++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new Ci,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=sr(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||Nl()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Ul(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Bl());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ne(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Ur(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Ur(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=$r++;const t=this.hls.config,s=sr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ne(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),$l(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,o,c,l,h){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,y=n?n.start:r.start,p=r.decryptdata,E=this.frag,T=!(E&&r.cc===E.cc),S=!(E&&l.level===E.level),v=E?l.sn-E.sn:-1,x=this.part?l.part-this.part.index:-1,D=v===0&&l.id>1&&l.id===E?.stats.chunkCount,A=!S&&(v===1||v===0&&(x===1||D&&x<=0)),_=self.performance.now();(S||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=_),n&&(x||!A)&&(n.stats.parsing.start=_);const b=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),I=new wc(T,A,c,S,y,b);if(!A||T||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===B.MAIN?"level":"track"}: ${l.level} id: ${l.id}
|
|
16
|
+
${t.m3u8}`)}function Gn(a,e,t=!0){const s=e.startSN+e.skippedSegments-a.startSN,i=a.fragments,r=s>=0;let n=0;if(r&&s<i.length)n=i[s].start;else if(r&&e.startSN===a.endSN+1)n=a.fragmentEnd;else if(r&&t)n=a.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)n=a.fragmentStart;else return;oi(e,n)}function oi(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function Kn(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Vn(a,e,t){if(!a)return null;let s=a.fragments[e-a.startSN];return s||(s=a.fragmentHint,s&&s.sn===e)?s:e<a.startSN&&t&&t.sn===e?t:null}function Cr(a,e,t){return a?Hn(a.partList,e,t):null}function Hn(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Yn(a){a.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function Cl(a,e){return a!==e&&e?Pr(a)!==Pr(e):!1}function Pr(a){return a.replace(/\?[^?]*$/,"")}function _t(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function Pl(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function kr(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function Wn(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)kr(t[s],a);e.fragmentHint&&kr(e.fragmentHint,a),e.alignedSliding=!0}function kl(a,e){a&&(qn(e,a),e.alignedSliding||ps(e,a),!e.alignedSliding&&!e.skippedSegments&&Gn(a,e,!1))}function qn(a,e){if(!Pl(e,a))return;const t=Math.min(e.endCC,a.endCC),s=_t(e.fragments,t),i=_t(a.fragments,t);if(!s||!i)return;se.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;Wn(r,a)}function ps(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=_t(s,n),r=_t(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=_t(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);Wn(l,a)}function Te(a,e,t){Ae(a,e,t),a.addEventListener(e,t)}function Ae(a,e,t){a.removeEventListener(e,t)}const wl={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},C={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class xs extends wn{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,u=c?c.currentTime:0,d=q.bufferInfo(l||c,u,n.maxBufferHole),f=!d.len;if(this.log(`Media seeking to ${M(u)?u.toFixed(3):u}, state: ${h}, ${f?"out of":"in"} buffer`),this.state===C.ENDED)this.resetLoadingState();else if(o){const g=n.maxFragLookUpTolerance,y=o.start-g,p=o.start+o.duration+g;if(f||p<d.start||y>d.end){const E=u>p;(u<y||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(u>g&&(this.lastCurrentTime=u),!this.loadingParts){const y=Math.max(d.end,u),p=this.shouldLoadParts(this.getLevelDetails(),y);p&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${y.toFixed(2)}`),this.loadingParts=p)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===C.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new ll(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Li(e.config)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=q.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return q.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Te(s,"seeking",this.onMediaSeeking),Te(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ae(i,"seeking",this.onMediaSeeking),Ae(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=C.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,o=r.frag;if(this.fragContextChanged(o)){(n===C.FRAG_LOADING||!this.fragCurrent&&n===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===de.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===de.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,o=r.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&Et(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,bi(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==C.STOPPED&&(this.state=C.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(o.message),!n||n.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?wl.toString(q.getBuffered(s)):"(detached)"})`),ce(e)){var i;if(e.type!==B.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=C.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=C.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(c=>!c),o=new vs(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===C.KEY_LOADING&&(this.state=C.IDLE),d}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(ce(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c?.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&ce(e)){const d=n.partList;if(d&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const f=this.getNextPart(d,e,s);if(f>-1){const g=d[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${d.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=C.FRAG_LOADING;let y;return o?y=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(p=>this.handleFragLoadError(p)):y=this.doFragPartsLoad(e,g,t,i).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):y}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(ce(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),M(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;const h=this.config.progressive;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([d])=>(!h&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{c[u.index]=d;const f=d.part;this.hls.trigger(m.FRAG_LOADED,d);const g=Cr(s.details,e.sn,u.index+1)||Hn(l,e.sn,u.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:c})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===V.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===B.SUBTITLE)return!1;const n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=n>-1?Cr(c,r,n):null,h=l?l.fragment:Vn(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==C.PARSING)return;const{data1:n,data2:o}=e;let c=n;if(o&&(c=De(n,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=q.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!M(i))return null;const n=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}getFwdBufferInfoAtPos(e,t,s,i){const r=q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(r.nextStart,n.end)-t,i);return q.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=B.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,f=this.hls.liveSyncPosition,g=c?(d!==-1&&d>=n?d:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=n&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const u=c.sn-t.startSN;h=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===de.OK||s===de.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=n.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(wr(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(wr(this.config)&&e.type!==B.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s?.playerQueue;if(r)for(let n=r.length;n--;){const o=r[n].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Qo(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Dn(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&c);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(n=n.concat(c),o=c.sn);let d;if(e<t){var f;const y=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;d=ct(r,n,e,y)}else d=n[n.length-1];if(d){const g=d.sn-s.startSN,y=this.fragmentTracker.getState(d);if((y===de.OK||y===de.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!s.live)&&d.level===r.level){const E=n[g+1];d.sn<o&&this.fragmentTracker.getState(E)!==de.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,o=e.alignedSliding&&M(r);if(n||!o&&!r){kl(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&M(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ce(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===R.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=C.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&c===ue.RetryRequest,g=d&&!o.resolved&&l===ve.MoveAllAlternatesMatchingHost,y=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&ce(i)&&!i.endList&&y&&!Pn(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var p;const E=ii((p=t.response)==null?void 0:p.code),T=Ii(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=C.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${T}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!n&&c!==ue.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===ue.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!ii(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=C.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===B.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const d=i?0:$n(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;if(s.fragmentError===0&&this.treatAsGap(e,s),((o=this.transmuxer)==null?void 0:o.error)===null){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===B.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function wr(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class jn{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Ol(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Ol(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}var Fs={exports:{}},Or;function Fl(){return Or||(Or=1,function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,u||c,d),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function n(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,u;if(this._eventsCount===0)return l;for(u in h=this._events)e.call(h,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},o.prototype.listenerCount=function(l){var h=t?t+l:l,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,h,u,d,f,g){var y=t?t+l:l;if(!this._events[y])return!1;var p=this._events[y],E=arguments.length,T,S;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),E){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,h),!0;case 3:return p.fn.call(p.context,h,u),!0;case 4:return p.fn.call(p.context,h,u,d),!0;case 5:return p.fn.call(p.context,h,u,d,f),!0;case 6:return p.fn.call(p.context,h,u,d,f,g),!0}for(S=1,T=new Array(E-1);S<E;S++)T[S-1]=arguments[S];p.fn.apply(p.context,T)}else{var v=p.length,x;for(S=0;S<v;S++)switch(p[S].once&&this.removeListener(l,p[S].fn,void 0,!0),E){case 1:p[S].fn.call(p[S].context);break;case 2:p[S].fn.call(p[S].context,h);break;case 3:p[S].fn.call(p[S].context,h,u);break;case 4:p[S].fn.call(p[S].context,h,u,d);break;default:if(!T)for(x=1,T=new Array(E-1);x<E;x++)T[x-1]=arguments[x];p[S].fn.apply(p[S].context,T)}}return!0},o.prototype.on=function(l,h,u){return r(this,l,h,u,!1)},o.prototype.once=function(l,h,u){return r(this,l,h,u,!0)},o.prototype.removeListener=function(l,h,u,d){var f=t?t+l:l;if(!this._events[f])return this;if(!h)return n(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!d||g.once)&&(!u||g.context===u)&&n(this,f);else{for(var y=0,p=[],E=g.length;y<E;y++)(g[y].fn!==h||d&&!g[y].once||u&&g[y].context!==u)&&p.push(g[y]);p.length?this._events[f]=p.length===1?p[0]:p:n(this,f)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o}(Fs)),Fs.exports}var Ml=Fl(),Ci=ho(Ml);const wt="1.6.14",xt={};function Nl(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Bl(){const a=xt[wt];if(a)return a.clientCount++,a;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return xt[wt]=i,i}function Ul(a){const e=xt[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return xt[a]=i,i}function $l(a){const e=xt[a||wt];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete xt[a||wt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Xn(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Pi(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function As(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function Ot(a,e){const t=e;let s=0;for(;Pi(a,e);){s+=10;const i=As(a,e+6);s+=i,Xn(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function Gl(a,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],n=r>>2&15;if(n>12){const f=new Error(`invalid ADTS sampling index:${n}`);a.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[n];let u=n;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return se.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${n})`),{config:d,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function zn(a,e){return a[e]===255&&(a[e+1]&246)===240}function Qn(a,e){return a[e+1]&1?7:9}function ki(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function Kl(a,e){return e+5<a.length}function ys(a,e){return e+1<a.length&&zn(a,e)}function Vl(a,e){return Kl(a,e)&&zn(a,e)&&ki(a,e)<=a.length-e}function Hl(a,e){if(ys(a,e)){const t=Qn(a,e);if(e+t>=a.length)return!1;const s=ki(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||ys(a,i)}return!1}function Zn(a,e,t,s,i){if(!a.samplerate){const r=Gl(e,t,s,i);if(!r)return;ie(a,r)}}function Jn(a){return 1024*9e4/a}function Yl(a,e){const t=Qn(a,e);if(e+t<=a.length){const s=ki(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function ea(a,e,t,s,i){const r=Jn(a.samplerate),n=s+i*r,o=Yl(e,t);let c;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+f);const y={unit:c,pts:n};return g||a.samples.push(y),{sample:y,length:f,missing:g}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:n},length:l,missing:-1}}function Wl(a,e){return Pi(a,e)&&As(a,e+6)+10<=a.length-e}function ql(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function Ms(a,e=0,t=1/0){return jl(a,e,t,Uint8Array)}function jl(a,e,t,s){const i=Xl(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=zl(a)?a.byteOffset:0,o=(n+a.byteLength)/r,c=(n+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function Xl(a){return a instanceof ArrayBuffer?a:a.buffer}function zl(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function Ql(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=a.data.subarray(1).indexOf(0);if(s===-1)return;const i=Re(Ms(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=Re(Ms(a.data,3+s,n));let c;return i==="-->"?c=Re(Ms(a.data,4+s+n)):c=ql(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Zl(a){if(a.size<2)return;const e=Re(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function Jl(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=Re(a.data.subarray(t),!0);t+=s.length+1;const i=Re(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Re(a.data.subarray(1));return{key:a.type,info:"",data:e}}function ec(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=Re(a.data.subarray(t),!0);t+=s.length+1;const i=Re(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Re(a.data);return{key:a.type,info:"",data:e}}function tc(a){return a.type==="PRIV"?Zl(a):a.type[0]==="W"?ec(a):a.type==="APIC"?Ql(a):Jl(a)}function sc(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=As(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const Vt=10,ic=10;function ta(a){let e=0;const t=[];for(;Pi(a,e);){const s=As(a,e+6);a[e+5]>>6&1&&(e+=Vt),e+=Vt;const i=e+s;for(;e+ic<i;){const r=sc(a.subarray(e)),n=tc(r);n&&t.push(n),e+=r.size+Vt}Xn(a,e)&&(e+=Vt)}return t}function sa(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function rc(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function wi(a){const e=ta(a);for(let t=0;t<e.length;t++){const s=e[t];if(sa(s))return rc(s)}}let xe=function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a}({});function Ue(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Oi{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=De(this.cachedData,e),this.cachedData=null);let s=Ot(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,c=s?wi(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&M(c))&&(this.basePTS=nc(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:xe.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else Wl(e,i)?(s=Ot(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:xe.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=De(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:Ue(),id3Track:o,textTrack:Ue()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ue(),id3Track:this._id3Track,textTrack:Ue()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const nc=(a,e,t)=>{if(M(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let Ht=null;const ac=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],oc=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],lc=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cc=[0,1,1,4];function ia(a,e,t,s,i){if(t+24>e.length)return;const r=ra(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function ra(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,c=t===3?3-s:s===3?3:4,l=ac[c*14+i-1]*1e3,u=oc[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=lc[t][s],g=cc[s],y=f*8*g,p=Math.floor(f*l/u+n)*g;if(Ht===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ht=S?parseInt(S[1]):0}return!!Ht&&Ht<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:u,channelCount:d,frameLength:p,samplesPerFrame:y}}}function Fi(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function na(a,e){return e+1<a.length&&Fi(a,e)}function hc(a,e){return Fi(a,e)&&4<=a.length-e}function aa(a,e){if(e+1<a.length&&Fi(a,e)){const s=ra(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||na(a,r)}return!1}class uc extends Oi{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Ot(e,0);let i=s?.length||0;if(aa(e,i))return!1;for(let r=e.length;i<r;i++)if(Hl(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Vl(e,t)}appendFrame(e,t,s){Zn(e,this.observer,t,s,e.manifestCodec);const i=ea(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const oa=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(n[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class dc extends Oi{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=la(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Ot(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&wi(t)!==void 0&&oa(e,s)<16}}function la(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,y=[2,1,2,3,3,4,4,5][u]+f,p=e[t+5]>>3,E=e[t+5]&7,T=new Uint8Array([r<<6|p<<1|E>>2,(E&3)<<6|u<<3|f<<2|c>>4,c<<4&224]),S=1536/o*9e4,v=s+i*S,x=e.subarray(t,t+h);return a.config=T,a.channelCount=y,a.samplerate=o,a.samples.push({unit:x,pts:v}),h}class fc extends Oi{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Ot(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&wi(t)!==void 0&&oa(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(aa(e,s))return se.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return hc(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return ia(e,t,s,this.basePTS,this.frameIndex)}}const gc=/\/emsg[-/]ID3/i;class mc{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Ue("video",1),n=this.audioTrack=Ue("audio",1),o=this.txtTrack=Ue("text",1);if(this.id3Track=Ue("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=yn(e);if(c.video){const{id:l,timescale:h,codec:u,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(c.audio){const{id:l,timescale:h,codec:u}=c.audio;n.id=l,n.timescale=h,n.codec=u}o.id=gn.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return mo(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=De(this.remainderData,e));const o=xo(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Ji(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Ji(e,t),{videoTrack:t,audioTrack:Ue(),id3Track:i,textTrack:Ue()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=z(e.samples,["emsg"]);i&&i.forEach(r=>{const n=Io(r);if(gc.test(n.schemeIdUri)){const o=Fr(n,t);let c=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:xe.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Fr(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:xe.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function Fr(a,e){return M(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class pc{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Li(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,et.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=Sn(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(n,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}class ca{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,o=[];let c=0,l,h,u,d=-1,f=0;for(r===-1&&(d=0,f=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,d>=0){const g={data:t.subarray(d,h),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(n&&c<=4-n&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-n)),h>0&&(g.data=De(g.data,t.subarray(0,h)),g.state=0))}c<i?(u=this.getNALuType(t,c),d=c,f=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const g={data:t.subarray(d,i),type:f,state:r};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=De(g.data,t))}return e.naluState=r,o}}class Dt{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&se.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class yc extends ca{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 1:{let y=!1;o=!0;const p=l.data;if(c&&p.length>4){const E=this.readSliceType(p);(E===2||E===4||E===7||E===9)&&(y=!0)}if(y){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=y;break}case 5:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:{o=!0,vi(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const y=l.data,p=this.readSPS(y);if(!e.sps||e.width!==p.width||e.height!==p.height||((f=e.pixelRatio)==null?void 0:f[0])!==p.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[y];const E=y.subarray(1,4);let T="avc1.";for(let S=0;S<3;S++){let v=E[S].toString(16);v.length<2&&(v="0"+v),T+=v}e.codec=T}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Dt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new Dt(e);let s=0,i=0,r=0,n=0,o,c,l;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),y=t.skipEG.bind(t),p=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const T=h();if(u(5),g(3),h(),p(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){const _=d();if(_===3&&g(1),p(),p(),g(1),f())for(c=_!==3?8:12,l=0;l<c;l++)f()&&(l<6?E(16,t):E(64,t))}p();const S=d();if(S===0)d();else if(S===1)for(g(1),y(),y(),o=d(),l=0;l<o;l++)y();p(),g(1);const v=d(),x=d(),D=u(1);D===0&&g(1),g(1),f()&&(s=d(),i=d(),r=d(),n=d());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((v+1)*16-s*2-i*2),height:(2-D)*(x+1)*16-(D?2:4)*(r+n),pixelRatio:A}}}class Ec extends ca{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=n)!=null&&d.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:o=!0,vi(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ie(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=n)!=null&&u.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Dt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),y=t.readUByte(),p=t.readUByte(),E=t.readUByte(),T=[],S=[];for(let J=0;J<s;J++)T.push(t.readBoolean()),S.push(t.readBoolean());if(s>0)for(let J=s;J<8;J++)t.readBits(2);for(let J=0;J<s;J++)T[J]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[J]&&t.readUByte();t.readUEG();const v=t.readUEG();v==3&&t.skipBits(1);const x=t.readUEG(),D=t.readUEG(),A=t.readBoolean();let _=0,b=0,I=0,P=0;A&&(_+=t.readUEG(),b+=t.readUEG(),I+=t.readUEG(),P+=t.readUEG());const F=t.readUEG(),U=t.readUEG(),H=t.readUEG(),$=t.readBoolean();for(let J=$?0:s;J<=s;J++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let ye=0;ye<4;ye++)for(let _e=0;_e<(ye===3?2:6);_e++)if(!t.readBoolean())t.readUEG();else{const Pe=Math.min(64,1<<4+(ye<<1));ye>1&&t.readEG();for(let ht=0;ht<Pe;ht++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const N=t.readUEG();let K=0;for(let J=0;J<N;J++){let ye=!1;if(J!==0&&(ye=t.readBoolean()),ye){J===N&&t.readUEG(),t.readBoolean(),t.readUEG();let _e=0;for(let st=0;st<=K;st++){const Pe=t.readBoolean();let ht=!1;Pe||(ht=t.readBoolean()),(Pe||ht)&&_e++}K=_e}else{const _e=t.readUEG(),st=t.readUEG();K=_e+st;for(let Pe=0;Pe<_e;Pe++)t.readUEG(),t.readBoolean();for(let Pe=0;Pe<st;Pe++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const J=t.readUEG();for(let ye=0;ye<J;ye++){for(let _e=0;_e<H+4;_e++)t.readBits(1);t.readBits(1)}}let w=0,O=1,j=1,ee=!0,X=1,Z=0;t.readBoolean(),t.readBoolean();let pe=!1;if(t.readBoolean()){if(t.readBoolean()){const it=t.readUByte(),Vi=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Nt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];it>0&&it<16?(O=Vi[it-1],j=Nt[it-1]):it===255&&(O=t.readBits(16),j=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),pe=t.readBoolean(),pe&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(X=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Nt=t.readBoolean(),Hi=t.readBoolean();let At=!1;(Nt||Hi)&&(At=t.readBoolean(),At&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),At&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Yi=0;Yi<=s;Yi++){ee=t.readBoolean();const Ja=ee||t.readBoolean();let Wi=!1;Ja?t.readEG():Wi=t.readBoolean();const qi=Wi?1:t.readUEG()+1;if(Nt)for(let It=0;It<qi;It++)t.readUEG(),t.readUEG(),At&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Hi)for(let It=0;It<qi;It++)t.readUEG(),t.readUEG(),At&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),w=t.readUEG())}let be=x,Fe=D;if(A){let J=1,ye=1;v===1?J=ye=2:v==2&&(J=2),be=x-J*b-J*_,Fe=D-ye*P-ye*I}const tt=i?["A","B","C"][i]:"",Za=o<<24|c<<16|l<<8|h;let bs=0;for(let J=0;J<32;J++)bs=(bs|(Za>>J&1)<<31-J)>>>0;let _s=bs.toString(16);return n===1&&_s==="2"&&(_s="6"),{codecString:`hvc1.${tt}${n}.${_s}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[u,d,f,g,y,p],general_level_idc:E,bit_depth:F+8,bit_depth_luma_minus8:F,bit_depth_chroma_minus8:U,min_spatial_segmentation_idc:w,chroma_format_idc:v,frame_rate:{fixed:ee,fps:Z/X}},width:be,height:Fe,pixelRatio:[O,j]}}readPPS(e){const t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),r=t.readBoolean();let n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const fe=188;class Ze{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=Ze.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(fe*5,t-fe)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let c=i;c<t;c+=fe)if(e[c]===71&&(t-c===fe||e[c+fe]===71)){if(o++,n===-1&&(n=c,n!==0&&(s=Math.min(n+fe*99,e.length-fe)+1)),r||(r=li(e,c)===0),r&&o>1&&(n===0&&o>2||c+fe>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:gn[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ze.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Ze.createTrack("audio",i),this._id3Track=Ze.createTrack("id3"),this._txtTrack=Ze.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=n.pid,u=n.pesData,d=o.pid,f=c.pid,g=o.pesData,y=c.pesData,p=null,E=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(e=De(this.remainderData,e),S=e.length,this.remainderData=null),S<fe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};const v=Math.max(0,Ze.syncOffset(e));S-=(S-v)%fe,S<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let x=0;for(let A=v;A<S;A+=fe)if(e[A]===71){const _=!!(e[A+1]&64),b=li(e,A),I=(e[A+3]&48)>>4;let P;if(I>1){if(P=A+5+e[A+4],P===A+fe)continue}else P=A+4;switch(b){case h:_&&(u&&(r=ft(u,this.logger))&&(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(P,A+fe)),u.size+=A+fe-P);break;case d:if(_){if(g&&(r=ft(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(P,A+fe)),g.size+=A+fe-P);break;case f:_&&(y&&(r=ft(y,this.logger))&&this.parseID3PES(c,r),y={data:[],size:0}),y&&(y.data.push(e.subarray(P,A+fe)),y.size+=A+fe-P);break;case 0:_&&(P+=e[P]+1),T=this._pmtId=Tc(e,P);break;case T:{_&&(P+=e[P]+1);const F=Sc(e,P,this.typeSupported,s,this.observer,this.logger);h=F.videoPid,h>0&&(n.pid=h,n.segmentCodec=F.segmentVideoCodec),d=F.audioPid,d>0&&(o.pid=d,o.segmentCodec=F.segmentAudioCodec),f=F.id3Pid,f>0&&(c.pid=f),p!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${p}'. Backtracking to sync byte @${v} to parse all TS packets.`),p=null,A=v-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=b;break}}else x++;x>0&&ci(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=u,o.pesData=g,c.pesData=y;const D={audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(D),D}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,c=i.pesData;let l;if(n&&(l=ft(n,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,o&&(l=ft(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=ft(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new pc(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new yc:e==="hevc"&&(this.videoParser=new Ec))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=De(i.sample.unit,r);else{const f=d-u;i.sample.unit.set(r.subarray(0,u),f),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!ys(r,n);n++);if(n!==s){let u;const d=n<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${n}`:u="No ADTS header found in AAC PES",ci(this.observer,new Error(u),d,this.logger),!d)return}Zn(e,this.observer,r,n,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const u=Jn(e.samplerate);c=i.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;n<o;)if(h=ea(e,r,n,c,l),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;n<o-1&&!ys(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(na(s,n)){const c=ia(e,s,n,o,r);if(c)n+=c.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,c;for(;o<r&&(c=la(e,s,o,i,n++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ie({},t,{type:this._videoTrack?xe.emsg:xe.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function li(a,e){return((a[e+1]&31)<<8)+a[e+2]}function Tc(a,e){return(a[e+10]&31)<<8|a[e+11]}function Sc(a,e,t,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],c=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<c;){const h=li(a,e),u=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){Ns("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=h);break;case 21:n.id3Pid===-1&&(n.id3Pid=h);break;case 219:if(!s){Ns("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="mp3");break;case 193:if(!s){Ns("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&u>0){let d=e+5,f=u;for(;f>2;){switch(a[d]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=h,n.segmentAudioCodec="ac3");break}const y=a[d+1]+2;d+=y,f-=y}}break;case 194:case 135:return ci(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=h,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return n}function ci(a,e,t,s){s.warn(`parsing error: ${e.message}`),a.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Ns(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function ft(a,e){let t=0,s,i,r,n,o;const c=a.data;if(!a||a.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=De(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>a.size-6)return null;const h=s[7];h&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,n-o>60*9e4&&(e.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),r=s[8];let u=r+9;if(a.size<=u)return null;a.size-=u;const d=new Uint8Array(a.size);for(let f=0,g=c.length;f<g;f++){s=c[f];let y=s.byteLength;if(u)if(u>y){u-=y;continue}else s=s.subarray(u),y-=u,u=0;d.set(s,t),t+=y}return i&&(i-=r+3),{data:d,pts:n,dts:o,len:i}}return null}class vc{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Xe=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);L.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=r,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,n,c,n,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Xe+1)),i=Math.floor(t%(Xe+1));return L.box(L.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale||0,e.duration||0),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,s){return L.box(L.types.moof,L.mfhd(e),L.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(L.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Xe+1)),i=Math.floor(t%(Xe+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return L.box(L.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,s)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=L.box(L.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return L.box(L.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return L.box(L.types.mp4a,L.audioStsd(e),L.box(L.types.esds,L.esds(e)))}static mp3(e){return L.box(L.types[".mp3"],L.audioStsd(e))}static ac3(e){return L.box(L.types["ac-3"],L.audioStsd(e),L.box(L.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return L.box(L.types.stsd,L.STSD,L.mp4a(e));if(t==="ac3"&&e.config)return L.box(L.types.stsd,L.STSD,L.ac3(e));if(t==="mp3"&&e.codec==="mp3")return L.box(L.types.stsd,L.STSD,L.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return L.box(L.types.stsd,L.STSD,L.avc1(e));if(t==="hevc"&&e.vps)return L.box(L.types.stsd,L.STSD,L.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(Xe+1)),o=Math.floor(s%(Xe+1));return L.box(L.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=L.sdtp(e),i=e.id,r=Math.floor(t/(Xe+1)),n=Math.floor(t%(Xe+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),L.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,c,l,h,u,d;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,u=c.flags,d=c.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return L.box(L.types.trun,n)}static initSegment(e){L.types||L.init();const t=L.moov(e);return De(L.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let g=0;g<s.length;g+=1){n+=3;for(let y=0;y<s[g].length;y+=1)n+=2+s[g][y].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const c=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,s[g].length]),n),n+=3;for(let y=0;y<s[g].length;y+=1)o.set(new Uint8Array([s[g][y].length>>8,s[g][y].length&255]),n),n+=2,o.set(s[g][y],n),n+=s[g][y].length}const l=L.box(L.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return L.box(L.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}L.types=void 0;L.HDLR_TYPES=void 0;L.STTS=void 0;L.STSC=void 0;L.STCO=void 0;L.STSZ=void 0;L.VMHD=void 0;L.SMHD=void 0;L.STSD=void 0;L.FTYP=void 0;L.DINF=void 0;const ha=9e4;function Mi(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function xc(a,e,t=1,s=!1){return Mi(a,e,1/t,s)}function Lt(a,e=!1){return Mi(a,1e3,1/ha,e)}function Ac(a,e=1){return Mi(a,ha,1/e)}function Mr(a){const{baseTime:e,timescale:t,trackId:s}=a;return`${e/t} (${e}/${t}) trackId: ${s}`}const Ic=10*1e3,Lc=1024,Rc=1152,bc=1536;let gt=null,Bs=null;function Nr(a,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class is extends Ce{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,gt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);gt=n?parseInt(n[1]):0}if(Bs===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Bs=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Mr(t)} > ${e&&Mr(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,n)=>{let o=n.pts,c=o-r;return c<-4294967296&&(t=!0,o=Le(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,o,c){let l,h,u,d,f,g,y=r,p=r;const E=e.pid>-1,T=t.pid>-1,S=t.samples.length,v=e.samples.length>0,x=o&&S>0||S>1;if((!E||v)&&(!T||x)||this.ISGenerated||o){if(this.ISGenerated){var A,_,b,I;const H=this.videoTrackConfig;(H&&(t.width!==H.width||t.height!==H.height||((A=t.pixelRatio)==null?void 0:A[0])!==((_=H.pixelRatio)==null?void 0:_[0])||((b=t.pixelRatio)==null?void 0:b[1])!==((I=H.pixelRatio)==null?void 0:I[1]))||!H&&x||this.nextAudioTs===null&&v)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,n));const P=this.isVideoContiguous;let F=-1,U;if(x&&(F=_c(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,F>0){this.warn(`Dropped ${F} out of ${S} video samples due to a missing keyframe`);const H=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(F),t.dropped+=F,p+=(t.samples[0].pts-H)/t.inputTimeScale,U=p}else F===-1&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(v&&x){const H=this.getVideoStartPts(t.samples),k=(Le(e.samples[0].pts,H)-H)/t.inputTimeScale;y+=Math.max(0,k),p+=Math.max(0,-k)}if(v){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,y,this.isAudioContiguous,n,T||x||c===B.AUDIO?p:void 0),x){const H=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,p,P,H)}}else x&&(l=this.remuxVideo(t,p,P,0));l&&(l.firstKeyFrame=F,l.independent=F!==-1,l.firstKeyFramePTS=U)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=ua(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=da(i,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:g,text:d,id3:f}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Le(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,u="audio/mp4",d,f,g,y=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(y=e.id,g=e.inputTimeScale,!l||g!==l.timescale?d=f=this.computeInitPts(r[0].pts,g,s,"audio"):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(y=t.id,g=t.inputTimeScale,!l||g!==l.timescale){const p=this.getVideoStartPts(n),E=Le(n[0].dts,p),T=this.computeInitPts(E,g,s,"video"),S=this.computeInitPts(p,g,s,"video");f=Math.min(f,T),d=Math.min(d,S)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${y}`),this._initPTS={baseTime:d,timescale:g,trackId:y},this._initDTS={baseTime:f,timescale:g,trackId:y}):d=g=void 0,{tracks:c,initPTS:d,timescale:g,trackId:y}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],c=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let u=this.nextVideoTs,d=8,f=this.videoSampleDuration,g,y,p=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!s||u===null){const w=h+t*r,O=n[0].pts-Le(n[0].dts,n[0].pts);gt&&u!==null&&Math.abs(w-O-(u+h))<15e3?s=!0:u=w-O-h}const S=u+h;for(let w=0;w<c;w++){const O=n[w];O.pts=Le(O.pts,S),O.dts=Le(O.dts,S),O.dts<n[w>0?w-1:w].dts&&(T=!0)}T&&n.sort(function(w,O){const j=w.dts-O.dts,ee=w.pts-O.pts;return j||ee}),g=n[0].dts,y=n[n.length-1].dts;const v=y-g,x=v?Math.round(v/(c-1)):f||e.inputTimeScale/30;if(s){const w=g-S,O=w>x,j=w<-1;if((O||j)&&(O?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Lt(w,!0)} ms (${w}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Lt(-w,!0)} ms (${w}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||S>=n[0].pts||gt)){g=S;const ee=n[0].pts-w;if(O)n[0].dts=g,n[0].pts=ee;else{let X=!0;for(let Z=0;Z<n.length&&!(n[Z].dts>ee&&X);Z++){const pe=n[Z].pts;if(n[Z].dts-=w,n[Z].pts-=w,Z<n.length-1){const me=n[Z+1].pts,be=n[Z].pts,Fe=me<=be,tt=me<=pe;X=Fe==tt}}}this.log(`Video: Initial PTS/DTS adjusted: ${Lt(ee,!0)}/${Lt(g,!0)}, delta: ${Lt(w,!0)} ms`)}}g=Math.max(0,g);let D=0,A=0,_=g;for(let w=0;w<c;w++){const O=n[w],j=O.units,ee=j.length;let X=0;for(let Z=0;Z<ee;Z++)X+=j[Z].data.length;A+=X,D+=ee,O.length=X,O.dts<_?(O.dts=_,_+=x/4|0||1):_=O.dts,p=Math.min(O.pts,p),E=Math.max(O.pts,E)}y=n[c-1].dts;const b=A+4*D+8;let I;try{I=new Uint8Array(b)}catch(w){this.observer.emit(m.ERROR,m.ERROR,{type:V.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:b,reason:`fail allocating video mdat ${b}`});return}const P=new DataView(I.buffer);P.setUint32(0,b),I.set(L.types.mdat,4);let F=!1,U=Number.POSITIVE_INFINITY,H=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let w=0;w<c;w++){const O=n[w],j=O.units;let ee=0;for(let pe=0,me=j.length;pe<me;pe++){const be=j[pe],Fe=be.data,tt=be.data.byteLength;P.setUint32(d,tt),d+=4,I.set(Fe,d),d+=tt,ee+=4+tt}let X;if(w<c-1)f=n[w+1].dts-O.dts,X=n[w+1].pts-O.pts;else{const pe=this.config,me=w>0?O.dts-n[w-1].dts:x;if(X=w>0?O.pts-n[w-1].pts:x,pe.stretchShortVideoTrack&&this.nextAudioTs!==null){const be=Math.floor(pe.maxBufferHole*r),Fe=(i?p+i*r:this.nextAudioTs+h)-O.pts;Fe>be?(f=Fe-me,f<0?f=me:F=!0,this.log(`It is approximately ${Fe/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=me}else f=me}const Z=Math.round(O.pts-O.dts);U=Math.min(U,f),$=Math.max($,f),H=Math.min(H,X),k=Math.max(k,X),o.push(Nr(O.key,f,ee,Z))}if(o.length){if(gt){if(gt<70){const w=o[0].flags;w.dependsOn=2,w.isNonSync=0}}else if(Bs&&k-H<$-U&&x/$<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let w=g;for(let O=0,j=o.length;O<j;O++){const ee=w+o[O].duration,X=w+o[O].cts;if(O<j-1){const Z=ee+o[O+1].cts;o[O].duration=Z-X}else o[O].duration=O?o[O-1].duration:x;o[O].cts=0,w=ee}}}f=F||!f?x:f;const G=y+f;this.nextVideoTs=u=G-h,this.videoSampleDuration=f,this.isVideoContiguous=!0;const Y={data1:L.moof(e.sequenceNumber++,g,ie(e,{samples:o})),data2:I,startPTS:(p-h)/r,endPTS:(E+f-h)/r,startDTS:(g-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Rc;case"ac3":return bc;default:return Lc}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,c=n/o,l=this.getSamplesPerFrame(e),h=l*c,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let y=e.samples,p=d?0:8,E=this.nextAudioTs||-1;const T=u.baseTime*n/u.timescale,S=T+t*n;if(this.isAudioContiguous=s=s||y.length&&E>0&&(i&&Math.abs(S-(E+T))<9e3||Math.abs(Le(y[0].pts,S)-(E+T))<20*h),y.forEach(function(k){k.pts=Le(k.pts,S)}),!s||E<0){const k=y.length;if(y=y.filter(G=>G.pts>=0),k!==y.length&&this.warn(`Removed ${y.length-k} of ${k} samples (initPTS ${T} / ${n})`),!y.length)return;r===0?E=0:i&&!g?E=Math.max(0,S-T):E=y[0].pts-T}if(e.segmentCodec==="aac"){const k=this.config.maxAudioFramesDrift;for(let G=0,N=E+T;G<y.length;G++){const K=y[G],Y=K.pts,w=Y-N,O=Math.abs(1e3*w/n);if(w<=-k*h&&g)G===0&&(this.warn(`Audio frame @ ${(Y/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*w/n)} ms.`),this.nextAudioTs=E=Y-T,N=Y);else if(w>=k*h&&O<Ic&&g){let j=Math.round(w/h);for(N=Y-j*h;N<0&&j&&h;)j--,N+=h;G===0&&(this.nextAudioTs=E=N-T),this.warn(`Injecting ${j} audio frames @ ${((N-T)/n).toFixed(3)}s due to ${Math.round(1e3*w/n)} ms gap.`);for(let ee=0;ee<j;ee++){let X=vc.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);X||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),X=K.unit.subarray()),y.splice(G,0,{unit:X,pts:N}),N+=h,G++}}K.pts=N,N+=h}}let v=null,x=null,D,A=0,_=y.length;for(;_--;)A+=y[_].unit.byteLength;for(let k=0,G=y.length;k<G;k++){const N=y[k],K=N.unit;let Y=N.pts;if(x!==null){const O=f[k-1];O.duration=Math.round((Y-x)/c)}else if(s&&e.segmentCodec==="aac"&&(Y=E+T),v=Y,A>0){A+=p;try{D=new Uint8Array(A)}catch(O){this.observer.emit(m.ERROR,m.ERROR,{type:V.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(D.buffer).setUint32(0,A),D.set(L.types.mdat,4))}else return;D.set(K,p);const w=K.byteLength;p+=w,f.push(Nr(!0,l,w,0)),x=Y}const b=f.length;if(!b)return;const I=f[f.length-1];E=x-T,this.nextAudioTs=E+c*I.duration;const P=d?new Uint8Array(0):L.moof(e.sequenceNumber++,v/c,ie({},e,{samples:f}));e.samples=[];const F=(v-T)/n,U=E/n,$={data1:P,data2:D,startPTS:F,endPTS:U,startDTS:F,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,$}}function Le(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function _c(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function ua(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const c=a.samples[o];c.pts=Le(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=Le(c.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function da(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=Le(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class Dc extends Ce{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=yn(e);if(t)To(e,t);else{const c=r||n;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=Br(r,re.AUDIO,this)),n&&(i=Br(n,re.VIDEO,this));const o={};r&&n?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?o.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n){var o,c;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};M(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const y=vo(d,g,this),p=g.audio?y[g.audio.id]:null,E=g.video?y[g.video.id]:null,T=Yt(E,1/0),S=Yt(p,1/0),v=Yt(E,0,!0),x=Yt(p,0,!0);let D=r,A=0;const _=p&&(!E||!l&&S<T||l&&l.trackId===g.audio.id),b=_?p:E;if(b){const N=b.timescale,K=b.start-r*N,Y=_?g.audio.id:g.video.id;D=b.start/N,A=_?x-S:v-T,(n||!l)&&(Cc(l,D,r,A)||N!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${K/N} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${D-r} (${K}/${N}) trackId: ${Y}`),l=null,f.initPTS=K,f.timescale=N,f.trackId=Y)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const I=D-l.baseTime/l.timescale,P=I+A;A>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const F=!!g.audio,U=!!g.video;let H="";F&&(H+="audio"),U&&(H+="video");const $=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),k={data1:d,startPTS:I,startDTS:I,endPTS:P,endDTS:P,type:H,hasAudio:F,hasVideo:U,nb:1,dropped:0,encrypted:$};u.audio=F&&!U?k:void 0,u.video=U?k:void 0;const G=E?.sampleCount;if(G){const N=E.keyFrameIndex,K=N!==-1;k.nb=G,k.dropped=N===0||this.isVideoContiguous?0:K?N:G,k.independent=K,k.firstKeyFrame=N,K&&E.keyFrameStart&&(k.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),k.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${N}/${G} dropped: ${k.dropped} start: ${k.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=ua(s,r,l,l),i.samples.length&&(u.text=da(i,r,l)),u}}function Yt(a,e,t=!1){return a?.start!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function Cc(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function Br(a,e,t){const s=a.codec;return s&&s.length>4?s:e===re.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?cs(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let We;try{We=self.performance.now.bind(self.performance)}catch{We=Date.now}const rs=[{demux:mc,remux:Dc},{demux:Ze,remux:is},{demux:uc,remux:is},{demux:fc,remux:is}];rs.splice(2,0,{demux:dc,remux:is});class Ur{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=We();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:y,videoCodec:p,defaultInitPts:E,duration:T,initSegmentData:S}=c,v=Pc(n,t);if(v&&Et(v.method)){const _=this.getDecrypter(),b=bi(v.method);if(_.isSync()){let I=_.softwareDecrypt(n,v.key.buffer,v.iv.buffer,b);if(s.part>-1){const F=_.flush();I=F&&F.buffer}if(!I)return r.executeEnd=We(),Us(s);n=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=_.webCryptoDecrypt(n,v.key.buffer,v.iv.buffer,b).then(I=>{const P=this.push(I,null,s);return this.decryptionPromise=null,P}),this.decryptionPromise}const x=this.needsProbing(h,u);if(x){const _=this.configureTransmuxer(n);if(_)return this.logger.warn(`[transmuxer] ${_.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:_,reason:_.message}),r.executeEnd=We(),Us(s)}(h||u||g||x)&&this.resetInitSegment(S,y,p,T,t),(h||g||x)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const D=this.transmux(n,v,f,d,s);this.asyncResult=Ft(D);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=We(),D}flush(e){const t=e.transmuxing;t.executeStart=We();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&n.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=We();const u=[Us(e)];return this.asyncResult?Promise.resolve(u):u}const h=c.flush(o);return Ft(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(n,u,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===B.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=We()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let u=0,d=rs.length;u<d;u++){var n;if((n=rs[u].demux)!=null&&n.probe(e,this.logger)){r=rs[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Li(this.config)),e}}function Pc(a,e){let t=null;return a.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Us=a=>({remuxResult:{},chunkMeta:a});function Ft(a){return"then"in a&&a.then instanceof Function}class kc{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class wc{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let $r=0;class fa{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=$r++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new Ci,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=sr(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||Nl()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Ul(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Bl());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ne(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Ur(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Ur(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=$r++;const t=this.hls.config,s=sr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ne(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),$l(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,o,c,l,h){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,y=n?n.start:r.start,p=r.decryptdata,E=this.frag,T=!(E&&r.cc===E.cc),S=!(E&&l.level===E.level),v=E?l.sn-E.sn:-1,x=this.part?l.part-this.part.index:-1,D=v===0&&l.id>1&&l.id===E?.stats.chunkCount,A=!S&&(v===1||v===0&&(x===1||D&&x<=0)),_=self.performance.now();(S||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=_),n&&(x||!A)&&(n.stats.parsing.start=_);const b=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),I=new wc(T,A,c,S,y,b);if(!A||T||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===B.MAIN?"level":"track"}: ${l.level} id: ${l.id}
|
|
17
17
|
discontinuity: ${T}
|
|
18
18
|
trackSwitch: ${S}
|
|
19
19
|
contiguous: ${A}
|
|
@@ -24,8 +24,8 @@ ${this.list("video")}
|
|
|
24
24
|
${this.list("audio")}
|
|
25
25
|
${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const Kr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ya="HlsJsTrackRemovedError";class Fc extends Error{constructor(e){super(e),this.name=ya}}class Ea extends Ce{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=co(je(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?ie(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=ie({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=je(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&n instanceof c,Vr(s),Mc(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
26
26
|
required tracks: ${ne(s,(c,l)=>c==="initSegment"?void 0:l)};
|
|
27
|
-
transfer tracks: ${ne(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!hn(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,l?.fragments[0].start||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){const p=q.getBuffered(u);d.detectEvictedFragments(l,p,f,null,!0)}const g=$s(l),y=[l,u];this.sourceBuffers[g]=y,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Vr(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[$s(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Oc(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!n&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(n||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const u=t[c],{id:d,codec:f,levelCodec:g,container:y,metadata:p,supplemental:E}=u;let T=i[c];const S=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],v=S!=null&&S.buffer?S:T,x=v?.pendingCodec||v?.codec,D=v?.levelCodec;T||(T=i[c]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:y,levelCodec:g,metadata:p,id:d});const A=ts(x,D),_=A?.replace(Kr,"$1");let b=ts(f,g);const I=(h=b)==null?void 0:h.replace(Kr,"$1");b&&A&&_!==I&&(c.slice(0,5)==="audio"&&(b=cs(b,this.appendSource)),this.log(`switching codec ${x} to ${b}`),b!==(T.pendingCodec||T.codec)&&(T.pendingCodec=b),T.container=y,this.appendChangeType(c,y,b))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const n=this.tracks[e];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,B.MAIN))==null?void 0:t.gap)===!0)return;const n={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,B.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:o,part:c,chunkMeta:l,offset:h}=t,u=l.buffering[r],{sn:d,cc:f}=o,g=self.performance.now();u.start=g;const y=o.stats.buffering,p=c?c.stats.buffering:null;y.start===0&&(y.start=g),p&&p.start===0&&(p.start=g);const E=s.audio;let T=!1;r==="audio"&&E?.container==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=s.video,v=S?.buffer;if(v&&d!=="initSegment"){const A=c||o,_=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const I=A.start+A.duration*.05,P=v.buffered,F=this.currentOp("video");!P.length&&!F?this.blockAudio(A):!F&&!q.isBuffered(v,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(A)}else if(r==="video"){const b=A.end;if(_){const I=_.frag.start;(b>I||b<this.lastVideoAppendEnd||q.isBuffered(v,I))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}const x=(c||o).start,D={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const _=(A=this.tracks[r])==null?void 0:A.buffer;_&&(T?this.updateTimestampOffset(_,x,.1,r,d,f):h!==void 0&&M(h)&&this.updateTimestampOffset(_,h,1e-6,r,d,f)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,y.first===0&&(y.first=A),p&&p.first===0&&(p.first=A);const _={};this.sourceBuffers.forEach(([b,I])=>{b&&(_[b]=q.getBuffered(I))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:_})},onError:A=>{var _;const b={type:V.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},I=(_=this.media)==null?void 0:_.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)b.details=R.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)b.errorAction=yt(!0);else if(A.name===ya&&this.sourceBufferCount===0)b.errorAction=yt(!0);else{const P=++this.appendErrors[r];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||I)&&(b.fatal=!0)}this.hls.trigger(m.ERROR,b)}};this.log(`queuing "${r}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===B.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(D,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[re.AUDIOVIDEO]?r.push("audiovideo"):(n[re.AUDIO]&&r.push("audio"),n[re.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([n])=>{if(n){const o=this.tracks[n];(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${n} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var o;return n&&!((o=this.tracks[n])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;M(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(M(o)&&o>=0){const l=Math.max(o,n),h=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,h)}const c=i.frontBufferFlushThreshold;if(M(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,n),u=Math.floor(r/n)*n+h;this.flushFrontBuffer(r,n,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=q.getBuffered(r);if(o.length>0&&s>o.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=q.getBuffered(r),o=n.length;if(o<2)return;const c=n.start(o-1),l=n.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return M(r)?{duration:r}:null;const n=this.media.duration,o=M(s.duration)?s.duration:0;return i>o&&i>n||!M(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(M(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ne(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,o=e[n];if(this.isPending(o)){const c=this.getTrackCodec(o,n),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ne(o)}`);try{const h=s.addSourceBuffer(l),u=$s(n),d=[n,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&Pt(s,"video")&&(i=Po(i,s));const r=ts(i,e.levelCodec);return r?t.slice(0,5)==="audio"?cs(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,n)=>{const o=n.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],o=n?.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=M(i.duration)?i.duration:1/0,l=M(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new Fc(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(n=>this.appendBlocker(n));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(n=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Vr(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function Mc(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function $s(a){return a==="audio"?1:0}class Ls{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&M(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,Ls.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=n||c.height>=n)&&i(c,e[o+1])){r=o;break}}return r}}const Nc={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Se=Nc,Bc={HLS:"h"},Uc=Bc;class Ge{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Ge?s:new Ge(s))),this.value=e,this.params=t}}const $c="Dict";function Gc(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function Kc(a,e,t,s){return new Error(`failed to ${a} "${Gc(e)}" as ${t}`,{cause:s})}function Ke(a,e,t){return Kc("serialize",a,e,t)}class Ta{constructor(e){this.description=e}}const Hr="Bare Item",Vc="Boolean";function Hc(a){if(typeof a!="boolean")throw Ke(a,Vc);return a?"?1":"?0"}function Yc(a){return btoa(String.fromCharCode(...a))}const Wc="Byte Sequence";function qc(a){if(ArrayBuffer.isView(a)===!1)throw Ke(a,Wc);return`:${Yc(a)}:`}const jc="Integer";function Xc(a){return a<-999999999999999||999999999999999<a}function Sa(a){if(Xc(a))throw Ke(a,jc);return a.toString()}function zc(a){return`@${Sa(a.getTime()/1e3)}`}function va(a,e){if(a<0)return-va(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}const Qc="Decimal";function Zc(a){const e=va(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ke(a,Qc);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Jc="String",eh=/[\x00-\x1f\x7f]+/;function th(a){if(eh.test(a))throw Ke(a,Jc);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function sh(a){return a.description||a.toString().slice(7,-1)}const ih="Token";function Yr(a){const e=sh(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ke(e,ih);return e}function ui(a){switch(typeof a){case"number":if(!M(a))throw Ke(a,Hr);return Number.isInteger(a)?Sa(a):Zc(a);case"string":return th(a);case"symbol":return Yr(a);case"boolean":return Hc(a);case"object":if(a instanceof Date)return zc(a);if(a instanceof Uint8Array)return qc(a);if(a instanceof Ta)return Yr(a);default:throw Ke(a,Hr)}}const rh="Key";function di(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw Ke(a,rh);return a}function Ni(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${di(e)}`:`;${di(e)}=${ui(t)}`).join("")}function xa(a){return a instanceof Ge?`${ui(a.value)}${Ni(a.params)}`:ui(a)}function nh(a){return`(${a.value.map(xa).join(" ")})${Ni(a.params)}`}function ah(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw Ke(a,$c);const t=a instanceof Map?a.entries():Object.entries(a),s=e?.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Ge||(r=new Ge(r));let n=di(i);return r.value===!0?n+=Ni(r.params):(n+="=",Array.isArray(r.value)?n+=nh(r):n+=xa(r)),n}).join(`,${s}`)}function Aa(a,e){return ah(a,e)}const Ne="CMCD-Object",le="CMCD-Request",rt="CMCD-Session",ze="CMCD-Status",oh={br:Ne,ab:Ne,d:Ne,ot:Ne,tb:Ne,tpb:Ne,lb:Ne,tab:Ne,lab:Ne,url:Ne,pb:le,bl:le,tbl:le,dl:le,ltc:le,mtp:le,nor:le,nrr:le,rc:le,sn:le,sta:le,su:le,ttfb:le,ttfbb:le,ttlb:le,cmsdd:le,cmsds:le,smrt:le,df:le,cs:le,ts:le,cid:rt,pr:rt,sf:rt,sid:rt,st:rt,v:rt,msd:rt,bs:ze,bsd:ze,cdn:ze,rtp:ze,bg:ze,pt:ze,ec:ze,e:ze},lh={REQUEST:le};function ch(a){return Object.keys(a).reduce((e,t)=>{var s;return(s=a[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function hh(a,e){const t={};if(!a)return t;const s=Object.keys(a),i=e?ch(e):{};return s.reduce((r,n)=>{var o;const c=oh[n]||i[n]||lh.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[n]=a[n],r},t)}function uh(a){return["ot","sf","st","e","sta"].includes(a)}function dh(a){return typeof a=="number"?M(a):a!=null&&a!==""&&a!==!1}const Ia="event";function fh(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const ns=a=>Math.round(a),fi=(a,e)=>Array.isArray(a)?a.map(t=>fi(t,e)):a instanceof Ge&&typeof a.value=="string"?new Ge(fi(a.value,e),a.params):(e.baseUrl&&(a=fh(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),Wt=a=>ns(a/100)*100,gh=(a,e)=>{let t=a;return e.version>=2&&(a instanceof Ge&&typeof a.value=="string"?t=new Ge([a]):typeof a=="string"&&(t=[a])),fi(t,e)},mh={br:ns,d:ns,bl:Wt,dl:Wt,mtp:Wt,nor:gh,rtp:Wt,tb:ns},La="request",Ra="response",Bi=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],ph=["e"],yh=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Rs(a){return yh.test(a)}function Eh(a){return Bi.includes(a)||ph.includes(a)||Rs(a)}const ba=["d","dl","nor","ot","rtp","su"];function Th(a){return Bi.includes(a)||ba.includes(a)||Rs(a)}const Sh=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function vh(a){return Bi.includes(a)||ba.includes(a)||Sh.includes(a)||Rs(a)}const xh=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Ah(a){return xh.includes(a)||Rs(a)}const Ih={[Ra]:vh,[Ia]:Eh,[La]:Th};function _a(a,e={}){const t={};if(a==null||typeof a!="object")return t;const s=e.version||a.v||1,i=e.reportingMode||La,r=s===1?Ah:Ih[i];let n=Object.keys(a).filter(r);const o=e.filter;typeof o=="function"&&(n=n.filter(o));const c=i===Ra||i===Ia;c&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");const l=ie({},mh,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return n.sort().forEach(u=>{let d=a[u];const f=l[u];if(typeof f=="function"&&(d=f(d,h)),u==="v"){if(s===1)return;d=s}u=="pr"&&d===1||(c&&u==="ts"&&!M(d)&&(d=Date.now()),dh(d)&&(uh(u)&&typeof d=="string"&&(d=new Ta(d)),t[u]=d))}),t}function Lh(a,e={}){const t={};if(!a)return t;const s=_a(a,e),i=hh(s,e?.customHeaderMap);return Object.entries(i).reduce((r,[n,o])=>{const c=Aa(o,{whitespace:!1});return c&&(r[n]=c),r},t)}function Rh(a,e,t){return ie(a,Lh(e,t))}const bh="CMCD";function _h(a,e={}){return a?Aa(_a(a,e),{whitespace:!1}):""}function Dh(a,e={}){if(!a)return"";const t=_h(a,e);return encodeURIComponent(t)}function Ch(a,e={}){if(!a)return"";const t=Dh(a,e);return`${bh}=${t}`}const Wr=/CMCD=[^&#]+/;function Ph(a,e,t){const s=Ch(e,t);if(!s)return a;if(Wr.test(a))return a.replace(Wr,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class Da{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Se.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:c};(c===Se.VIDEO||c===Se.AUDIO||c==Se.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Uc.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ie(t,this.createData());const s=t.ot===Se.INIT||t.ot===Se.VIDEO||t.ot===Se.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,o)=>(i.includes(o)&&(n[o]=t[o]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Rh(e.headers,t,r)):e.url=Ph(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===n)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Se.TIMED_TEXT;if(e.sn==="initSegment")return Se.INIT;if(t==="audio")return Se.AUDIO;if(t==="main")return this.hls.audioTracks.length?Se.VIDEO:Se.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===Se.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Se.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}}const kh=3e5;class Ca extends Ce{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===ue.SendAlternateToPenaltyBox&&s.flags===ve.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?n=this.getPathwayForGroupId(o,l,n):c&&(n=c)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),t.details===R.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${i&&i.length} priorities: ${ne(r)} penalized: ${ne(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>kh&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Yn(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===Q.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===Q.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(h=>{const u=new ae(h.attrs);u["PATHWAY-ID"]=n;const d=u.AUDIO&&`${u.AUDIO}_clone_${n}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);const g=Pa(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new vt({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let p=1;p<h.audioGroups.length;p++)y.addGroupId("audio",`${h.audioGroups[p]}_clone_${n}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)y.addGroupId("text",`${h.subtitleGroups[p]}_clone_${n}`);return y});t.push(...l),qr(this.audioTracks,s,c,n),qr(this.subtitleTracks,i,c,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},c={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=h.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":y,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":E}=g;if(y)try{this.uri=new self.URL(y,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${y}`);return}this.scheduleRefresh(this.uri||d.url),p&&this.clonePathways(p);const T={steeringManifest:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,T),E&&this.updatePathwayPriority(E)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){const y=this.loader;if(typeof y?.getResponseHeader=="function"){const p=y.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function qr(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=ie({},n);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=Pa(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function Pa(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n?.[e],o&&(a=o));const c=new self.URL(a);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class lt extends Ce{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=lt.CDMCleanupPromise?[lt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let n=Object.keys(this.keySystemAccessPromises);n.length||(n=Rt(this.config));const o=n.map(ks).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=ss(n);if(s!=="sinf"||o!==oe.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const f=he(new Uint8Array(i)),g=_i(JSON.parse(f).sinf),y=Tn(g);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24))}catch(f){this.warn(`${r} Failed to parse sinf: ${f}`);return}const l=Ee(c),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[l];for(let f=0;f<u.length;f++){const g=u[f],y=g.decryptdata;if(!y.keyId)continue;const p=Ee(y.keyId);if(gs(c,y.keyId)||y.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=h[p],!d)continue;if(y.pssh)break;delete h[p],y.pssh=new Uint8Array(i),y.keyId=c,d=h[l]=d.then(()=>this.generateRequestWithPreferredKeySession(g,s,i,"encrypted-event-key-match")),d.catch(E=>this.handleError(E));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(n=>this.handleError(n))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===oe.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,c)=>!!n&&c.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(u=>n({keySystem:h,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Ie?o(u):o(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Di===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=yl(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],o=(i=n)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ne(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=n=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Ee(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=qt(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Ee(e.decryptdata.keyId||[])}
|
|
28
|
-
} (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>ks(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=ks(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Rt(this.config),s=e.map(ss).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=wh(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=qt(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=jr(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return n.catch(o=>{if(o instanceof Ie){const c=te({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Ie(c,o.message);this.handleError(l,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ie){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ee(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=qt(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=ss(e.keyFormat),r=i?[i]:Rt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Rt(this.config)),e.length===0)throw new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ne({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(n)try{const g=n.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=qt(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new Ci,h=e._onmessage=g=>{const y=e.mediaKeysSession;if(!y){l.emit("error",new Error("invalid state"));return}const{messageType:p,message:E}=g;this.log(`"${p}" message event for session "${y.sessionId}" message size: ${E.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,E).catch(T=>{l.eventNames().length?l.emit("error",T):this.handleError(T)}):p==="license-release"?e.keySystem===oe.FAIRPLAY&&this.updateKeySession(e,ni("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${p}"`)},u=(g,y)=>{y.keyStatus=g;let p;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?p=jr(g,y.decryptdata):g==="expired"?p=new Error(`key expired (keyId: ${o})`):g==="released"?p=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),p&&(l.eventNames().length?l.emit("error",p):this.handleError(p))},d=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const p=this.getKeyStatuses(e);if(!Object.keys(p).some(v=>p[v]!=="status-pending"))return;if(p[o]==="expired"){this.log(`Expired key ${ne(p)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=p[o];if(T)u(T,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const x=this.getKeyStatus(e.decryptdata);if(x&&x!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${x} from other session.`),u(x,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",u(T,e)},1e3)),this.log(`No status for keyId ${o} (${ne(p)}).`)}};Te(e.mediaKeysSession,"message",h),Te(e.mediaKeysSession,"keystatuseschange",d);const f=new Promise((g,y)=>{l.on("error",y),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);e.keySystem===oe.PLAYREADY&&r.length===16&&Mn(r);const n=Ee(r);s==="internal-error"&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,y)=>{n(d.data)},onError:(d,f,g,y)=>{o(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:te({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};i.load(c,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var n,o;h=r[u];const f=(n=h.querySelector("name"))==null?void 0:n.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ni(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,n,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==oe.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Te(s,"encrypted",this.onMediaEncrypted),Te(s,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(Ae(e,"encrypted",this.onMediaEncrypted),Ae(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const t=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Je.clearKeyUriToKeyIdMap();const i=s.length;lt.CDMCleanupPromise=Promise.all(s.map(r=>this.removeSession(r)).concat((t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(r=>{this.log(`Could not clear media keys: ${r}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${r}`)})}))||Promise.resolve())).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${r}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={}}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Ee(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(l=>self.clearTimeout(n[l]));const{drmSystemOptions:o}=this.config;return(Tl(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}lt.CDMCleanupPromise=void 0;function qt(a){if(!a)throw new Error("Could not read keyId of undefined decryptdata");if(a.keyId===null)throw new Error("keyId is null");return Ee(a.keyId)}function wh(a,e){if(a.keyId&&e.mediaKeysSession.keyStatuses.has(a.keyId))return e.mediaKeysSession.keyStatuses.get(a.keyId);if(a.matches(e.decryptdata))return e.keyStatus}class Ie extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function jr(a,e){const t=a==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ie({type:V.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class ka{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*n/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),c>0&&n>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function wa(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function Oa(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){se.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){se.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function pt(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let s=a.cues.length;s--;)e&&a.cues[s].removeEventListener("enter",e),a.removeCue(a.cues[s]);t==="disabled"&&(a.mode=t)}function gi(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=Fh(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function Oh(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r;return a[s].startTime-e<e-a[i].startTime?s:i}function Fh(a,e,t){const s=[],i=Oh(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function as(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class Fa extends Is{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=as(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;as(s.textTracks).forEach(n=>{pt(n)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(n=>i?.indexOf(n)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=$e(o,n);if(h>-1)r=n[h];else{const u=$e(o,this.tracks);r=this.tracks[u]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||ot(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Mt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Mt(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(hi(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&ot(e,s))return s;const i=$e(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=$e(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=as(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>hi(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!M(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:c,type:l,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u)}}function Mh(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Ct(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const Tt=.025;let Es=function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a}({});function Nh(a,e,t){return`${a.identifier}-${t+1}-${Ct(e)}`}class Bh{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Gs(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=Gs(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=M(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Gs(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Tt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Es.Range:Es.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Uh(this)}}function Gs(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<Tt)?e.start:e.start+e.duration}function Ma(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Ks(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function Uh(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function mt(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class $h{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,n),r.once(m.AUDIO_TRACK_LOADED,n),r.once(m.SUBTITLE_TRACK_LOADED,n),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Ma(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=q.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=q.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${mt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Xr=.033;class Gh extends Ce{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const o=n.timelineStart;if(t===o||t>o&&(t<o+(n.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const u=l.cue.pre,d=l.cue.post,f=h.cue.pre,g=h.cue.post;if(u&&!f)return-1;if(f&&!u||d&&!g)return 1;if(g&&!d)return-1;if(!u&&!f&&!d&&!g){const y=l.startTime,p=h.startTime;if(y!==p)return y-p}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||r?.length!==n.length||n.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const o=r[n],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new Bh(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,u)=>{const d=h.cue.pre,f=h.cue.post,g=e[u-1]||null,y=h.appendInPlace,p=f?r:h.startOffset,E=h.duration,T=h.timelineOccupancy===Es.Range?E:0,S=h.resumptionOffset,v=g?.startTime===p,x=p+h.cumulativeDuration;let D=y?x+E:p+S;if(d||!f&&p<=0){const _=l;l+=T,h.timelineStart=x;const b=n;n+=E,s.push({event:h,start:x,end:D,playout:{start:b,end:n},integrated:{start:_,end:l}})}else if(p<=r){if(!v){const I=p-c;if(I>Xr){const P=c,F=l;l+=I;const U=n;n+=I;const H={previousEvent:e[u-1]||null,nextEvent:h,start:P,end:P+I,playout:{start:U,end:n},integrated:{start:F,end:l}};s.push(H)}else I>0&&g&&(g.cumulativeDuration+=I,s[s.length-1].end=p)}f&&(D=x),h.timelineStart=x;const _=l;l+=T;const b=n;n+=E,s.push({event:h,start:x,end:D,playout:{start:b,end:n},integrated:{start:_,end:l}})}else return;const A=h.resumeTime;f||A>r?c=r:c=A}),c<r){var o;const h=c,u=l,d=r-c;l+=d;const f=n;n+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+d,playout:{start:f,end:n},integrated:{start:u,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,u=l?0:h?i:o.startTime;this.updateAssetDurations(o),n===u?o.cumulativeDuration=r:(r=0,n=u),!h&&o.snapOptions.in&&(o.resumeAnchor=ct(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Xr&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=M(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Tt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(n=>{const o=t[n].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${n} playlist end ${c}`),!1;const l=ct(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${n} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=n==="audio"?.175:0;return Math.abs(l.start-s)<Tt+h||Math.abs(l.end-s)<Tt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${n} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const o=e.assetList[n],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function ke(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class Kh{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Ma(s,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,f);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,o=new n(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,y)=>{const p=d.data,E=p?.ASSETS;if(!Array.isArray(E)){const T=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,y);this.hls.trigger(m.ERROR,T);return}e.assetListResponse=p,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:y})},onError:(d,f,g,y)=>{const p=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,y,g);this.hls.trigger(m.ERROR,p)},onTimeout:(d,f,g)=>{const y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);this.hls.trigger(m.ERROR,y)}};return o.load(c,h,u),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:V.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function zr(a){a?.play().catch(()=>{})}function jt(a,e){return`[${a}] Advancing timeline position to ${e}`}class Vh extends Ce{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const n=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),n&&s<o.start||s>=o.end){var c;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(n?-1:1),this.log(`seeked ${n?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!n&&g>f){const y=this.schedule.findJumpRestrictedIndex(f+1,g);if(y>f){this.setSchedulePosition(y);return}}this.setSchedulePosition(g);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const h=l.timelineStart,u=l.duration||0;if(n&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearInterstitial(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const n=r.timelineStart+(r.duration||0);s>=n&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(y=>y.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
27
|
+
transfer tracks: ${ne(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!hn(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,l?.fragments[0].start||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){const p=q.getBuffered(u);d.detectEvictedFragments(l,p,f,null,!0)}const g=$s(l),y=[l,u];this.sourceBuffers[g]=y,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Vr(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[$s(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Oc(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!n&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(n||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const u=t[c],{id:d,codec:f,levelCodec:g,container:y,metadata:p,supplemental:E}=u;let T=i[c];const S=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],v=S!=null&&S.buffer?S:T,x=v?.pendingCodec||v?.codec,D=v?.levelCodec;T||(T=i[c]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:y,levelCodec:g,metadata:p,id:d});const A=ts(x,D),_=A?.replace(Kr,"$1");let b=ts(f,g);const I=(h=b)==null?void 0:h.replace(Kr,"$1");b&&A&&_!==I&&(c.slice(0,5)==="audio"&&(b=cs(b,this.appendSource)),this.log(`switching codec ${x} to ${b}`),b!==(T.pendingCodec||T.codec)&&(T.pendingCodec=b),T.container=y,this.appendChangeType(c,y,b))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const n=this.tracks[e];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,B.MAIN))==null?void 0:t.gap)===!0)return;const n={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,B.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:o,part:c,chunkMeta:l,offset:h}=t,u=l.buffering[r],{sn:d,cc:f}=o,g=self.performance.now();u.start=g;const y=o.stats.buffering,p=c?c.stats.buffering:null;y.start===0&&(y.start=g),p&&p.start===0&&(p.start=g);const E=s.audio;let T=!1;r==="audio"&&E?.container==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=s.video,v=S?.buffer;if(v&&d!=="initSegment"){const A=c||o,_=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const I=A.start+A.duration*.05,P=v.buffered,F=this.currentOp("video");!P.length&&!F?this.blockAudio(A):!F&&!q.isBuffered(v,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(A)}else if(r==="video"){const b=A.end;if(_){const I=_.frag.start;(b>I||b<this.lastVideoAppendEnd||q.isBuffered(v,I))&&this.unblockAudio()}this.lastVideoAppendEnd=b}}const x=(c||o).start,D={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const _=(A=this.tracks[r])==null?void 0:A.buffer;_&&(T?this.updateTimestampOffset(_,x,.1,r,d,f):h!==void 0&&M(h)&&this.updateTimestampOffset(_,h,1e-6,r,d,f)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,y.first===0&&(y.first=A),p&&p.first===0&&(p.first=A);const _={};this.sourceBuffers.forEach(([b,I])=>{b&&(_[b]=q.getBuffered(I))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:_})},onError:A=>{var _;const b={type:V.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},I=(_=this.media)==null?void 0:_.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)b.details=R.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)b.errorAction=yt(!0);else if(A.name===ya&&this.sourceBufferCount===0)b.errorAction=yt(!0);else{const P=++this.appendErrors[r];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||I)&&(b.fatal=!0)}this.hls.trigger(m.ERROR,b)}};this.log(`queuing "${r}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===B.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(D,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[re.AUDIOVIDEO]?r.push("audiovideo"):(n[re.AUDIO]&&r.push("audio"),n[re.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([n])=>{if(n){const o=this.tracks[n];(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${n} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var o;return n&&!((o=this.tracks[n])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;M(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(M(o)&&o>=0){const l=Math.max(o,n),h=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,h)}const c=i.frontBufferFlushThreshold;if(M(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,n),u=Math.floor(r/n)*n+h;this.flushFrontBuffer(r,n,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=q.getBuffered(r);if(o.length>0&&s>o.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=q.getBuffered(r),o=n.length;if(o<2)return;const c=n.start(o-1),l=n.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return M(r)?{duration:r}:null;const n=this.media.duration,o=M(s.duration)?s.duration:0;return i>o&&i>n||!M(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(M(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ne(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,o=e[n];if(this.isPending(o)){const c=this.getTrackCodec(o,n),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ne(o)}`);try{const h=s.addSourceBuffer(l),u=$s(n),d=[n,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&Pt(s,"video")&&(i=Po(i,s));const r=ts(i,e.levelCodec);return r?t.slice(0,5)==="audio"?cs(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,n)=>{const o=n.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],o=n?.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=M(i.duration)?i.duration:1/0,l=M(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,l);u>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new Fc(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(n=>this.appendBlocker(n));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(n=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Vr(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function Mc(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function $s(a){return a==="audio"?1:0}class Ls{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&M(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,Ls.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=n||c.height>=n)&&i(c,e[o+1])){r=o;break}}return r}}const Nc={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Se=Nc,Bc={HLS:"h"},Uc=Bc;class Ge{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Ge?s:new Ge(s))),this.value=e,this.params=t}}const $c="Dict";function Gc(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function Kc(a,e,t,s){return new Error(`failed to ${a} "${Gc(e)}" as ${t}`,{cause:s})}function Ke(a,e,t){return Kc("serialize",a,e,t)}class Ta{constructor(e){this.description=e}}const Hr="Bare Item",Vc="Boolean";function Hc(a){if(typeof a!="boolean")throw Ke(a,Vc);return a?"?1":"?0"}function Yc(a){return btoa(String.fromCharCode(...a))}const Wc="Byte Sequence";function qc(a){if(ArrayBuffer.isView(a)===!1)throw Ke(a,Wc);return`:${Yc(a)}:`}const jc="Integer";function Xc(a){return a<-999999999999999||999999999999999<a}function Sa(a){if(Xc(a))throw Ke(a,jc);return a.toString()}function zc(a){return`@${Sa(a.getTime()/1e3)}`}function va(a,e){if(a<0)return-va(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}const Qc="Decimal";function Zc(a){const e=va(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ke(a,Qc);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Jc="String",eh=/[\x00-\x1f\x7f]+/;function th(a){if(eh.test(a))throw Ke(a,Jc);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function sh(a){return a.description||a.toString().slice(7,-1)}const ih="Token";function Yr(a){const e=sh(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ke(e,ih);return e}function ui(a){switch(typeof a){case"number":if(!M(a))throw Ke(a,Hr);return Number.isInteger(a)?Sa(a):Zc(a);case"string":return th(a);case"symbol":return Yr(a);case"boolean":return Hc(a);case"object":if(a instanceof Date)return zc(a);if(a instanceof Uint8Array)return qc(a);if(a instanceof Ta)return Yr(a);default:throw Ke(a,Hr)}}const rh="Key";function di(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw Ke(a,rh);return a}function Ni(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${di(e)}`:`;${di(e)}=${ui(t)}`).join("")}function xa(a){return a instanceof Ge?`${ui(a.value)}${Ni(a.params)}`:ui(a)}function nh(a){return`(${a.value.map(xa).join(" ")})${Ni(a.params)}`}function ah(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw Ke(a,$c);const t=a instanceof Map?a.entries():Object.entries(a),s=e?.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Ge||(r=new Ge(r));let n=di(i);return r.value===!0?n+=Ni(r.params):(n+="=",Array.isArray(r.value)?n+=nh(r):n+=xa(r)),n}).join(`,${s}`)}function Aa(a,e){return ah(a,e)}const Ne="CMCD-Object",le="CMCD-Request",rt="CMCD-Session",ze="CMCD-Status",oh={br:Ne,ab:Ne,d:Ne,ot:Ne,tb:Ne,tpb:Ne,lb:Ne,tab:Ne,lab:Ne,url:Ne,pb:le,bl:le,tbl:le,dl:le,ltc:le,mtp:le,nor:le,nrr:le,rc:le,sn:le,sta:le,su:le,ttfb:le,ttfbb:le,ttlb:le,cmsdd:le,cmsds:le,smrt:le,df:le,cs:le,ts:le,cid:rt,pr:rt,sf:rt,sid:rt,st:rt,v:rt,msd:rt,bs:ze,bsd:ze,cdn:ze,rtp:ze,bg:ze,pt:ze,ec:ze,e:ze},lh={REQUEST:le};function ch(a){return Object.keys(a).reduce((e,t)=>{var s;return(s=a[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function hh(a,e){const t={};if(!a)return t;const s=Object.keys(a),i=e?ch(e):{};return s.reduce((r,n)=>{var o;const c=oh[n]||i[n]||lh.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[n]=a[n],r},t)}function uh(a){return["ot","sf","st","e","sta"].includes(a)}function dh(a){return typeof a=="number"?M(a):a!=null&&a!==""&&a!==!1}const Ia="event";function fh(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const ns=a=>Math.round(a),fi=(a,e)=>Array.isArray(a)?a.map(t=>fi(t,e)):a instanceof Ge&&typeof a.value=="string"?new Ge(fi(a.value,e),a.params):(e.baseUrl&&(a=fh(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),Wt=a=>ns(a/100)*100,gh=(a,e)=>{let t=a;return e.version>=2&&(a instanceof Ge&&typeof a.value=="string"?t=new Ge([a]):typeof a=="string"&&(t=[a])),fi(t,e)},mh={br:ns,d:ns,bl:Wt,dl:Wt,mtp:Wt,nor:gh,rtp:Wt,tb:ns},La="request",Ra="response",Bi=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],ph=["e"],yh=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Rs(a){return yh.test(a)}function Eh(a){return Bi.includes(a)||ph.includes(a)||Rs(a)}const ba=["d","dl","nor","ot","rtp","su"];function Th(a){return Bi.includes(a)||ba.includes(a)||Rs(a)}const Sh=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function vh(a){return Bi.includes(a)||ba.includes(a)||Sh.includes(a)||Rs(a)}const xh=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Ah(a){return xh.includes(a)||Rs(a)}const Ih={[Ra]:vh,[Ia]:Eh,[La]:Th};function _a(a,e={}){const t={};if(a==null||typeof a!="object")return t;const s=e.version||a.v||1,i=e.reportingMode||La,r=s===1?Ah:Ih[i];let n=Object.keys(a).filter(r);const o=e.filter;typeof o=="function"&&(n=n.filter(o));const c=i===Ra||i===Ia;c&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");const l=ie({},mh,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return n.sort().forEach(u=>{let d=a[u];const f=l[u];if(typeof f=="function"&&(d=f(d,h)),u==="v"){if(s===1)return;d=s}u=="pr"&&d===1||(c&&u==="ts"&&!M(d)&&(d=Date.now()),dh(d)&&(uh(u)&&typeof d=="string"&&(d=new Ta(d)),t[u]=d))}),t}function Lh(a,e={}){const t={};if(!a)return t;const s=_a(a,e),i=hh(s,e?.customHeaderMap);return Object.entries(i).reduce((r,[n,o])=>{const c=Aa(o,{whitespace:!1});return c&&(r[n]=c),r},t)}function Rh(a,e,t){return ie(a,Lh(e,t))}const bh="CMCD";function _h(a,e={}){return a?Aa(_a(a,e),{whitespace:!1}):""}function Dh(a,e={}){if(!a)return"";const t=_h(a,e);return encodeURIComponent(t)}function Ch(a,e={}){if(!a)return"";const t=Dh(a,e);return`${bh}=${t}`}const Wr=/CMCD=[^&#]+/;function Ph(a,e,t){const s=Ch(e,t);if(!s)return a;if(Wr.test(a))return a.replace(Wr,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class Da{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Se.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:c};(c===Se.VIDEO||c===Se.AUDIO||c==Se.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Uc.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ie(t,this.createData());const s=t.ot===Se.INIT||t.ot===Se.VIDEO||t.ot===Se.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,o)=>(i.includes(o)&&(n[o]=t[o]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Rh(e.headers,t,r)):e.url=Ph(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===n)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Se.TIMED_TEXT;if(e.sn==="initSegment")return Se.INIT;if(t==="audio")return Se.AUDIO;if(t==="main")return this.hls.audioTracks.length?Se.VIDEO:Se.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===Se.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Se.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}}const kh=3e5;class Ca extends Ce{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===ue.SendAlternateToPenaltyBox&&s.flags===ve.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?n=this.getPathwayForGroupId(o,l,n):c&&(n=c)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),t.details===R.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${i&&i.length} priorities: ${ne(r)} penalized: ${ne(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>kh&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Yn(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===Q.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===Q.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(h=>{const u=new ae(h.attrs);u["PATHWAY-ID"]=n;const d=u.AUDIO&&`${u.AUDIO}_clone_${n}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);const g=Pa(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new vt({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let p=1;p<h.audioGroups.length;p++)y.addGroupId("audio",`${h.audioGroups[p]}_clone_${n}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)y.addGroupId("text",`${h.subtitleGroups[p]}_clone_${n}`);return y});t.push(...l),qr(this.audioTracks,s,c,n),qr(this.subtitleTracks,i,c,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},c={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=h.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":y,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":E}=g;if(y)try{this.uri=new self.URL(y,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${y}`);return}this.scheduleRefresh(this.uri||d.url),p&&this.clonePathways(p);const T={steeringManifest:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,T),E&&this.updatePathwayPriority(E)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){const y=this.loader;if(typeof y?.getResponseHeader=="function"){const p=y.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function qr(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=ie({},n);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=Pa(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function Pa(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n?.[e],o&&(a=o));const c=new self.URL(a);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class lt extends Ce{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=lt.CDMCleanupPromise?[lt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let n=Object.keys(this.keySystemAccessPromises);n.length||(n=Rt(this.config));const o=n.map(ks).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=ss(n);if(s!=="sinf"||o!==oe.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const f=he(new Uint8Array(i)),g=_i(JSON.parse(f).sinf),y=Tn(g);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24))}catch(f){this.warn(`${r} Failed to parse sinf: ${f}`);return}const l=Ee(c),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[l];for(let f=0;f<u.length;f++){const g=u[f],y=g.decryptdata;if(!y.keyId)continue;const p=Ee(y.keyId);if(gs(c,y.keyId)||y.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=h[p],!d)continue;if(y.pssh)break;delete h[p],y.pssh=new Uint8Array(i),y.keyId=c,d=h[l]=d.then(()=>this.generateRequestWithPreferredKeySession(g,s,i,"encrypted-event-key-match")),d.catch(E=>this.handleError(E));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(n=>this.handleError(n))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t?.[e];if(i)return i.licenseUrl;if(e===oe.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,c)=>!!n&&c.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(u=>n({keySystem:h,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Ie?o(u):o(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Di===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=yl(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],o=(i=n)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ne(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=n=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Ee(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=qt(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Ee(e.decryptdata.keyId||[])}
|
|
28
|
+
} (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>ks(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=ks(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Rt(this.config),s=e.map(ss).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=wh(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=qt(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=jr(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return n.catch(o=>{if(o instanceof Ie){const c=te({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Ie(c,o.message);this.handleError(l,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ie){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ee(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=qt(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=ss(e.keyFormat),r=i?[i]:Rt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Rt(this.config)),e.length===0)throw new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ne({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(n)try{const g=n.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=qt(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new Ci,h=e._onmessage=g=>{const y=e.mediaKeysSession;if(!y){l.emit("error",new Error("invalid state"));return}const{messageType:p,message:E}=g;this.log(`"${p}" message event for session "${y.sessionId}" message size: ${E.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,E).catch(T=>{l.eventNames().length?l.emit("error",T):this.handleError(T)}):p==="license-release"?e.keySystem===oe.FAIRPLAY&&this.updateKeySession(e,ni("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${p}"`)},u=(g,y)=>{y.keyStatus=g;let p;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?p=jr(g,y.decryptdata):g==="expired"?p=new Error(`key expired (keyId: ${o})`):g==="released"?p=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),p&&(l.eventNames().length?l.emit("error",p):this.handleError(p))},d=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const p=this.getKeyStatuses(e);if(!Object.keys(p).some(v=>p[v]!=="status-pending"))return;if(p[o]==="expired"){this.log(`Expired key ${ne(p)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=p[o];if(T)u(T,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const x=this.getKeyStatus(e.decryptdata);if(x&&x!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${x} from other session.`),u(x,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",u(T,e)},1e3)),this.log(`No status for keyId ${o} (${ne(p)}).`)}};Te(e.mediaKeysSession,"message",h),Te(e.mediaKeysSession,"keystatuseschange",d);const f=new Promise((g,y)=>{l.on("error",y),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);e.keySystem===oe.PLAYREADY&&r.length===16&&Mn(r);const n=Ee(r);s==="internal-error"&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,y)=>{n(d.data)},onError:(d,f,g,y)=>{o(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:te({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};i.load(c,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var n,o;h=r[u];const f=(n=h.querySelector("name"))==null?void 0:n.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const c=i.querySelector("Challenge"),l=c?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ni(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,n,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Ie({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==oe.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Te(s,"encrypted",this.onMediaEncrypted),Te(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Ae(e,"encrypted",this.onMediaEncrypted),Ae(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Je.clearKeyUriToKeyIdMap();const r=i.length;lt.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Ee(i?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(l=>self.clearTimeout(n[l]));const{drmSystemOptions:o}=this.config;return(Tl(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}lt.CDMCleanupPromise=void 0;function qt(a){if(!a)throw new Error("Could not read keyId of undefined decryptdata");if(a.keyId===null)throw new Error("keyId is null");return Ee(a.keyId)}function wh(a,e){if(a.keyId&&e.mediaKeysSession.keyStatuses.has(a.keyId))return e.mediaKeysSession.keyStatuses.get(a.keyId);if(a.matches(e.decryptdata))return e.keyStatus}class Ie extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function jr(a,e){const t=a==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ie({type:V.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class ka{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*n/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),c>0&&n>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function wa(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function Oa(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){se.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){se.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function pt(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let s=a.cues.length;s--;)e&&a.cues[s].removeEventListener("enter",e),a.removeCue(a.cues[s]);t==="disabled"&&(a.mode=t)}function gi(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=Fh(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function Oh(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r;return a[s].startTime-e<e-a[i].startTime?s:i}function Fh(a,e,t){const s=[],i=Oh(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function as(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class Fa extends Is{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=as(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;as(s.textTracks).forEach(n=>{pt(n)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(n=>i?.indexOf(n)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=$e(o,n);if(h>-1)r=n[h];else{const u=$e(o,this.tracks);r=this.tracks[u]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||ot(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Mt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Mt(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(hi(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&ot(e,s))return s;const i=$e(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=$e(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=as(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>hi(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!M(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:c,type:l,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u)}}function Mh(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Ct(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const Tt=.025;let Es=function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a}({});function Nh(a,e,t){return`${a.identifier}-${t+1}-${Ct(e)}`}class Bh{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Gs(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=Gs(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=M(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Gs(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Tt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Es.Range:Es.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Uh(this)}}function Gs(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<Tt)?e.start:e.start+e.duration}function Ma(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Ks(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function Uh(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function mt(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class $h{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,n),r.once(m.AUDIO_TRACK_LOADED,n),r.once(m.SUBTITLE_TRACK_LOADED,n),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Ma(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=q.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=q.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${mt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Xr=.033;class Gh extends Ce{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const o=n.timelineStart;if(t===o||t>o&&(t<o+(n.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const u=l.cue.pre,d=l.cue.post,f=h.cue.pre,g=h.cue.post;if(u&&!f)return-1;if(f&&!u||d&&!g)return 1;if(g&&!d)return-1;if(!u&&!f&&!d&&!g){const y=l.startTime,p=h.startTime;if(y!==p)return y-p}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||r?.length!==n.length||n.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const o=r[n],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new Bh(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,u)=>{const d=h.cue.pre,f=h.cue.post,g=e[u-1]||null,y=h.appendInPlace,p=f?r:h.startOffset,E=h.duration,T=h.timelineOccupancy===Es.Range?E:0,S=h.resumptionOffset,v=g?.startTime===p,x=p+h.cumulativeDuration;let D=y?x+E:p+S;if(d||!f&&p<=0){const _=l;l+=T,h.timelineStart=x;const b=n;n+=E,s.push({event:h,start:x,end:D,playout:{start:b,end:n},integrated:{start:_,end:l}})}else if(p<=r){if(!v){const I=p-c;if(I>Xr){const P=c,F=l;l+=I;const U=n;n+=I;const H={previousEvent:e[u-1]||null,nextEvent:h,start:P,end:P+I,playout:{start:U,end:n},integrated:{start:F,end:l}};s.push(H)}else I>0&&g&&(g.cumulativeDuration+=I,s[s.length-1].end=p)}f&&(D=x),h.timelineStart=x;const _=l;l+=T;const b=n;n+=E,s.push({event:h,start:x,end:D,playout:{start:b,end:n},integrated:{start:_,end:l}})}else return;const A=h.resumeTime;f||A>r?c=r:c=A}),c<r){var o;const h=c,u=l,d=r-c;l+=d;const f=n;n+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+d,playout:{start:f,end:n},integrated:{start:u,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,u=l?0:h?i:o.startTime;this.updateAssetDurations(o),n===u?o.cumulativeDuration=r:(r=0,n=u),!h&&o.snapOptions.in&&(o.resumeAnchor=ct(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Xr&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=M(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Tt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(n=>{const o=t[n].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${n} playlist end ${c}`),!1;const l=ct(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${n} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=n==="audio"?.175:0;return Math.abs(l.start-s)<Tt+h||Math.abs(l.end-s)<Tt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${n} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const o=e.assetList[n],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function ke(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class Kh{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Ma(s,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,f);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,o=new n(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,y)=>{const p=d.data,E=p?.ASSETS;if(!Array.isArray(E)){const T=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,y);this.hls.trigger(m.ERROR,T);return}e.assetListResponse=p,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:y})},onError:(d,f,g,y)=>{const p=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,y,g);this.hls.trigger(m.ERROR,p)},onTimeout:(d,f,g)=>{const y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);this.hls.trigger(m.ERROR,y)}};return o.load(c,h,u),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:V.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function zr(a){var e;a==null||(e=a.play())==null||e.catch(()=>{})}function jt(a,e){return`[${a}] Advancing timeline position to ${e}`}class Vh extends Ce{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const n=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),n&&s<o.start||s>=o.end){var c;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(n?-1:1),this.log(`seeked ${n?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!n&&g>f){const y=this.schedule.findJumpRestrictedIndex(f+1,g);if(y>f){this.setSchedulePosition(y);return}}this.setSchedulePosition(g);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const h=l.timelineStart,u=l.duration||0;if(n&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearInterstitial(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const n=r.timelineStart+(r.duration||0);s>=n&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(y=>y.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
|
|
29
29
|
Schedule: ${c.map(y=>ke(y))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,f=null;n&&(d=this.updateItem(n,this.timelinePos),this.itemsMatch(n,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),s.forEach(y=>{y.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){const p=y.assetItem.timelineStart,E=y.timelineOffset-p;if(E)try{y.timelineOffset=p}catch(T){Math.abs(E)>Tt&&this.warn(`${T} ("${y.assetId}" ${y.timelineOffset}->${p})`)}}}),u||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(n)&&h.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(d,n),g&&f!==d&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Kh(e),this.schedule=new Gh(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Ae(e,"play",this.onPlay),Ae(e,"pause",this.onPause),Ae(e,"seeking",this.onSeeking),Ae(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Te(s,"seeking",this.onSeeking),Te(s,"timeupdate",this.onTimeupdate),Te(s,"play",this.onPlay),Te(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,f,g,y)=>{if(u){let p=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==Es.Point){const T=s(f);T?.interstitial===E&&(p+=T.assetItem.startOffset+T[y])}}else{const T=g==="bufferedPos"?n():e[g];p+=T-u.start}return p}return 0},r=(u,d)=>{var f;if(u!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const y=e.schedule.findItemIndexAtTime(u),p=(g=e.schedule.items)==null?void 0:g[y];if(p){const E=p[d].start-p.start;return u+E}}return u},n=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},c=(u,d)=>{var f,g;const y=e.effectivePlayingItem;if(y!=null&&(f=y.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const p=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),T=(g=e.schedule.items)==null?void 0:g[E],S=e.getBufferingPlayer(),v=S?.interstitial,x=v?.appendInPlace,D=p&&e.itemsMatch(p,T);if(p&&(x||D)){const A=s(e.playingAsset),_=A?.media||e.primaryMedia;if(_){const b=d==="primary"?_.currentTime:i(p,d,e.playingAsset,"timelinePos","currentTime"),I=u-b,P=(x?b:_.currentTime)+I;if(P>=0&&(!A||x||P<=A.duration)){_.currentTime=P;return}}}if(T){let A=u;if(d!=="primary"){const b=T[d].start,I=u-b;A=T.start+I}const _=!e.isInterstitial(T);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(_||T.event.appendInPlace)){const b=e.media||(x?S?.media:null);b&&(b.currentTime=A)}else if(p){const b=e.findItemIndex(p);if(E>b){const P=e.schedule.findJumpRestrictedIndex(b+1,E);if(P>b){e.setSchedulePosition(P);return}}let I=0;if(_)e.timelinePos=A,e.checkBuffer();else{const P=T.event.assetList,F=u-(T[d]||T).start;for(let U=P.length;U--;){const H=P[U];if(H.duration&&F>=H.startOffset&&F<H.startOffset+H.duration){I=U;break}}}e.setSchedulePosition(E,I)}}},l=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var f;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const u=l(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=l(),f=e.effectivePlayingItem;f&&f===d&&c(u+f.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=l())==null?void 0:u.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const d=(u=l())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return n()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){c(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u?.event;if(d&&!d.restrictions.skip){const f=e.findItemIndex(u);if(d.appendInPlace){const g=u.playout.start+u.event.duration;c(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!M(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ne(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,o=e!==n,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(n.media)c&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const g=this.getBufferingPlayer();g?(r=g.transferMedia(),h=`${g}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ne(r)}`);else if(!this.detachedData||n.media===t){const g=this.playerQueue;g.length>1&&g.forEach(y=>{if(o&&y.interstitial.appendInPlace!==c){const p=y.interstitial;this.clearInterstitial(y.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${p}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(d===r&&f){const g=o&&e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:!o||g,cueRemoval:!o}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.log(jt("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){const n=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=Ks(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var n;const o=(n=this.schedule.items)==null?void 0:n[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=Ks(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1,o=r.length;if(n>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(jt("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const n=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&ke(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const h=n.event,u=this.playingAsset,d=u?.identifier,f=d?this.getAssetPlayer(d):null;if(f&&d&&(!this.eventItemsMatch(n,r)||t!==void 0&&d!==h.assetList[t].identifier)){var c;const g=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${h.assetList.length} ${mt(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:g,event:h,schedule:i.slice(0),scheduleIndex:e,player:f}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(d,r),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${ke(n)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const g=(l=this.schedule)==null?void 0:l.items;if(r&&g){const y=this.findItemIndex(r);this.advanceSchedule(y,g,t,n,o)}return}}this.advanceSchedule(e,i,t,n,o)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const u=h.interstitial,d=n.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=n.findAssetIndex(h,this.timelinePos);const g=Ks(h,s-1);if(h.isAssetPastPlayoutLimit(g)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=g}const u=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${ke(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=h.assetList[s];if(!f){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const g=h.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${h}`),d=this.createAssetPlayer(h,f,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&zr(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&zr(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${ke(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(jt("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ke(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(jt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=te(te({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{audio:s});return}const r=te(te({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{subtitles:s});return}const r=te(te({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=nr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=nr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const n=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[n];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${ke(e)} (was ${ke(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,o=this.findItemIndex(n);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((c===-1&&r&&e>=r.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=u),this.isInterstitial(r)){const f=r.event;if(u-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(c===o?this.bufferedToItem(n):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${ke(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===l&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const n=this.preloadAssets(s,t);if(n!=null&&n.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(n,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,n=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!n&&i){for(let l=t;l<i;l++){const h=e.assetList[l],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,n){const o={parentIdentifier:e.identifier,identifier:Nh(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(n||o)&&(n=ie({},n),o.videoCodec&&(n.videoCodec=o.videoCodec),o.videoRange&&(n.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const v=this.timelinePos-t.timelineStart;if(v>1){const x=t.duration;x&&v<x&&(h=v)}}const u=t.identifier,d=te(te({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=ie({},f,{contentId:Ct(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const g=new $h(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;let y=!0;const p=v=>{if(v.live){var x;const _=new Error(`Interstitials MUST be VOD assets ${e}`),b={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:_},I=((x=this.schedule)==null?void 0:x.findEventIndex(e.identifier))||-1;this.handleAssetItemError(b,e,I,s,_.message);return}const D=v.edge-v.fragmentStart,A=t.duration;(y||A===null||D>A)&&(y=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${D}`),t.duration=D,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(v,{details:x})=>p(x)),g.on(m.LEVEL_PTS_UPDATED,(v,{details:x})=>p(x)),g.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(v,x)=>{const D=this.getAssetPlayer(u);if(D&&x.tracks){D.off(m.BUFFER_CODECS,E),D.tracks=x.tracks;const A=this.primaryMedia;this.bufferingAsset===D.assetItem&&A&&!D.media&&this.bufferAssetPlayer(D,A)}};g.on(m.BUFFER_CODECS,E);const T=()=>{var v;const x=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${x}`),!x||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),A=(v=this.schedule.items)==null?void 0:v[D];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};g.on(m.BUFFERED_TO_END,T);const S=v=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,v)};return g.once(m.MEDIA_ENDED,S(s)),g.once(m.PLAYOUT_LIMIT_REACHED,S(1/0)),g.on(m.ERROR,(v,x)=>{if(!this.schedule)return;const D=this.getAssetPlayer(u);if(x.details===R.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${x.error} ${e}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const x=new Error(`Asset player destroyed unexpectedly ${u}`),D={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${mt(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)}),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&ke(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:o,assetId:c}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${mt(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&l?.interstitial.appendInPlace===!1)return;const u=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!hn(u,e.tracks)){const d=new Error(`Asset ${mt(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},g=r.findAssetIndex(n);this.handleAssetItemError(f,r,o,g,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const o=this.getAssetPlayer(n.identifier);if(o){const c=o.currentTime||i-n.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===R.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&mt(n)} ${e.error}`),!this.schedule)return;const o=n?.identifier||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,u=ie({},e,{fatal:!1,errorAction:yt(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(n&&(this.clearAssetPlayer(o,null),n.error=g),!t.assetList.some(y=>!y.error))t.error=g;else for(let y=i;y<t.assetList.length;y++)this.resetAssetPlayer(t.assetList[y].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,s,i):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${ke(s)} error: ${e.error}`);let i=this.timelinePos;i===-1&&(i=this.hls.startPosition);const r=this.updateItem(s,i);if(this.itemsMatch(s,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const n=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(n)}else this.checkStart()}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(n)))return;const c=r.timelineStart,l=r.duration;let h=0;o.forEach((y,p)=>{const E=parseFloat(y.DURATION);this.createAsset(r,p,h,c+h,E,y.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const u=this.waitingItem,d=u?.event.identifier===n;this.updateSchedule();const f=(i=this.bufferingItem)==null?void 0:i.event;if(d){var g;const y=this.schedule.findEventIndex(n),p=(g=this.schedule.items)==null?void 0:g[y];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==y){r.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${r}`),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(p)}this.setSchedulePosition(y)}else if(f?.identifier===n){const y=r.assetList[0];if(y){const p=this.getAssetPlayer(y.identifier);if(f.appendInPlace){const E=this.primaryMedia;p&&E&&this.bufferAssetPlayer(p,E)}else p&&p.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Qr=500;class Na extends xs{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",B.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=C.IDLE,this.setInterval(Qr),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragContextChanged(s)||(ce(s)&&(this.fragPrevious=s),this.state=C.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){n=r[l];break}const c=s.start+s.duration;n?n.end=c:(n={start:o,end:c},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,B.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===B.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ma(this.levels,t)){this.levels=t.map(s=>new vt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new vt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,B.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==C.STOPPED&&this.setInterval(Qr)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=r[o];if(o>=r.length||!c)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(s=c.details)!=null&&s.live){if(n.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!c.details)n.hasProgramDateTime&&u.hasProgramDateTime?(ps(n,u),l=n.fragmentStart):d&&(l=d.start,oi(n,l));else{var h;l=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&d&&(l=d.start,oi(n,l))}u&&!this.startFragRequested&&this.setStartPosition(u,l)}c.details=n,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(ct(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&Et(i.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,bi(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=C.IDLE})}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=n,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;const u=l.fragments,d=u.length,f=l.edge;let g=null;const y=this.fragPrevious;if(o<f){const T=i.maxFragLookUpTolerance,S=o>f-T?0:T;g=ct(y,u,Math.max(u[0].start,o),S),!g&&y&&y.start<u[0].start&&(g=u[0])}else g=u[d-1];if(g=this.filterReplacedPrimary(g,s.details),!g)return;const p=g.sn-l.startSN,E=u[p-1];if(E&&E.cc===g.cc&&this.fragmentTracker.getState(E)===de.NOT_LOADED&&(g=E),this.fragmentTracker.getState(g)===de.NOT_LOADED){const T=this.mapToInitFragWhenRequired(g);T&&this.loadFragment(T,s,o)}}}loadFragment(e,t,s){ce(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Hh(this.tracksBuffered[this.currentTrackId]||[])}}class Hh{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const Yh={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Ba=a=>String.fromCharCode(Yh[a]||a),we=15,He=100,Wh={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},qh={17:2,18:4,21:6,22:8,23:10,19:13,20:15},jh={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Xh={25:2,26:4,29:6,30:8,31:10,27:13,28:15},zh=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Qh{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;se.log(`${this.time} [${e}] ${s}`)}}}const nt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Ua{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Zh{constructor(){this.uchar=" ",this.penState=new Ua}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Jh{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Ua,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<He;t++)this.chars.push(new Zh);this.logger=e}equals(e){for(let t=0;t<He;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<He;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<He;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>He&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=He)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Ba(e);if(this.pos>=He){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<He;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<He;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Vs{constructor(e){this.rows=[],this.currRow=we-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<we;t++)this.rows.push(new Jh(e));this.logger=e}reset(){for(let e=0;e<we;e++)this.rows[e].clear();this.currRow=we-1}equals(e){let t=!0;for(let s=0;s<we;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<we;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<we;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ne(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<we;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ne(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<we;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
|
|
30
30
|
`)),s}getTextAndFormat(){return this.rows}}class Zr{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Vs(s),this.nonDisplayedMemory=new Vs(s),this.lastOutputScreen=new Vs(s),this.currRollUpRow=this.displayedMemory.rows[we-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[we-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ne(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Jr{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=tu(),this.logger=void 0;const i=this.logger=new Qh;this.channels=[null,new Zr(e,t,i),new Zr(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+nt([t[s],t[s+1]])+"] -> ("+nt([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(eu(i,r,c)){Xt(null,null,c),this.logger.log(3,()=>"Repeated command ("+nt([i,r])+") is dropped");continue}Xt(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else Xt(null,null,c);if(!n&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+nt([i,r])+" orig: "+nt([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+nt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const n=e<=23?1:2;t>=64&&t<=95?s=n===1?Wh[e]:jh[e]:s=n===1?qh[e]:Xh[e];const o=this.channels[n];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+Ba(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+nt(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=zh[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Xt(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Xt(a,e,t){t.a=a,t.b=e}function eu(a,e,t){return t.a===a&&t.b===e}function tu(){return{a:null,b:null}}var Ui=function(){if(ms!=null&&ms.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(a,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const u in h)o[u]=h[u]}return o}function n(o,c,l){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",f=!1,g=o,y=c,p=l,E=null,T="",S=!0,v="auto",x="start",D=50,A="middle",_=50,b="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(I){d=""+I}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return y},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");y=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return p},set:function(I){p=""+I,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(I){E=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return T},set:function(I){const P=s(I);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return S},set:function(I){S=!!I,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return v},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");v=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return x},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");x=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return D},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");D=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");A=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return _},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");_=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return b},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");b=P,this.hasBeenReset=!0}})),h.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class su{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function $a(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class iu{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Ga(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],c=n[1];e(o,c)}}const mi=new Ui(0,0,""),zt=mi.align==="middle"?"middle":"center";function ru(a,e,t){const s=a;function i(){const o=$a(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){const l=new iu;Ga(o,function(d,f){let g;switch(d){case"region":for(let y=t.length-1;y>=0;y--)if(t[y].id===f){l.set(d,t[y].region);break}break;case"vertical":l.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(d,g[0]),l.percent(d,g[0])&&l.set("snapToLines",!1),l.alt(d,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",zt,"end"]);break;case"position":g=f.split(","),l.percent(d,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",zt,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,f);break;case"align":l.alt(d,f,["start",zt,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&mi.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",zt);let u=l.get("position","auto");u==="auto"&&mi.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function Ka(a){return a.replace(/<br(?: \/)?>/gi,`
|
|
31
31
|
`)}class nu{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new su,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,n=0;for(r=Ka(r);n<r.length&&r[n]!=="\r"&&r[n]!==`
|