PageSourceSearch

https://faptap.net/assets/Player.vue_vue_type_script_setup_true_lang.373c1e69.js

js faptap.net collected 2026-09-25 22:12:25 UTC 562,123 bytes, 40 lines download raw bytes

1import{d as zs,f as de,i as q,v as ne,b as Ae,L as Ni,w as Zt,aK as $r,a8 as ms,c as ps,p as dt,t as qe,h as oe,aL as Tr,a4 as Yl,ay as Wl,a6 as ql,G as jl,r as zl,aM as Xl,aN as Ql,a as ei,K as Zl,aG as qi,aF as $e,u as nt,l as Xe,ac as Ln,aJ as In,g as Nt,j as Ge,n as zt,_ as ls,k as ji,m as at,O as Jl,P as ec,Q as tc,aO as sc,s as ic,q as rc,aP as bn,F as Rn,N as _n,aQ as nc}from"./index.16ba4ea0.js";import{u as ac,h as Dn,s as ti,g as Fs,v as Cn,a as oc,b as lc,S as Pn}from"./VRPlayer.vue_vue_type_style_index_0_lang.a44f4621.js";import{intifaceMetric as cc,bluetoothMetric as uc,fleshyX3Metric as dc,fstMetric as hc,vacuglideMetric as fc,autoblowMetric as gc,handyMetric as mc,loobMetric as pc,osrMetric as yc}from"./metric.84224865.js";var Ec="M11,15H13V17H11V15M11,7H13V13H11V7M12,2C6.47,2 2,6.5 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20Z",vc="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z",Tc="M10,12V22H8V14H6V12H10M18,14V20C18,21.11 17.11,22 16,22H14A2,2 0 0,1 12,20V14A2,2 0 0,1 14,12H16C17.11,12 18,12.9 18,14M14,14V20H16V14H14M11.5,3C14.15,3 16.55,4 18.4,5.6L21,3V10H14L16.62,7.38C15.23,6.22 13.46,5.5 11.5,5.5C7.96,5.5 4.95,7.81 3.9,11L1.53,10.22C2.92,6.03 6.85,3 11.5,3Z",Sc="M5,5H10V7H7V10H5V5M14,5H19V10H17V7H14V5M17,14H19V19H14V17H17V14M10,17V19H5V14H7V17H10Z",xc="M14,14H19V16H16V19H14V14M5,14H10V19H8V16H5V14M8,5H10V10H5V8H8V5M19,8V10H14V5H16V8H19Z",kn="M14,19H18V5H14M6,19H10V5H6V19Z",wn="M8,5.14V19.14L19,12.14L8,5.14Z",Ac="M14.5,13.5H16.5V10.5H14.5M18,14A1,1 0 0,1 17,15H16.25V16.5H14.75V15H14A1,1 0 0,1 13,14V10A1,1 0 0,1 14,9H17A1,1 0 0,1 18,10M11,15H9.5V13H7.5V15H6V9H7.5V11.5H9.5V9H11M19,4H5C3.89,4 3,4.89 3,6V18A2,2 0 0,0 5,20H19A2,2 0 0,0 21,18V6C21,4.89 20.1,4 19,4Z",Lc="M12.5,3C17.15,3 21.08,6.03 22.47,10.22L20.1,11C19.05,7.81 16.04,5.5 12.5,5.5C10.54,5.5 8.77,6.22 7.38,7.38L10,10H3V3L5.6,5.6C7.45,4 9.85,3 12.5,3M10,12V22H8V14H6V12H10M18,14V20C18,21.11 17.11,22 16,22H14A2,2 0 0,1 12,20V14A2,2 0 0,1 14,12H16C17.11,12 18,12.9 18,14M14,14V20H16V14H14Z",Ic="M14,3.23V5.29C16.89,6.15 19,8.83 19,12C19,15.17 16.89,17.84 14,18.7V20.77C18,19.86 21,16.28 21,12C21,7.72 18,4.14 14,3.23M16.5,12C16.5,10.23 15.5,8.71 14,7.97V16C15.5,15.29 16.5,13.76 16.5,12M3,9V15H7L12,20V4L7,9H3Z",bc="M12,4L9.91,6.09L12,8.18M4.27,3L3,4.27L7.73,9H3V15H7L12,20V13.27L16.25,17.53C15.58,18.04 14.83,18.46 14,18.7V20.77C15.38,20.45 16.63,19.82 17.68,18.96L19.73,21L21,19.73L12,10.73M19,12C19,12.94 18.8,13.82 18.46,14.64L19.97,16.15C20.62,14.91 21,13.5 21,12C21,7.72 18,4.14 14,3.23V5.29C16.89,6.15 19,8.83 19,12M16.5,12C16.5,10.23 15.5,8.71 14,7.97V10.18L16.45,12.63C16.5,12.43 16.5,12.21 16.5,12Z";const G=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},Rc=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=_c},_c=Number.MAX_SAFE_INTEGER||9007199254740991;let W=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}({}),_=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_ER
1ROR="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 ie={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},K={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class cs{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}
vendor: 4,140 bytes, line 1
1getTotalWeight(){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 Dc{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 cs(e),this.fast_=new cs(t),this.defaultTTFB_=i,this.ttfb_=new cs(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new cs(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new cs(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new cs(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 Cc(a,e,t){return(e=kc(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function he(){return he=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},he.apply(null,arguments)}function On(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 le(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?On(Object(t),!0).forEach(function(s){Cc(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):On(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function Pc(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 kc(a){var e=Pc(a,"string");return typeof e=="symbol"?e:e+""}class lt{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=$t,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 $t=function(){},wc={trace:$t,debug:$t,log:$t,warn:$t,info:$t,error:$t};function Sr(){return he({},wc)}function Oc(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):$t}function Mn(a,e,t){return e[a]?e[a].bind(e):Oc(a,t)}const xr=Sr();function Mc(a,e,t){const s=Sr();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Mn(r,a,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Sr()}i.forEach(r=>{xr[r]=Mn(r,a)})}else he(xr,s);return s}const ce=xr;function Kt(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Fc(a){return typeof self<"u"&&a===self.ManagedMediaSource}function Ja(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 tt(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const u=l.indexOf("\0");return u!==-1?l.substring(0,u):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>>
vendor: 27,929 bytes, line 1
14){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 Be(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 eo(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Nc(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var zi={exports:{}},Fn;function Bc(){return Fn||(Fn=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,u){if(u=u||{},c=c.trim(),l=l.trim(),!l){if(!u.alwaysNormalize)return c;var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):l;var g=o.parseURL(c);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var y={scheme:g.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(y.netLoc=g.netLoc,h.path[0]!=="/"))if(!h.path)y.path=g.path,h.params||(y.params=g.params,h.query||(y.query=g.query));else{var E=g.path,v=E.substring(0,E.lastIndexOf("/")+1)+h.path;y.path=o.normalizePath(v)}return y.path===null&&(y.path=u.alwaysNormalize?o.normalizePath(h.path):h.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})()}(zi)),zi.exports}var Gr=Bc();class Vr{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 fe={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class to{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,$c(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=(t==null?void 0: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={[fe.AUDIO]:null,[fe.VIDEO]:null,[fe.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 Vr),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Gr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[fe.AUDIO]=null,e[fe.VIDEO]=null,e[fe.AUDIOVIDEO]=null}}function be(a){return a.sn!=="initSegment"}class Xi extends to{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(G(e)&&G(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=G(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(!G(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return be(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 Uc extends to{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 so(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||so(t,e)}}function $c(a,e){const t=so(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const Nn=Math.pow(2,32)-1,Gc=[].push,io={video:1,audio:2,id3:3,text:4};function Pe(a){return String.fromCharCode.apply(null,a)}function ro(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function Q(a,e){const t=no(a,e);return t<0?4294967296+t:t}function Bn(a,e){let t=Q(a,e);return t*=Math.pow(2,32),t+=Q(a,e+4),t}function no(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function Vc(a){const e=a.byteLength;for(let t=0;t<e;){const s=Q(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 te(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=Q(a,i),n=Pe(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=te(a.subarray(i+8,o),e.slice(1));c.length&&Gc.apply(t,c)}i=o}return t}function Kc(a){const e=[],t=a[0];let s=8;const i=Q(a,s);s+=4;let r=0,n=0;t===0?(r=Q(a,s),n=Q(a,s+4),s+=8):(r=Bn(a,s),n=Bn(a,s+8),s+=16),s+=2;let o=a.length+n;const c=ro(a,s);s+=2;for(let l=0;l<c;l++){let u=s;const d=Q(a,u);u+=4;const h=d&2147483647;if((d&2147483648)>>>31===1)return ce.warn("SIDX has hierarchical references (not supported)"),null;const f=Q(a,u);u+=4,e.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+h-1}}),o+=h,u+=4,s=u}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function ao(a){const e=[],t=te(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=te(r,["tkhd"])[0];if(n){let o=n[0];const c=Q(n,o===0?12:20),l=te(r,["mdia","mdhd"])[0];if(l){o=l[0];const u=Q(l,o===0?12:20),d=te(r,["mdia","hdlr"])[0];if(d){const h=Pe(d.subarray(8,12)),g={soun:fe.AUDIO,vide:fe.VIDEO}[h],f=te(r,["mdia","minf","stbl","stsd"])[0],y=Hc(f);g?(e[c]={timescale:u,type:g,stsd:y},e[g]=le({timescale:u,id:c},y)):e[c]={timescale:u,type:h,stsd:y}}}}}return te(a,["moov","mvex","trex"]).forEach(i=>{const r=Q(i,4),n=e[r];n&&(n.default={duration:Q(i,12),flags:Q(i,20)})}),e}function Hc(a){const e=a.subarray(8),t=e.subarray(8+78),s=Pe(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=te(e,[s])[0].subarray(s==="enca"?28:78);te(l,["sinf"]).forEach(d=>{const h=te(d,["schm"])[0];if(h){const g=Pe(h.subarray(4,8));if(g==="cbcs"||g==="cenc"){const f=te(d,["frma"])[0];f&&(i=Pe(f))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=te(t,["avcC"])[0];c&&c.length>3&&(i+="."+ii(c[1])+ii(c[2])+ii(c[3]),r=si(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=te(e,[s])[0],l=te(c.subarray(28),["esds"])[0];if(l&&l.length>7){let u=4;if(l[u++]!==3)break;u=Qi(l,u),u+=2;const d=l[u++];if(d&128&&(u+=2),d&64&&(u+=l[u++]),l[u++]!==4)break;u=Qi(l,u);const h=l[u++];if(h===64)i+="."+ii(h);else break;if(u+=12,l[u++]!==5)break;u=Qi(l,u);const g=l[u++];let f=(g&248)>>3;f===31&&(f+=1+((g&7)<<3)+((l[u]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const c=te(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],u=["","A","B","C"][l>>6],d=l&31,h=Q(c,2),g=(l&32)>>5?"H":"L",f=c[12],y=c.subarray(6,12);i+="."+u+d,i+="."+Yc(h).toString(16).toUpperCase(),i+="."+g+f;let E="";for(let v=y.length;v--;){const T=y[v];(T||E)&&(E="."+T.toString(16).toUpperCase()+E)}i+=E}r=si(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=si(i,t)||i;break}case"vp09":{const c=te(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],u=c[5],d=c[6]>>4&15;i+="."+Tt(l)+"."+Tt(u)+"."+Tt(d)}break}case"av01":{const c=te(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,u=c[1]&31,d=c[2]>>>7?"H":"M",h=(c[2]&64)>>6,g=(c[2]&32)>>5,f=l===2&&h?g?12:10:h?10:8,y=(c[2]&16)>>4,E=(c[2]&8)>>3,v=(c[2]&4)>>2,T=c[2]&3,S=1,x=1,A=1,P=0;i+="."+l+"."+Tt(u)+d+"."+Tt(f)+"."+y+"."+E+v+T+"."+Tt(S)+"."+Tt(x)+"."+Tt(A)+"."+P,r=si("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function si(a,e){const t=te(e,["dvvC"]),s=t.length?t[0]:te(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+Tt(i)+"."+Tt(r)}}function Yc(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<32-1-t;return e>>>0}function Qi(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function ii(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function Tt(a){return(a<10?"0":"")+a}function Wc(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&oo(a,(s,i)=>{const r=s.subarray(8,24);r.some(n=>n!==0)||(ce.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Be(r)} -> ${Be(t)}`),s.set(t,8))})}function qc(a){const e=[];return oo(a,t=>e.push(t.subarray(8,24))),e}function oo(a,e){te(a,["moov","trak"]).forEach(s=>{const i=te(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=te(r,["enca"]);const o=n.length>0;o||(n=te(r,["encv"])),n.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);te(l,["sinf"]).forEach(d=>{const h=lo(d);h&&e(h,o)})})})}function lo(a){const e=te(a,["schm"])[0];if(e){const t=Pe(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=te(a,["schi","tenc"])[0];if(s)return s}}}function jc(a,e,t){const s={},i=te(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=te(n,["tfhd"])[0],c=Q(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 u=s[c],d=te(n,["tfdt"])[0];if(d){const S=d[0];let x=Q(d,4);S===1&&(x===Nn?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(x*=Nn+1,x+=Q(d,8))),G(x)&&(!G(u.start)||x<u.start)&&(u.start=x)}const h=l.default,g=Q(o,0)|(h==null?void 0:h.flags);let f=(h==null?void 0:h.duration)||0;g&8&&(g&2?f=Q(o,12):f=Q(o,8));const y=te(n,["trun"]);let E=u.start||0,v=0,T=f;for(let S=0;S<y.length;S++){const x=y[S],A=Q(x,4),P=u.sampleCount;u.sampleCount+=A;const L=x[3]&1,p=x[3]&4,D=x[2]&1,I=x[2]&2,k=x[2]&4,N=x[2]&8;let B=8,Y=A;for(L&&(B+=4),p&&A&&(!(x[B+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=P),B+=4,D?(T=Q(x,B),B+=4):T=f,I&&(B+=4),N&&(B+=4),E+=T,v+=T,Y--);Y--;)D?(T=Q(x,B),B+=4):T=f,I&&(B+=4),k&&(x[B+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(Y+1),u.keyFrameStart=E),B+=4),N&&(B+=4),E+=T,v+=T;!v&&f&&(v+=f*A)}u.duration+=v}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=te(a,["sidx"]);for(let c=0;c<o.length;c++){const l=Kc(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const u=l.references.reduce((d,h)=>d+h.info.duration||0,0);n=Math.max(n,u+l.earliestPresentationTime/l.timescale)}}n&&G(n)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=n*s[c].timescale-s[c].start)})}return s}function zc(a){const e={valid:null,remainder:null},t=te(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 ot(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Un(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return te(s,["moof"]).map(c=>{const l=c.byteOffset-8;te(c,["traf"]).map(d=>{const h=te(d,["tfdt"]).map(g=>{const f=g[0];let y=Q(g,4);return f===1&&(y*=Math.pow(2,32),y+=Q(g,8)),y/i})[0];return h!==void 0&&(a=h),te(d,["tfhd"]).map(g=>{const f=Q(g,4),y=Q(g,0)&16777215,E=(y&1)!==0,v=(y&2)!==0,T=(y&8)!==0;let S=0;const x=(y&16)!==0;let A=0;const P=(y&32)!==0;let L=8;f===r&&(E&&(L+=8),v&&(L+=4),T&&(S=Q(g,L),L+=4),x&&(A=Q(g,L),L+=4),P&&(L+=4),e.type==="video"&&(n=Bi(e.codec)),te(d,["trun"]).map(p=>{const D=p[0],I=Q(p,0)&16777215,k=(I&1)!==0;let N=0;const B=(I&4)!==0,Y=(I&256)!==0;let $=0;const O=(I&512)!==0;let V=0;const U=(I&1024)!==0,H=(I&2048)!==0;let X=0;const M=Q(p,4);let F=8;k&&(N=Q(p,F),F+=4),B&&(F+=4);let Z=N+l;for(let ae=0;ae<M;ae++){if(Y?($=Q(p,F),F+=4):$=S,O?(V=Q(p,F),F+=4):V=A,U&&(F+=4),H&&(D===0?X=Q(p,F):X=no(p,F),F+=4),e.type===fe.VIDEO){let ee=0;for(;ee<V;){const re=Q(s,Z);if(Z+=4,Xc(n,s[Z])){const pe=s.subarray(Z,Z+re);Kr(pe,n?2:1,a+X/i,t)}Z+=re,ee+=re+4}}a+=$/i}}))})})}),t}function Bi(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Xc(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Kr(a,e,t,s){const i=co(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 u=r;if(o<l)r+=o;else if(o>l){ce.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(n===4){if(i[u++]===181){const h=ro(i,u);if(u+=2,h===49){const g=Q(i,u);if(u+=4,g===1195456820){const f=i[u++];if(f===3){const y=i[u++],E=31&y,v=64&y,T=v?2+E*3:0,S=new Uint8Array(T);if(v){S[0]=y;for(let x=1;x<T;x++)S[x]=i[u++]}s.push({type:f,payloadType:n,pts:t,bytes:S})}}}}}else if(n===5&&o>16){const d=[];for(let f=0;f<16;f++){const y=i[u++].toString(16);d.push(y.length==1?"0"+y:y),(f===3||f===5||f===7||f===9)&&d.push("-")}const h=o-16,g=new Uint8Array(h);for(let f=0;f<h;f++)g[f]=i[u++];s.push({payloadType:n,pts:t,uuid:d.join(""),userData:tt(g),userDataBytes:g})}}}function co(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 Qc(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,c=0,l=0;if(e===0){for(;Pe(a.subarray(l,l+1))!=="\0";)t+=Pe(a.subarray(l,l+1)),l+=1;for(t+=Pe(a.subarray(l,l+1)),l+=1;Pe(a.subarray(l,l+1))!=="\0";)s+=Pe(a.subarray(l,l+1)),l+=1;s+=Pe(a.subarray(l,l+1)),l+=1,i=Q(a,12),r=Q(a,16),o=Q(a,20),c=Q(a,24),l=28}else if(e===1){l+=4,i=Q(a,l),l+=4;const d=Q(a,l);l+=4;const h=Q(a,l);for(l+=4,n=2**32*d+h,Rc(n)||(n=Number.MAX_SAFE_INTEGER,ce.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Q(a,l),l+=4,c=Q(a,l),l+=4;Pe(a.subarray(l,l+1))!=="\0";)t+=Pe(a.subarray(l,l+1)),l+=1;for(t+=Pe(a.subarray(l,l+1)),l+=1;Pe(a.subarray(l,l+1))!=="\0";)s+=Pe(a.subarray(l,l+1)),l+=1;s+=Pe(a.subarray(l,l+1)),l+=1}const u=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:c,payload:u}}function Zc(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 Jc(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),Zc([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t)}function eu(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=tu(i);e.push(r),s+=r.size}}return e}function tu(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=Be(new Uint8Array(n,t+12,16));let c=null,l=null,u=0;if(r===0)u=28;else{const h=a.getUint32(28);if(!h||s<32+h*16)return{offset:t,size:e};c=[];for(let g=0;g<h;g++)c.push(new Uint8Array(n,t+32+g*16,16));u=32+h*16}if(!u)return{offset:t,size:e};const d=a.getUint32(u);return e-32<d?{offset:t,size:e}:(l=new Uint8Array(n,t+u+4,d),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const uo=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),xs={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 Hr(a,e){const t=xs[e];return!!t&&!!t[a.slice(0,4)]}function Vs(a,e,t=!0){return!a.split(",").some(s=>!Yr(s,e,t))}function Yr(a,e,t=!0){var s;const i=Kt(t);return(s=i==null?void 0:i.isTypeSupported(Ks(a,e)))!=null?s:!1}function Ks(a,e){return`${e}/mp4;codecs=${a}`}function $n(a){if(a){const e=a.substring(0,4);return xs.video[e]}return 2}function bi(a){const e=uo();return a.split(",").reduce((t,s)=>{const r=e&&Bi(s)?9:xs.video[s];return r?(r*2+t)/(t?3:2):(xs.audio[s]+t)/(t?2:1)},0)}const Zi={};function su(a,e=!0){if(Zi[a])return Zi[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(Yr(t[i],"audio",e))return Zi[a]=t[i],t[i];if(t[i]==="mp3"&&(s=Kt(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const iu=/flac|opus|mp4a\.40\.34/i;function Ri(a,e=!0){return a.replace(iu,t=>su(t.toLowerCase(),e))}function ru(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)Hr(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function Ei(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(Gn(a,"audio")||Gn(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 Gn(a,e){return Hr(a,e)&&Yr(a,e)}function nu(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 au(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 Vn(a){const e=Kt(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 Ar(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const ou={supported:!0,powerEfficient:!0,smooth:!0},lu={supported:!1,smooth:!1,powerEfficient:!1},ho={supported:!0,configurations:[],decodingInfoResults:[ou]};function fo(a,e){return{supported:!1,configurations:e,decodingInfoResults:[lu],error:a}}function cu(a,e,t,s,i,r){const n=a.videoCodec,o=a.audioCodec?a.audioGroups:null,c=r==null?void 0:r.audioCodec,l=r==null?void 0:r.channels,u=l?parseInt(l):c?1/0:2;let d=null;if(o!=null&&o.length)try{o.length===1&&o[0]?d=e.groups[o[0]].channels:d=o.reduce((h,g)=>{if(g){const f=e.groups[g];if(!f)throw new Error(`Audio track group ${g} not found`);Object.keys(f.channels).forEach(y=>{h[y]=(h[y]||0)+f.channels[y]})}return h},{2:0})}catch{return!0}return n!==void 0&&(n.split(",").some(h=>Bi(h))||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))||!!d&&G(u)&&Object.keys(d).some(h=>parseInt(h)>u)}function go(a,e,t,s={}){const i=a.videoCodec;if(!i&&!a.audioCodec||!t)return Promise.resolve(ho);const r=[],n=uu(a),o=n.length,c=du(a,e,o>0),l=c.length;for(let u=o||1*l||1;u--;){const d={type:"media-source"};if(o&&(d.video=n[u%o]),l){d.audio=c[u%l];const h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}r.push(d)}if(i){const u=navigator.userAgent;if(i.split(",").some(d=>Bi(d))&&uo())return Promise.resolve(fo(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),r))}return Promise.all(r.map(u=>{const d=fu(u);return s[d]||(s[d]=t.decodingInfo(u))})).then(u=>({supported:!u.some(d=>!d.supported),configurations:r,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:r,decodingInfoResults:[],error:u}))}function uu(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),s=mo(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:Ks(au(c),"video"),width:i,height:r,bitrate:s,framerate:n};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function du(a,e,t){var s;const i=(s=a.audioCodec)==null?void 0:s.split(","),r=mo(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((u,d)=>{if(d.groupId===o){const h=parseFloat(d.channels||"");i.forEach(g=>{const f={contentType:Ks(g,"audio"),bitrate:t?hu(g,r):r};h&&(f.channels=""+h),u.push(f)})}return u},n):n},[]):[]}function hu(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 mo(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function fu(a){let e="";const{audio:t,video:s}=a;if(s){const i=Ar(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=Ar(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const Lr=["NONE","TYPE-0","TYPE-1",null];function gu(a){return Lr.indexOf(a)>-1}const _i=["SDR","PQ","HLG"];function mu(a){return!!a&&_i.indexOf(a)>-1}var vi={No:"",Yes:"YES",v2:"v2"};function Kn(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?vi.v2:vi.Yes:vi.No}class Hn{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 Hs{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 Yn(this._audioGroups,e)}hasSubtitleGroup(e){return Yn(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 Yn(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function pu(){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 yu(a,e){let t=!1,s=[];
vendor: 4,735 bytes, line 1
1if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||_i.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&pu(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Eu=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}},ge=(a,e)=>JSON.stringify(a,Eu(e));function vu(a,e,t,s,i){const r=Object.keys(a),n=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,c=i==null?void 0:i.videoCodec,l=n&&parseInt(n)===2;let u=!1,d=!1,h=1/0,g=1/0,f=1/0,y=1/0,E=0,v=[];const{preferHDR:T,allowedVideoRanges:S}=yu(e,i);for(let p=r.length;p--;){const D=a[r[p]];u||(u=D.channels[2]>0),h=Math.min(h,D.minHeight),g=Math.min(g,D.minFramerate),f=Math.min(f,D.minBitrate),S.filter(k=>D.videoRanges[k]>0).length>0&&(d=!0)}h=G(h)?h:0,g=G(g)?g:0;const x=Math.max(1080,h),A=Math.max(30,g);f=G(f)?f:t,t=Math.max(f,t),d||(e=void 0);const P=r.length>1;return{codecSet:r.reduce((p,D)=>{const I=a[D];if(D===p)return p;if(v=d?S.filter(k=>I.videoRanges[k]>0):[],P){if(I.minBitrate>t)return yt(D,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),p;if(!I.hasDefaultAudio)return yt(D,"no renditions with default or auto-select sound found"),p;if(o&&D.indexOf(o.substring(0,4))%5!==0)return yt(D,`audio codec preference "${o}" not found`),p;if(n&&!l){if(!I.channels[n])return yt(D,`no renditions with ${n} channel sound found (channels options: ${Object.keys(I.channels)})`),p}else if((!o||l)&&u&&I.channels[2]===0)return yt(D,"no renditions with stereo sound found"),p;if(I.minHeight>x)return yt(D,`min resolution of ${I.minHeight} > maximum of ${x}`),p;if(I.minFramerate>A)return yt(D,`min framerate of ${I.minFramerate} > maximum of ${A}`),p;if(!v.some(k=>I.videoRanges[k]>0))return yt(D,`no variants with VIDEO-RANGE of ${ge(v)} found`),p;if(c&&D.indexOf(c.substring(0,4))%5!==0)return yt(D,`video codec preference "${c}" not found`),p;if(I.maxScore<E)return yt(D,`max score of ${I.maxScore} < selected max of ${E}`),p}return p&&(bi(D)>=bi(p)||I.fragmentError>a[p].fragmentError)?p:(y=I.minIndex,E=I.maxScore,D)},void 0),videoRanges:v,preferHDR:T,minFramerate:g,minBitrate:f,minIndex:y}}function yt(a,e){ce.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function po(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 Tu(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(u=>{if(!u)return;const d=e.groups[u];!d||(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?d.hasDefault:d.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(d.channels).forEach(h=>{c.channels[h]=(c.channels[h]||0)+d.channels[h]}))}),i},{})}function Wn(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 xt(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(es(a,i,t))return s}return-1}function es(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||Su(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in a)||xu(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function Su(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function xu(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function Jt(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 Au(a,e,t,s,i){const r=e[s],o=e.reduce((h,g,f)=>{const y=g.uri;
vendor: 5,715 bytes, lines 1-11
1return(h[y]||(h[y]=[])).push(f),h},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,u=r.codecSet.substring(0,4),d=qn(e,s,h=>{if(h.videoRange!==c||h.frameRate!==l||h.codecSet.substring(0,4)!==u)return!1;const g=h.audioGroups,f=t.filter(y=>!g||g.indexOf(y.groupId)!==-1);return xt(a,f,i)>-1});return d>-1?d:qn(e,s,h=>{const g=h.audioGroups,f=t.filter(y=>!g||g.indexOf(y.groupId)!==-1);return xt(a,f,i)>-1})}function qn(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 Di(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Lu extends lt{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(),u=r?r.stats:i.stats,d=r?r.duration:i.duration,h=l-u.loading.start,g=n.minAutoLevel,f=i.level,y=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||f<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const E=y>-1&&y!==f,v=!!t||E;if(!v&&(c.paused||!c.playbackRate||!c.readyState))return;const T=n.mainForwardBufferInfo;if(!v&&T===null)return;const S=this.bwEstimator.getEstimateTTFB(),x=Math.abs(c.playbackRate);if(h<=Math.max(S,1e3*(d/(x*2))))return;const A=T?T.len/x:0,P=u.loading.first?u.loading.first-u.loading.start:-1,L=u.loaded&&P>-1,p=this.getBwEstimate(),D=n.levels,I=D[f],k=Math.max(u.loaded,Math.round(d*(i.bitrate||I.averageBitrate)/8));let N=L?h-P:h;N<1&&L&&(N=Math.min(h,u.loaded*8/p));const B=L?u.loaded*1e3/N:0,Y=S/1e3,$=B?(k-u.loaded)/B:k*8/p+Y;if($<=A)return;const O=B?B*8:p,V=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,U=this.hls.config.abrBandWidthUpFactor;let H=Number.POSITIVE_INFINITY,X;for(X=f-1;X>g;X--){const ae=D[X].maxBitrate,ee=!D[X].details||V;if(H=this.getTimeToLoadFrag(Y,O,d*ae,ee),H<Math.min(A,d+Y))break}if(H>=$||H>d*10)return;L?this.bwEstimator.sample(h-Math.min(S,P),u.loaded):this.bwEstimator.sampleTTFB(h);const M=D[X].maxBitrate;this.getBwEstimate()*U>M&&this.resetEstimator(M);const F=this.findBestLevel(M,g,X,0,A,1,1);F>-1&&(X=F),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly;
2      Fragment duration: ${i.duration.toFixed(3)}
3      Time to underbuffer: ${A.toFixed(3)} s
4      Estimated load time for current fragment: ${$.toFixed(3)} s
5      Estimated load time for down switch fragment: ${H.toFixed(3)} s
6      TTFB estimate: ${P|0} ms
7      Current BW estimate: ${G(p)?p|0:"Unknown"} bps
8      New BW estimate: ${this.getBwEstimate()|0} bps
9      Switching to level ${X} @ ${M|0} bps`),n.nextLoadLevel=n.nextAutoLevel=X,this.clearTimer();const Z=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===X&&X>0){const ae=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${X>0?"and switching down":""}
10      Fragment duration: ${i.duration.toFixed(3)} s
11      Time to underbuffer: ${ae.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,X>g){let ee=this.findBestLevel(this.hls.levels[g].bitrate,g,X,0,ae,1,1);ee===-1&&(ee=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ee,this.resetEstimator(this.hls.levels[ee].bitrate)}}};E||$>H*2?Z():this.timer=self.setInterval(Z,H*1e3),n.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Dc(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;!e||(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;
vendor: 3,234 bytes, line 11
11if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case _.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),o=r?r.stats:s.stats,c=n-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(d,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?e+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;G(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===K.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,c=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:c},n.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==K.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}
11_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let u=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const E=this.findBestLevel(c,n,i,l,0,u,d);if(E>=0)return this.rebufferNotice=-1,E}let h=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const E=this.bitrateTestDelay;E&&(h=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-E,this.info(`bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=d=1)}const g=this.findBestLevel(c,n,i,l,h,u,d);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const f=s.levels[n],y=s.loadLevelObj;return y&&(f==null?void 0:f.bitrate)<y.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,o){var c;const l=i+r,u=this.lastLoadedFragLevel,d=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:g}=this,{levels:f,allAudioTracks:y,loadLevel:E,config:v}=this.hls;if(f.length===1)return 0;const T=f[d],S=!!((c=this.hls.latestLevelDetails)!=null&&c.live),x=E===-1||u===-1;let A,P="SDR",L=(T==null?void 0:T.frameRate)||0;const{audioPreference:p,videoPreference:D}=v,I=this.audioTracksByGroup||(this.audioTracksByGroup=po(y));let k=-1;if(x){if(this.firstSelection!==-1)return this.firstSelection;const O=this.codecTiers||(this.codecTiers=Tu(f,I,t,s)),V=vu(O,P,e,p,D),{codecSet:U,videoRanges:H,minFramerate:X,minBitrate:M,minIndex:F,preferHDR:Z}=V;k=F,A=U,P=Z?H[H.length-1]:H[0],L=X,e=Math.max(e,M),this.log(`picked start tier ${ge(V)}`)}else A=T==null?void 0:T.codecSet,P=T==null?void 0:T.videoRange;const N=g?g.duration:h?h.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,Y=[];for(let O=s;O>=t;O--){var $;const V=f[O],U=O>d;if(!V)continue;if(v.useMediaCapabilities&&!V.supportedResult&&!V.supportedPromise){const ee=navigator.mediaCapabilities;typeof(ee==null?void 0:ee.decodingInfo)=="function"&&cu(V,I,P,L,e,p)?(V.supportedPromise=go(V,I,ee,this.supportedCache),V.supportedPromise.then(re=>{if(!this.hls)return;V.supportedResult=re;const pe=this.hls.levels,ve=pe.indexOf(V);re.error?this.warn(`MediaCapabilities decodingInfo error: "${re.error}" for level ${ve} ${ge(re)}`):re.supported?re.decodingInfoResults.some(_e=>_e.smooth===!1||_e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ve} not smooth or powerEfficient: ${ge(re)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ve} ${ge(re)}`),ve>-1&&pe.length>1&&(this.log(`Removing unsupported level ${ve}`),this.hls.removeLevel(ve),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(re=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${re}`)})):V.supportedResult=ho}if((A&&V.codecSet!==A||P&&V.videoRange!==P||U&&L>V.frameRate||!U&&L>0&&L<V.frameRate||($=V.supportedResult)!=null&&($=$.decodingInfoResults)!=null&&$.some(ee=>ee.smooth===!1))&&(!x||O!==k)){Y.push(O);continue}const H=V.details,X=(g?H==null?void 0:H.partTarget:H==null?void 0:H.averagetargetduration)||N;let M;U?M=o*e:M=n*e;const F=N&&i>=N*2&&r===0?V.averageBitrate:V.maxBitrate,Z=this.getTimeToLoadFrag(B,M,F*X,H===void 0);if(M>=F&&(O===u||V.loadError===0&&V.fragmentError===0)&&(Z<=B||!G(Z)||S&&!this.bitrateTestDelay||Z<l)){const ee=this.forcedAutoLevel;return O!==E&&(ee===-1||ee!==E)&&(Y.length&&this.trace(`Skipped level(s) ${Y.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[Y[0]].codecs}" ${f[Y[0]].videoRange}; not compatible with "${A}" ${P}`),this.info(`switch candidate:${d}->${O} adjustedbw(${Math.round(M)})-bitrate=${Math.round(M-F)} ttfb:${B.toFixed(1)} avgDuration:${X.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${Z.toFixed(1)}
11 firstSelection:${x} codecSet:${V.codecSet} videoRange:${V.videoRange} hls.loadLevel:${E}`)),x&&(this.firstSelection=O),O}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const yo={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function Iu(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!G(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<a.length;++r){const n=a[r];if(Ru(e,t,n))return n}return null}function ts(a,e,t=0,s=0,i=.005){let r=null;if(a){r=e[1+a.sn-e[0].sn]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&a.level!==r.level&&r.end<=a.end&&(r=e[2+a.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!a||a.level===r.level)&&jn(t,s,r)===0||bu(r,a,Math.min(i,s))))return r;const n=yo.search(e,jn.bind(null,t,s));return n&&(n!==a||!r)?n:r}function bu(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return a.start<=s}return!1}function jn(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function Ru(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function Eo(a,e,t){if(a&&a.startCC<=e&&a.endCC>=e){let s=a.fragments;const{fragmentHint:i}=a;i&&(s=s.concat(i));let r;return yo.search(s,n=>n.cc<e?1:n.cc>e?-1:(r=n,n.end<=t?1:n.start>t?-1:0)),r||null}return null}function Ci(a){switch(a.details){case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_TIMEOUT:case _.LEVEL_LOAD_TIMEOUT:case _.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function vo(a){return a.details.startsWith("key")}function To(a){return vo(a)&&!!a.frag&&!a.frag.decryptdata}function zn(a,e){const t=Ci(e);return a.default[`${t?"timeout":"error"}Retry`]}function Wr(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function Xn(a){return le(le({},a),{errorRetry:null,timeoutRetry:null})}function Pi(a,e,t,s){if(!a)return!1;const i=s==null?void 0:s.code,r=e<a.maxNumRetry&&(_u(i)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,s,r):r}function _u(a){return Ir(a)||!!a&&(a<400||a>499)}function Ir(a){return a===0&&navigator.onLine===!1}var Ne={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ze={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class Du extends lt{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;!e||(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===K.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(n=>i.indexOf(n.groupId)>=0).some(n=>{var o;return(o=n.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case _.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Es();return}case _.FRAG_GAP:case _.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ne.SendAlternateToPenaltyBox;return}case _.LEVEL_EMPTY_ERROR:case _.LEVEL_PARSING_ERROR:{var n;const c=t.parent===K.MAIN?t.level:i.loadLevel;t.details===_.LEVEL_EMPTY_ERROR&&!!((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:typeof(r==null?void 0:r.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.SUBTITLE_LOAD_ERROR:case _.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=i.loadLevelObj;if(c&&(r.type===ie.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===ie.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ne.SendAlternateToPenaltyBox,t.errorAction.flags=Ze.MoveAllAlternatesMatchingHost;return}}return;case _.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ne.SendAlternateToPenaltyBox,flags:Ze.MoveAllAlternatesMatchingHDCP};return;case _.KEY_SYSTEM_SESSION_UPDATE_FAILED:case _.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case _.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ne.SendAlternateToPenaltyBox,flags:Ze.MoveAllAlternatesMatchingKey};return;
vendor: 11,096 bytes, line 11
11case _.BUFFER_ADD_CODEC_ERROR:case _.REMUX_ALLOC_ERROR:case _.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case _.INTERNAL_EXCEPTION:case _.BUFFER_APPENDING_ERROR:case _.BUFFER_FULL_ERROR:case _.LEVEL_SWITCH_ERROR:case _.BUFFER_STALLED_ERROR:case _.BUFFER_SEEK_OVER_HOLE:case _.BUFFER_NUDGE_ON_STALL:t.errorAction=Es();return}t.type===W.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Es())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=zn(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(Pi(i,r,Ci(e),e.response))return{action:Ne.RetryRequest,flags:Ze.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=zn(vo(e)?n:r,e),c=t.levels.reduce((u,d)=>u+d.fragmentError,0);if(i&&(e.details!==_.FRAG_GAP&&i.fragmentError++,!To(e)&&Pi(o,c,Ci(e),e.response)))return{action:Ne.RetryRequest,flags:Ze.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const l=e.details;i.loadError++,l===_.BUFFER_APPEND_ERROR&&i.fragmentError++;let u=-1;const{levels:d,loadLevel:h,minAutoLevel:g,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const y=(r=e.frag)==null?void 0:r.type,v=(y===K.AUDIO&&l===_.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===_.BUFFER_ADD_CODEC_ERROR||l===_.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:P})=>i.audioCodec!==P),S=e.sourceBufferName==="video"&&(l===_.BUFFER_ADD_CODEC_ERROR||l===_.BUFFER_APPEND_ERROR)&&d.some(({codecSet:P,audioCodec:L})=>i.codecSet!==P&&i.audioCodec===L),{type:x,groupId:A}=(n=e.context)!=null?n:{};for(let P=d.length;P--;){const L=(P+h)%d.length;if(L!==h&&L>=g&&L<=f&&d[L].loadError===0){var o,c;const p=d[L];if(l===_.FRAG_GAP&&y===K.MAIN&&e.frag){const D=d[L].details;if(D){const I=ts(e.frag,D.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(x===ie.AUDIO_TRACK&&p.hasAudioGroup(A)||x===ie.SUBTITLE_TRACK&&p.hasSubtitleGroup(A))continue;if(y===K.AUDIO&&(o=i.audioGroups)!=null&&o.some(D=>p.hasAudioGroup(D))||y===K.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(D=>p.hasSubtitleGroup(D))||v&&i.audioCodec===p.audioCodec||S&&i.codecSet===p.codecSet||!v&&i.codecSet!==p.codecSet)continue}u=L;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Ne.SendAlternateToPenaltyBox,flags:Ze.None,nextAutoLevel:u}}return{action:Ne.SendAlternateToPenaltyBox,flags:Ze.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ne.DoNothing:break;case Ne.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==_.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ze.None:this.switchLevel(e,r);break;case Ze.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],u=l==null?void 0:l.attrs["HDCP-LEVEL"];if(s.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){t.maxHdcpLevel=Lr[Lr.indexOf(u)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ze.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,u=l.length;for(let h=u;h--;)if(this.variantHasKey(l[h],c)){var n,o;this.log(`Banned key found in level ${h} (${l[h].bitrate}bps) or audio group "${(n=l[h].audioGroups)==null?void 0:n.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Be(c.keyId||[])}`),l[h].fragmentError++,l[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const d=e.frag;if(this.hls.levels.length<u)s.resolved=!0;else if(d&&d.type!==K.MAIN){const h=d.decryptdata;h&&!c.matches(h)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===_.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Ar(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function Es(a){const e={action:Ne.DoNothing,flags:Ze.None};return a&&(e.resolved=!0),e}var ke={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Cu{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const o=i[r[n]];if((o==null?void 0:o.body.type)===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||n>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(!!l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(u=>{const d=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return d&&this.removeFragment(c.body),d})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=us(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],u=n||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,u,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),ri(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];!s||(this.activePartLists[t]=Qn(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=us(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||n;for(let u=0;u<i.length;u++){const d=i.start(u)-this.bufferPadding,h=i.end(u)+this.bufferPadding;if(l>=d&&c<=h){r.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(o,i.end(u))});break}else if(n<h&&o>d){const g=Math.max(n,i.start(u)),f=Math.min(o,i.end(u));f>g&&(r.partial=!0,r.time.push({startPTS:g,endPTS:f}))}else if(o<=d)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const u=c[l];!u||ri(u)&&(i=u.body.start-o,r=u.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=u.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||ri(t))}getState(e){const t=us(e),s=this.fragments[t];return s?s.buffered?ri(s)?ke.PARTIAL:ke.OK:ke.APPENDING:ke.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=us(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const c=r[n];this.detectEvictedFragments(n,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=us(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((r==null?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=us(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Qn(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function ri(a){var e,t,s;return a.buffered&&!!(a.body.gap||(e=a.range.video)!=null&&e.partial||(t=a.range.audio)!=null&&t.partial||(s=a.range.audiovideo)!=null&&s.partial)}function us(a){return`${a.type}_${a.level}_${a.sn}`}function Qn(a,e){return a.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Ht={cbc:0,ctr:1};class Pu{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Ht.cbc:return this.subtle.decrypt({
vendor: 19,610 bytes, line 11
11name:"AES-CBC",iv:this.aesIV},t,e);case Ht.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function ku(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?a.slice(0,e-t):a}class wu{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],o=s[3],c=this.invSubMix,l=c[0],u=c[1],d=c[2],h=c[3],g=new Uint32Array(256);let f=0,y=0,E=0;for(E=0;E<256;E++)E<128?g[E]=E<<1:g[E]=E<<1^283;for(E=0;E<256;E++){let v=y^y<<1^y<<2^y<<3^y<<4;v=v>>>8^v&255^99,e[f]=v,t[v]=f;const T=g[f],S=g[T],x=g[S];let A=g[v]*257^v*16843008;i[f]=A<<24|A>>>8,r[f]=A<<16|A>>>16,n[f]=A<<8|A>>>24,o[f]=A,A=x*16843009^S*65537^T*257^f*16843008,l[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,d[v]=A<<8|A>>>24,h[v]=A,f?(f=T^g[g[g[x^T]]],y^=g[g[y]]):f=y=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(n),u=this.invKeySchedule=new Uint32Array(n),d=this.sBox,h=this.rcon,g=this.invSubMix,f=g[0],y=g[1],E=g[2],v=g[3];let T,S;for(o=0;o<n;o++){if(o<r){T=l[o]=t[o];continue}S=T,o%r===0?(S=S<<8|S>>>24,S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255],S^=h[o/r|0]<<24):r>6&&o%r===4&&(S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255]),l[o]=T=(l[o-r]^S)>>>0}for(c=0;c<n;c++)o=n-c,c&3?S=l[o]:S=l[o-4],c<4||o<=4?u[c]=S:u[c]=f[d[S>>>24]]^y[d[S>>>16&255]]^E[d[S>>>8&255]]^v[d[S&255]],u[c]=u[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],u=o[2],d=o[3],h=this.uint8ArrayToUint32Array_(s);let g=h[0],f=h[1],y=h[2],E=h[3];const v=new Int32Array(e),T=new Int32Array(v.length);let S,x,A,P,L,p,D,I,k,N,B,Y,$,O;const V=this.networkToHostOrderSwap;for(;t<v.length;){for(k=V(v[t]),N=V(v[t+1]),B=V(v[t+2]),Y=V(v[t+3]),L=k^r[0],p=Y^r[1],D=B^r[2],I=N^r[3],$=4,O=1;O<i;O++)S=c[L>>>24]^l[p>>16&255]^u[D>>8&255]^d[I&255]^r[$],x=c[p>>>24]^l[D>>16&255]^u[I>>8&255]^d[L&255]^r[$+1],A=c[D>>>24]^l[I>>16&255]^u[L>>8&255]^d[p&255]^r[$+2],P=c[I>>>24]^l[L>>16&255]^u[p>>8&255]^d[D&255]^r[$+3],L=S,p=x,D=A,I=P,$=$+4;S=n[L>>>24]<<24^n[p>>16&255]<<16^n[D>>8&255]<<8^n[I&255]^r[$],x=n[p>>>24]<<24^n[D>>16&255]<<16^n[I>>8&255]<<8^n[L&255]^r[$+1],A=n[D>>>24]<<24^n[I>>16&255]<<16^n[L>>8&255]<<8^n[p&255]^r[$+2],P=n[I>>>24]<<24^n[L>>16&255]<<16^n[p>>8&255]<<8^n[D&255]^r[$+3],T[t]=V(S^g),T[t+1]=V(P^f),T[t+2]=V(A^y),T[t+3]=V(x^E),g=k,f=N,y=B,E=Y,t=t+4}return T.buffer}}class Ou{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Mu(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Mu(a){switch(a){case Ht.cbc:return"AES-CBC";case Ht.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const Fu=16;class qr{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?ku(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?r(c.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:o}=this;if(i!==Ht.cbc||t.byteLength!==16)return ce.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=ot(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new wu),l.expandKey(t);const u=n;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Ou(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Pu(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(ce.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%Fu;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){!this.logEnabled||(ce.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Zn=Math.pow(2,17);class Nu{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new kt({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){c(ea(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new n(i),u=Jn(e);e.loader=l;const d=Xn(i.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Zn};e.stats=l.stats;const g={onSuccess:(f,y,E,v)=>{this.resetLoader(e,l);let T=f.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:v})},onError:(f,y,E,v)=>{this.resetLoader(e,l),c(new kt({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:le({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:E,stats:v}))},onAbort:(f,y,E)=>{this.resetLoader(e,l),c(new kt({type:W.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:f}))},onTimeout:(f,y,E)=>{this.resetLoader(e,l),c(new kt({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:E,stats:f}))}};t&&(g.onProgress=(f,y,E,v)=>t({frag:e,part:null,payload:E,networkDetails:v})),l.load(u,h,g)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(ea(e,t));return}const l=this.loader=r?new r(i):new n(i),u=Jn(e,t);e.loader=l;const d=Xn(i.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Zn};t.stats=l.stats,l.load(u,h,{onSuccess:(g,f,y,E)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:g.data,networkDetails:E};s(v),o(v)},onError:(g,f,y,E)=>{this.resetLoader(e,l),c(new kt({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:le({url:u.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:y,stats:E}))},onAbort:(g,f,y)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new kt({type:W.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:y,stats:g}))},onTimeout:(g,f,y)=>{this.resetLoader(e,l),c(new kt({type:W.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:y,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),d=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+d}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Jn(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(G(i)&&G(r)){var n;let o=i,c=r;if(a.sn==="initSegment"&&Bu((n=a.decryptdata)==null?void 0:n.method)){const l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function ea(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),s={type:W.MEDIA_ERROR,details:_.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new kt(s)}function Bu(a){return a==="AES-128"||a==="AES-256"}class kt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class So extends lt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class jr{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=ni(),this.buffering={audio:ni(),video:ni(),audiovideo:ni()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function ni(){return{start:0,executeStart:0,executeEnd:0,end:0}}const ta={length:0,start:()=>0,end:()=>0};class J{static isBuffered(e,t){if(e){const s=J.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=J.getBuffered(e);return J.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=J.bufferedRanges(e);if(i.length)return J.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((u,d)=>u.start-d.start||d.end-u.end);let i=-1,r=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(i=u);const d=r.length;if(d){const h=r[d-1].end;e[u].start-h<s?e[u].end>h&&(r[d-1].end=e[u].end):r.push(e[u])}else r.push(e[u])}else r=e;let n=0,o,c=t,l=t;for(let u=0;u<r.length;u++){const d=r[u].start,h=r[u].end;if(i===-1&&t>=d&&t<=h&&(i=u),t+s>=d&&t<h)c=d,l=h,n=l-t;else if(t+s<d){o=d;break}}return{len:n,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||ta}catch(t){return ce.log("failed to get media.buffered",t),ta}}}const xo=/\{\$([a-zA-Z0-9-_]+)\}/g;function sa(a){return xo.test(a)}function br(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(xo,s=>{const i=s.substring(2,s.length-1),r=t==null?void 0:t[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function ia(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${n.message}`))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function Uu(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const $u=/^(\d+)x(\d+)$/,ra=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ye{constructor(e,t){typeof e=="string"&&(e=ye.parseAttrList(e,t)),he(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=$u.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={},r='"';for(ra.lastIndex=0;(s=ra.exec(e))!==null;){const n=s[1].trim();let o=s[2];const c=o.indexOf(r)===0&&o.lastIndexOf(r)===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=br(t,o);else if(!l&&!c)switch(n){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ce.warn(`${e}: attribute ${n} is missing quotes`)}i[n]=o}return i}}const Gu="com.apple.hls.interstitial";function Vu(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Ku(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class Ao{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(i=t==null?void 0:t.tagOrder)!=null?i:s,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){ce.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=he(new ye({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);G(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(ce.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(G(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Gu}get isValid(){return!!this.id&&!this._badValueForSameId&&G(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const Hu=10;class Yu{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.drift
vendor: 4,535 bytes, line 11
11StartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?G(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Hu}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function ki(a,e){return a.length===e.length?!a.some((t,s)=>t!==e[s]):!1}function na(a,e){return!a&&!e?!0:!a||!e?!1:ki(a,e)}function vs(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function zr(a){switch(a){case"AES-128":case"AES-256":return Ht.cbc;case"AES-256-CTR":return Ht.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function Xr(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function Rr(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}function Wu(a){const e=Rr(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Lo(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function Io(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",n=i[1];r?(s.splice(-1,1),t=Xr(n)):t=Wu(n)}}return t}const wi=typeof self<"u"?self:void 0;var Ee={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ue={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ti(a){switch(a){case Ue.FAIRPLAY:return Ee.FAIRPLAY;case Ue.PLAYREADY:return Ee.PLAYREADY;case Ue.WIDEVINE:return Ee.WIDEVINE;case Ue.CLEARKEY:return Ee.CLEARKEY}}function Ji(a){switch(a){case Ee.FAIRPLAY:return Ue.FAIRPLAY;case Ee.PLAYREADY:return Ue.PLAYREADY;case Ee.WIDEVINE:return Ue.WIDEVINE;case Ee.CLEARKEY:return Ue.CLEARKEY}}function Bs(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[Ee.FAIRPLAY,Ee.WIDEVINE,Ee.PLAYREADY,Ee.CLEARKEY].filter(i=>!!e[i]):[];return!s[Ee.WIDEVINE]&&t&&s.push(Ee.WIDEVINE),s}const bo=function(a){return wi!=null&&(a=wi.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function qu(a,e,t,s){let i;switch(a){case Ee.FAIRPLAY:i=["cenc","sinf"];break;case Ee.WIDEVINE:case Ee.PLAYREADY:i=["cenc"];break;case Ee.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return ju(i,e,t,s)}function ju(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}
11`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function zu(a){var e;return!!a&&(a.sessionType==="persistent-license"||!!((e=a.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Ro(a){const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const o=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(o){const c=Xr(o).subarray(0,16);return Lo(c),c}}return null}let ds={};class Vt{static clearKeyUriToKeyIdMap(){ds={}}static setKeyIdForUri(e,t){ds[e]=t}static addKeyIdForUri(e){const t=Object.keys(ds).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),ds[e]=s,s}constructor(e,t,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!vs(e),n!=null&&n.startsWith("0x")&&(this.keyId=new Uint8Array(eo(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ki(e.keyFormatVersions,this.keyFormatVersions)&&na(e.iv,this.iv)&&na(e.keyId,this.keyId)}isSupported(){if(this.method){if(vs(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ue.FAIRPLAY:case Ue.WIDEVINE:case Ue.PLAYREADY:case Ue.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(vs(this.method)){let r=this.iv;return r||(typeof e!="number"&&(ce.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=Qu(e)),new Vt(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=ds[this.uri];if(r&&!ki(this.keyId,r)&&Vt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Io(this.uri);if(s)switch(this.keyFormat){case Ue.WIDEVINE:if(this.pssh=s,!this.keyId){const r=eu(s.buffer);if(r.length){var i;const n=r[0];this.keyId=(i=n.kids)!=null&&i.length?n.kids[0]:null}}this.keyId||(this.keyId=aa(t));break;case Ue.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Jc(r,null,s),this.keyId=Ro(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){const n=new Uint8Array(16);n.set(r,16-r.length),r=n}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=Xu(t),r||(r=aa(t),r||(r=ds[this.uri])),r&&(this.keyId=r,Vt.setKeyIdForUri(this.uri,r))}return this}}function Xu(a){const e=a==null?void 0:a[Ue.WIDEVINE];return e?e.keyId:null}function aa(a){const e=a==null?void 0:a[Ue.PLAYREADY];if(e){const t=Io(e.uri);if(t)return Ro(t)}return null}function Qu(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const oa=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,la=/#EXT-X-MEDIA:(.*)/g,Zu=/^#EXT(?:INF|-X-TARGETDURATION):/m,er=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ju=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class At{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Gr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Zu.test(e)}static parseMasterPlaylist(e,t){const s=sa(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(oa.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;(n=oa.exec(e))!=null;)if(n[1]){var o;const l=new ye(n[1],i),u=br(i,n[2]),d={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:At.resolve(u,t)},h=l.decimalResolution("RESOLUTION");h&&(d.width=h.width,d.height=h.height),da(l.CODECS,d);const g=l["SUPPLEMENTAL-CODECS"];g&&(d.supplemental={},da(g,d.supplemental)),(o=d.unknownCodecs)!=null&&o.length||r.push(d),i.levels.push(d)}else if(n[3]){const l=n[3],u=n[4];switch(l){case"SESSION-DATA":{const d=new ye(u,i),h=d["DATA-ID"];h&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[h]=d);break}case"SESSION-KEY":{const d=ca(u,t,i);d.encrypted&&d.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(d)):ce.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const d=new ye(u,i);ia(i,d,t)}break}case"CONTENT-STEERING":{const d=new ye(u,i);i.contentSteering={uri:At.resolve(d["SERVER-URI"],t),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=ua(u);break}}}const c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,o={AUDIO:n.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:n.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(la.lastIndex=0;(i=la.exec(e))!==null;){const l=new ye(i[1],s),u=l.TYPE;if(u){const d=o[u],h=r[u]||[];r[u]=h;const g=l.LANGUAGE,f=l["ASSOC-LANGUAGE"],y=l.CHANNELS,E=l.CHARACTERISTICS,v=l["INSTREAM-ID"],T={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:u,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?At.resolve(l.URI,t):""};if(f&&(T.assocLang=f),y&&(T.channels=y),E&&(T.characteristics=E),v&&(T.instreamId=v),d!=null&&d.length){const S=At.findGroup(d,T.groupId)||d[0];ha(T,S,"audioCodec"),ha(T,S,"textCodec")}h.push(T)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var o;const c={url:t},l=new Yu(t),u=l.fragments,d=[];let h=null,g=0,f=0,y=0,E=0,v=0,T=null,S=new Xi(i,c),x,A,P,L=-1,p=!1,D=null,I;if(er.lastIndex=0,l.m3u8=e,l.hasVariableRefs=sa(e),((o=er.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(x=er.exec(e))!==null;){p&&(p=!1,S=new Xi(i,c),S.playlistOffset=y,S.setStart(y),S.sn=g,S.cc=E,v&&(S.bitrate=v),S.level=s,h&&(S.initSegment=h,h.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),D&&(S.setByteRange(D),D=null)));const Y=x[1];if(Y){S.duration=parseFloat(Y);const $=(" "+x[2]).slice(1);S.title=$||null,S.tagList.push($?["INF",Y,$]:["INF",Y])}else if(x[3]){if(G(S.duration)){S.playlistOffset=y,S.setStart(y),P&&ga(S,P,l),S.sn=g,S.level=s,S.cc=E,u.push(S);const $=(" "+x[3]).slice(1);S.relurl=br(l,$),_r(S,T,d),T=S,y+=S.duration,g++,f=0,p=!0}}
vendor: 53,681 bytes, lines 11-16
11else{if(x=x[0].match(Ju),!x){ce.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<x.length&&x[A]===void 0;A++);const $=(" "+x[A]).slice(1),O=(" "+x[A+1]).slice(1),V=x[A+2]?(" "+x[A+2]).slice(1):null;switch($){case"BYTERANGE":T?S.setByteRange(O,T):S.setByteRange(O);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=O,S.tagList.push(["PROGRAM-DATE-TIME",O]),L===-1&&(L=u.length);break;case"PLAYLIST-TYPE":l.type&&Ct(l,$,x),l.type=O.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Ct(l,$,x):u.length>0&&ma(l,$,x),g=l.startSN=parseInt(O);break;case"SKIP":{l.skippedSegments&&Ct(l,$,x);const U=new ye(O,l),H=U.decimalInteger("SKIPPED-SEGMENTS");if(G(H)){l.skippedSegments+=H;for(let M=H;M--;)u.push(null);g+=H}const X=U.enumeratedString("RECENTLY-REMOVED-DATERANGES");X&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(X.split("	")));break}case"TARGETDURATION":l.targetduration!==0&&Ct(l,$,x),l.targetduration=Math.max(parseInt(O),1);break;case"VERSION":l.version!==null&&Ct(l,$,x),l.version=parseInt(O);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Ct(l,$,x),l.live=!1;break;case"#":(O||V)&&S.tagList.push(V?[O,V]:[O]);break;case"DISCONTINUITY":E++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([$]);break;case"BITRATE":S.tagList.push([$,O]),v=parseInt(O)*1e3,G(v)?S.bitrate=v:v=0;break;case"DATERANGE":{const U=new ye(O,l),H=new Ao(U,l.dateRanges[U.ID],l.dateRangeTagCount);l.dateRangeTagCount++,H.isValid||l.skippedSegments?l.dateRanges[H.id]=H:ce.warn(`Ignoring invalid DATERANGE tag: "${O}"`),S.tagList.push(["EXT-X-DATERANGE",O]);break}case"DEFINE":{{const U=new ye(O,l);"IMPORT"in U?Uu(l,U,n):ia(l,U,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Ct(l,$,x):u.length>0&&ma(l,$,x),l.startCC=E=parseInt(O);break;case"KEY":{const U=ca(O,t,l);if(U.isSupported()){if(U.method==="NONE"){P=void 0;break}P||(P={});const H=P[U.keyFormat];H!=null&&H.matches(U)||(H&&(P=he({},P)),P[U.keyFormat]=U)}else ce.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${O}"`);break}case"START":l.startTimeOffset=ua(O);break;case"MAP":{const U=new ye(O,l);if(S.duration){const H=new Xi(i,c);fa(H,U,s,P),h=H,S.initSegment=h,h.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime)}else{const H=S.byteRangeEndOffset;if(H){const X=S.byteRangeStartOffset;D=`${H-X}@${X}`}else D=null;fa(S,U,s,P),h=S,p=!0}h.cc=E;break}case"SERVER-CONTROL":{I&&Ct(l,$,x),I=new ye(O),l.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),l.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&Ct(l,$,x);const U=new ye(O);l.partTarget=U.decimalFloatingPoint("PART-TARGET");break}case"PART":{let U=l.partList;U||(U=l.partList=[]);const H=f>0?U[U.length-1]:void 0,X=f++,M=new ye(O,l),F=new Uc(M,S,c,X,H);U.push(F),S.duration+=F.duration;break}case"PRELOAD-HINT":{const U=new ye(O,l);l.preloadHint=U;break}case"RENDITION-REPORT":{const U=new ye(O,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(U);break}default:ce.warn(`line parsed but not handled: ${x}`);break}}}T&&!T.relurl?(u.pop(),y-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(_r(S,T,d),S.cc=E,l.fragmentHint=S,P&&ga(S,P,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const k=u.length,N=u[0],B=u[k-1];if(y+=l.skippedSegments*l.targetduration,y>0&&k&&B){l.averagetargetduration=y/k;const Y=B.sn;l.endSN=Y!=="initSegment"?Y:0,l.live||(B.endList=!0),L>0&&(td(u,L),N&&d.unshift(N))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,d.length&&l.dateRangeTagCount&&N&&_o(d,l),l.endCC=E,l}}function _o(a,e){let t=a.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];a.push(o),t++}else return;const s=a[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let u=t;u--;){var n;if(((n=a[u])==null?void 0:n.sn)<e.startSN)break;const d=ed(e,l,a,u,i);if(d!==-1){c.tagAnchor=e.fragments[d].ref;break}}}}function ed(a,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var n;const c=(((n=t[s+1])==null?void 0:n.start)||i)-r.start;if(e<=o+c*1e3){const l=t[s].sn-a.startSN;if(l<0)return-1;const u=a.fragments;if(u.length>t.length){const h=(t[s+1]||u[u.length-1]).sn-a.startSN;for(let g=h;g>l;g--){const f=u[g].programDateTime;if(e>=f&&e<f+u[g].duration*1e3)return g}}return l}}}return-1}function ca(a,e,t){var s,i;const r=new ye(a,t),n=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,u=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&ce.error(`Invalid IV: ${r.IV}`);const d=o?At.resolve(o,e):"",h=(l||"1").split("/").map(Number).filter(Number.isFinite);return new Vt(n,d,u,h,c,r.KEYID)}function ua(a){const t=new ye(a).decimalFloatingPoint("TIME-OFFSET");return G(t)?t:null}function da(a,e){let t=(a||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>Hr(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function ha(a,e,t){const s=e[t];s&&(a[t]=s)}function td(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function _r(a,e,t){a.rawProgramDateTime?t.push(a):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime)}function fa(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function ga(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}function Ct(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function ma(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function tr(a,e){const t=e.startPTS;if(G(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.setStart(a.start+(a.minEndPTS-a.start)):e.setStart(a.start+a.duration):e.setStart(Math.max(a.start-e.duration,0))}function Do(a,e,t,s,i,r,n){s-t<=0&&(n.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s;const u=e.startPTS,d=e.endPTS;if(G(u)){const v=Math.abs(u-t);a&&v>a.totalduration?n.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${a.url}`):G(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,c=Math.max(t,u),t=Math.min(t,u),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,d),s=Math.max(s,d),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const g=e.sn;if(!a||g<a.startSN||g>a.endSN)return 0;let f;const y=g-a.startSN,E=a.fragments;for(E[y]=e,f=y;f>0;f--)tr(E[f],E[f-1]);for(f=y;f<E.length-1;f++)tr(E[f],E[f+1]);return a.fragmentHint&&tr(E[E.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,h}function sd(a,e,t){if(a===e)return;let s=null;const i=a.fragments;for(let u=i.length-1;u>=0;u--){const d=i[u].initSegment;if(d){s=d;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let r;nd(a,e,(u,d,h,g)=>{if((!e.startCC||e.skippedSegments)&&d.cc!==u.cc){const f=u.cc-d.cc;for(let y=h;y<g.length;y++)g[y].cc+=f;e.endCC=g[g.length-1].cc}G(u.startPTS)&&G(u.endPTS)&&(d.setStart(d.startPTS=u.startPTS),d.startDTS=u.startDTS,d.maxStartPTS=u.maxStartPTS,d.endPTS=u.endPTS,d.endDTS=u.endDTS,d.minEndPTS=u.minEndPTS,d.setDuration(u.endPTS-u.startPTS),d.duration&&(r=d),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(d.elementaryStreams=u.elementaryStreams),d.loader=u.loader,u.hasStats&&(d.stats=u.stats),u.initSegment&&(d.initSegment=u.initSegment,s=u.initSegment)});const n=e.fragments,o=e.fragmentHint?n.concat(e.fragmentHint):n;if(s&&o.forEach(u=>{var d;u&&(!u.initSegment||u.initSegment.relurl===((d=s)==null?void 0:d.relurl))&&(u.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=n.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)n.shift();e.startSN=n[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=id(a.dateRanges,e,t));const u=a.fragments.filter(d=>d.rawProgramDateTime);if(a.hasProgramDateTime&&!e.hasProgramDateTime)for(let d=1;d<o.length;d++)o[d].programDateTime===null&&_r(o[d],o[d-1],u);_o(u,e)}e.endCC=n[n.length-1].cc}if(!e.startCC){var c;const u=ko(a,e.startSN-1);e.startCC=(c=u==null?void 0:u.cc)!=null?c:n[0].cc}rd(a.partList,e.partList,(u,d)=>{d.elementaryStreams=u.elementaryStreams,d.stats=u.stats}),r?Do(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Co(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const u=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=u),e.driftEndTime=l,e.driftEnd=u}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=a.requestScheduled)}function id(a,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=he({},a);i&&i.forEach(c=>{delete r[c]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{const l=r[c],u=new Ao(s[c].attr,l);u.isValid?(r[c]=u,l||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ge(s[c].attr)}"`)}),r):s}function rd(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function nd(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=i;l<=r;l++){const u=c[n+l];let d=o[l];if(s&&!d&&u&&(d=e.fragments[l]=u),u&&d){t(u,d,l,o);const h=u.relurl,g=d.relurl;if(h&&ad(h,g)){e.playlistParsingError=pa(`media sequence mismatch ${d.sn}:`,a,e,u,d);return}else if(u.cc!==d.cc){e.playlistParsingError=pa(`discontinuity sequence mismatch (${u.cc}!=${d.cc})`,a,e,u,d);return}}}}function pa(a,e,t,s,i){return new Error(`${a} ${i.url}
12Playlist starting @${e.startSN}
13${e.m3u8}
14
15Playlist starting @${t.startSN}
16${t.m3u8}`)}function Co(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;Dr(e,n)}function Dr(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 Po(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments,i=4;if(s.length&&t*i>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function ko(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 ya(a,e,t){return a?wo(a.partList,e,t):null}function wo(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 Oo(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 ad(a,e){return a!==e&&e?Ea(a)!==Ea(e):!1}function Ea(a){return a.replace(/\?[^?]*$/,"")}function Us(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 od(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function va(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function Mo(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)va(t[s],a);e.fragmentHint&&va(e.fragmentHint,a),e.alignedSliding=!0}function ld(a,e){!a||(Fo(e,a),e.alignedSliding||Oi(e,a),!e.alignedSliding&&!e.skippedSegments&&Co(a,e,!1))}function Fo(a,e){if(!od(e,a))return;const t=Math.min(e.endCC,a.endCC),s=Us(e.fragments,t),i=Us(a.fragments,t);if(!s||!i)return;ce.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;Mo(r,a)}function Oi(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=Us(s,n),r=Us(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Us(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);Mo(l,a)}function He(a,e,t){je(a,e,t),a.addEventListener(e,t)}function je(a,e,t){a.removeEventListener(e,t)}const cd={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}},w={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 Qr extends So{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=w.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:u}=this,d=c?c.currentTime:0,h=J.bufferInfo(l||c,d,n.maxBufferHole),g=!h.len;if(this.log(`Media seeking to ${G(d)?d.toFixed(3):d}, state: ${u}, ${g?"out of":"in"} buffer`),this.state===w.ENDED)this.resetLoadingState();else if(o){const f=n.maxFragLookUpTolerance,y=o.start-f,E=o.start+o.duration+f;if(g||E<h.start||y>h.end){const v=d>E;(d<y||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);const f=this.lastCurrentTime;if(d>f&&(this.lastCurrentTime=d),!this.loadingParts){const y=Math.max(h.end,d),E=this.shouldLoadParts(this.getLevelDetails(),y);E&&(this.log(`LL-Part loading ON after seeking to ${d.toFixed(2)} with buffer @${y.toFixed(2)}`),this.loadingParts=E)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,g&&(this.startPosition=d)),g&&this.state===w.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 Nu(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new qr(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===w.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=w.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=J.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 u=c[c.length-1];return J.isBuffered(this.media,u.start+u.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;He(s,"seeking",this.onMediaSeeking),He(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===w.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),je(i,"seeking",this.onMediaSeeking),je(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=w.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===w.FRAG_LOADING||!this.fragCurrent&&n===w.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=w.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===w.STOPPED||this.state===w.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===ke.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)===ke.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==null?void 0: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==null?void 0: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&&vs(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,zr(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const u=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:u}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===w.STOPPED||this.state===w.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!==w.STOPPED&&(this.state=w.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:W.KEY_SYSTEM_ERROR,details:_.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?cd.toString(J.getBuffered(s)):"(detached)"})`),be(e)){var i;if(e.type!==K.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=w.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=w.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 jr(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=w.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(m.KEY_LOADED,h),this.state===w.KEY_LOADING&&(this.state=w.IDLE),h}),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(be(e)&&(!c||e.sn!==c.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=h)}if(s=Math.max(e.start,s||0),this.loadingParts&&be(e)){const h=n.partList;if(h&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const g=this.getNextPart(h,e,s);if(g>-1){const f=h[g];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${g}/${h.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=w.FRAG_LOADING;let y;return o?y=o.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(E=>this.handleFragLoadError(E)):y=this.doFragPartsLoad(e,f,t,i).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:f,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(h,s))return Promise.resolve(null)}}if(be(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(h=>h.loaded).map(h=>`[${h.start}-${h.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))}`),G(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=w.FRAG_LOADING;const u=this.config.progressive&&e.type!==K.SUBTITLE;let d;return u&&o?d=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,i)).catch(h=>this.handleFragLoadError(h)):d=Promise.all([this.fragmentLoader.load(e,u?i:void 0),o]).then(([h])=>(!u&&i&&i(h),h)).catch(h=>this.handleFragLoadError(h)),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")):d}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,u=d=>{this.fragmentLoader.loadPart(e,d,i).then(h=>{c[d.index]=h;const g=h.part;this.hls.trigger(m.FRAG_LOADED,h);const f=ya(s.details,e.sn,d.index+1)||wo(l,e.sn,d.index+1);if(f)u(f);else return r({frag:e,part:g,partsLoaded:c})}).catch(n)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===_.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===W.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:W.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==w.PARSING){!this.fragCurrent&&this.state!==w.STOPPED&&this.state!==w.ERROR&&(this.state=w.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===K.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?ya(c,r,n):null,u=l?l.fragment:ko(c,r,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==w.PARSING)return;const{data1:n,data2:o}=e;let c=n;if(o&&(c=ot(n,o)),!c.length)return;const l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:u,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!J.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=J.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(!G(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=J.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 J.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=K.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 d=r.initialLiveManifestSize;if(i<d)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${d})`),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 h=this.hls.startPosition,g=this.hls.liveSyncPosition,f=c?(h!==-1&&h>=n?h:g)||c.start:e;this.log(`Setting startPosition to ${f} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${g} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=f}}else e<=n&&(c=s[0]);if(!c){const d=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,d,t)}let u=this.filterReplacedPrimary(c,t);if(!u&&c){const d=c.sn-t.startSN;u=this.filterReplacedPrimary(s[d+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===ke.OK||s===ke.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(Ta(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(Ta(this.config)&&e.type!==K.SUBTITLE){const s=this.hls.interstitialsManager,i=s==null?void 0: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==null?void 0:t.live)===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s==null?void 0: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 u=l.loaded;u?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=u}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=Iu(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=Eo(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,u=s.partList,d=!!(this.loadingParts&&u!=null&&u.length&&c);d&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(n=n.concat(c),o=c.sn);let h;if(e<t){var g;const y=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;h=ts(r,n,e,y)}else h=n[n.length-1];if(h){const f=h.sn-s.startSN,y=this.fragmentTracker.getState(h);if((y===ke.OK||y===ke.PARTIAL&&h.gap)&&(r=h),r&&h.sn===r.sn&&(!d||u[0].fragment.sn>h.sn||!s.live)&&h.level===r.level){const v=n[f+1];h.sn<o&&this.fragmentTracker.getState(v)!==ke.OK?h=v:h=null}}return h}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&&G(r);if(n||!o&&!r){ld(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&&G(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&&be(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!==w.FRAG_LOADING_WAITING_RETRY)&&(this.state=w.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.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===_.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=w.ERROR;return}const{action:c,flags:l,retryCount:u=0,retryConfig:d}=o,h=!!d,g=h&&c===Ne.RetryRequest,f=h&&!o.resolved&&l===Ze.MoveAllAlternatesMatchingHost,y=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!g&&f&&be(i)&&!i.endList&&y&&!To(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((g||f)&&u<d.maxNumRetry){var E;const v=Ir((E=t.response)==null?void 0:E.code),T=Wr(d,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=w.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){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 ${u+1}/${d.maxNumRetry} in ${T}ms`)}else if(d)if(this.resetFragmentErrors(e),u<d.maxNumRetry)!n&&c!==Ne.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else c===Ne.SendAlternateToPenaltyBox?this.state=w.WAITING_LEVEL:this.state=w.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Ir(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=w.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===w.PARSING||this.state===w.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==null?void 0: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===K.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==w.STOPPED&&(this.state=w.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=J.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===w.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==w.STOPPED&&(this.state=w.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 u=e.elementaryStreams[l];if(u){const d=u.endPTS-u.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${d})`),c||!1;const h=i?0:Do(r,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:h,type:l,frag:e,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=w.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===K.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 Ta(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class No{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=ud(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function ud(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 sr={exports:{}},Sa;function dd(){return Sa||(Sa=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,u){this.fn=c,this.context=l,this.once=u||!1}function r(c,l,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new i(u,d||c,h),f=t?t+l:l;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],g]:c._events[f].push(g):(c._events[f]=g,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=[],u,d;if(this._eventsCount===0)return l;for(d in u=this._events)e.call(u,d)&&l.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},o.prototype.listeners=function(l){var u=t?t+l:l,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,g=d.length,f=new Array(g);h<g;h++)f[h]=d[h].fn;return f},o.prototype.listenerCount=function(l){var u=t?t+l:l,d=this._events[u];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,u,d,h,g,f){var y=t?t+l:l;if(!this._events[y])return!1;var E=this._events[y],v=arguments.length,T,S;if(E.fn){switch(E.once&&this.removeListener(l,E.fn,void 0,!0),v){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,u),!0;case 3:return E.fn.call(E.context,u,d),!0;case 4:return E.fn.call(E.context,u,d,h),!0;case 5:return E.fn.call(E.context,u,d,h,g),!0;case 6:return E.fn.call(E.context,u,d,h,g,f),!0}for(S=1,T=new Array(v-1);S<v;S++)T[S-1]=arguments[S];E.fn.apply(E.context,T)}else{var x=E.length,A;for(S=0;S<x;S++)switch(E[S].once&&this.removeListener(l,E[S].fn,void 0,!0),v){case 1:E[S].fn.call(E[S].context);break;case 2:E[S].fn.call(E[S].context,u);break;case 3:E[S].fn.call(E[S].context,u,d);break;case 4:E[S].fn.call(E[S].context,u,d,h);break;default:if(!T)for(A=1,T=new Array(v-1);A<v;A++)T[A-1]=arguments[A];E[S].fn.apply(E[S].context,T)}}return!0},o.prototype.on=function(l,u,d){return r(this,l,u,d,!1)},o.prototype.once=function(l,u,d){return r(this,l,u,d,!0)},o.prototype.removeListener=function(l,u,d,h){var g=t?t+l:l;if(!this._events[g])return this;if(!u)return n(this,g),this;var f=this._events[g];if(f.fn)f.fn===u&&(!h||f.once)&&(!d||f.context===d)&&n(this,g);else{for(var y=0,E=[],v=f.length;y<v;y++)(f[y].fn!==u||h&&!f[y].once||d&&f[y].context!==d)&&E.push(f[y]);E.length?this._events[g]=E.length===1?E[0]:E:n(this,g)}return this},o.prototype.removeAllListeners=function(l){var u;return l?(u=t?t+l:l,this._events[u]&&n(this,u)):(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}(sr)),sr.exports}var hd=dd(),Zr=Nc(hd);const Ys="1.6.15",As={};function fd(){return typeof __HLS_WORKER_BUNDLE__=="function"}function gd(){const a=As[Ys];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 As[Ys]=i,i}function md(a){const e=As[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 As[a]=i,i}function pd(a){const e=As[a||Ys];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete As[a||Ys],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Bo(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 Jr(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 Ui(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 Ws(a,e){const t=e;let s=0;for(;Jr(a,e);){s+=10;const i=Ui(a,e+6);s+=i,Bo(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function yd(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 g=new Error(`invalid ADTS sampling index:${n}`);a.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,u=i[n];let d=n;(o===5||o===29)&&(d-=3);const h=[o<<3|(d&14)>>1,(d&1)<<7|c<<3];return ce.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${u} (ADTS object type:${o} sampling index:${n})`),{config:h,samplerate:u,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function Uo(a,e){return a[e]===255&&(a[e+1]&246)===240}function $o(a,e){return a[e+1]&1?7:9}function en(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function Ed(a,e){return e+5<a.length}function Mi(a,e){return e+1<a.length&&Uo(a,e)}function vd(a,e){return Ed(a,e)&&Uo(a,e)&&en(a,e)<=a.length-e}function Td(a,e){if(Mi(a,e)){const t=$o(a,e);if(e+t>=a.length)return!1;const s=en(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||Mi(a,i)}return!1}function Go(a,e,t,s,i){if(!a.samplerate){const r=yd(e,t,s,i);if(!r)return;he(a,r)}}function Vo(a){return 1024*9e4/a}function Sd(a,e){const t=$o(a,e);if(e+t<=a.length){const s=en(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function Ko(a,e,t,s,i){const r=Vo(a.samplerate),n=s+i*r,o=Sd(e,t);let c;if(o){const{frameLength:d,headerLength:h}=o,g=h+d,f=Math.max(0,t+g-e.length);f?(c=new Uint8Array(g-h),c.set(e.subarray(t+h,e.length),0)):c=e.subarray(t+h,t+g);const y={unit:c,pts:n};return f||a.samples.push(y),{sample:y,length:g,missing:f}}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 xd(a,e){return Jr(a,e)&&Ui(a,e+6)+10<=a.length-e}function Ad(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function ir(a,e=0,t=1/0){return Ld(a,e,t,Uint8Array)}function Ld(a,e,t,s){const i=Id(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=bd(a)?a.byteOffset:0,o=(n+a.byteLength)/r,c=(n+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),u=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,u-l)}function Id(a){return a instanceof ArrayBuffer?a:a.buffer}function bd(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function Rd(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=tt(ir(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=tt(ir(a.data,3+s,n));let c;return i==="-->"?c=tt(ir(a.data,4+s+n)):c=Ad(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function _d(a){if(a.size<2)return;const e=tt(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function Dd(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=tt(a.data.subarray(t),!0);t+=s.length+1;const i=tt(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=tt(a.data.subarray(1));return{key:a.type,info:"",data:e}}function Cd(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=tt(a.data.subarray(t),!0);t+=s.length+1;const i=tt(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=tt(a.data);return{key:a.type,info:"",data:e}}function Pd(a){return a.type==="PRIV"?_d(a):a.type[0]==="W"?Cd(a):a.type==="APIC"?Rd(a):Dd(a)}function kd(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Ui(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const ai=10,wd=10;function Ho(a){let e=0;const t=[];for(;Jr(a,e);){const s=Ui(a,e+6);a[e+5]>>6&1&&(e+=ai),e+=ai;const i=e+s;for(;e+wd<i;){const r=kd(a.subarray(e)),n=Pd(r);n&&t.push(n),e+=r.size+ai}Bo(a,e)&&(e+=ai)}return t}function Yo(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Od(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 tn(a){const e=Ho(a);for(let t=0;t<e.length;t++){const s=e[t];if(Yo(s))return Od(s)}}let et=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 St(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class sn{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=ot(this.cachedData,e),this.cachedData=null);let s=Ws(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,c=s?tn(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&G(c))&&(this.basePTS=Md(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:et.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const u=this.appendFrame(n,e,i);u?(this.frameIndex++,this.lastPTS=u.sample.pts,i+=u.length,r=i):i=l}else xd(e,i)?(s=Ws(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:et.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const u=e.slice(r);this.cachedData?this.cachedData=ot(this.cachedData,u):this.cachedData=u}}return{audioTrack:n,videoTrack:St(),id3Track:o,textTrack:St()}}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:St(),id3Track:this._id3Track,textTrack:St()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Md=(a,e,t)=>{if(G(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let oi=null;const Fd=[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],Nd=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Bd=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ud=[0,1,1,4];function Wo(a,e,t,s,i){if(t+24>e.length)return;const r=qo(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 qo(a,e){const t=a[e+1]>>
vendor: 5,030 bytes, line 16
163&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=Fd[c*14+i-1]*1e3,d=Nd[(t===3?0:t===2?1:2)*3+r],h=o===3?1:2,g=Bd[t][s],f=Ud[s],y=g*8*f,E=Math.floor(g*l/d+n)*f;if(oi===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);oi=S?parseInt(S[1]):0}return!!oi&&oi<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:d,channelCount:h,frameLength:E,samplesPerFrame:y}}}function rn(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function jo(a,e){return e+1<a.length&&rn(a,e)}function $d(a,e){return rn(a,e)&&4<=a.length-e}function zo(a,e){if(e+1<a.length&&rn(a,e)){const s=qo(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||jo(a,r)}return!1}class Gd extends sn{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=Ws(e,0);let i=(s==null?void 0:s.length)||0;if(zo(e,i))return!1;for(let r=e.length;i<r;i++)if(Td(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return vd(e,t)}appendFrame(e,t,s){Go(e,this.observer,t,s,e.manifestCodec);const i=Ko(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const Xo=(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 Vd extends sn{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=Qo(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=Ws(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&tn(t)!==void 0&&Xo(e,s)<16}}function Qo(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,u=[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+u>e.length)return-1;const d=e[t+6]>>5;let h=0;d===2?h+=2:(d&1&&d!==1&&(h+=2),d&4&&(h+=2));const g=(e[t+6]<<8|e[t+7])>>12-h&1,y=[2,1,2,3,3,4,4,5][d]+g,E=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([r<<6|E<<1|v>>2,(v&3)<<6|d<<3|g<<2|c>>4,c<<4&224]),S=1536/o*9e4,x=s+i*S,A=e.subarray(t,t+u);return a.config=T,a.channelCount=y,a.samplerate=o,a.samples.push({unit:A,pts:x}),u}class Kd extends sn{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=Ws(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&tn(t)!==void 0&&Xo(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(zo(e,s))return ce.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return $d(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Wo(e,t,s,this.basePTS,this.frameIndex)}}const Hd=/\/emsg[-/]ID3/i;class Yd{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=St("video",1),n=this.audioTrack=St("audio",1),o=this.txtTrack=St("text",1);if(this.id3Track=St("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=ao(e);if(c.video){const{id:l,timescale:u,codec:d,supplemental:h}=c.video;r.id=l,r.timescale=o.timescale=u,r.codec=d,r.supplemental=h}if(c.audio){const{id:l,timescale:u,codec:d}=c.audio;n.id=l,n.timescale=u,n.codec=d}o.id=io.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Vc(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=ot(this.remainderData,e));const o=zc(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);
vendor: 4,621 bytes, line 16
16return r.samples=Un(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=Un(e,t),{videoTrack:t,audioTrack:St(),id3Track:i,textTrack:St()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=te(e.samples,["emsg"]);i&&i.forEach(r=>{const n=Qc(r);if(Hd.test(n.schemeIdUri)){const o=xa(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:et.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=xa(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:et.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 xa(a,e){return G(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class Wd{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new qr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ht.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=co(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 Zo{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,u,d,h=-1,g=0;for(r===-1&&(h=0,g=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(u=c-r-1,h>=0){const f={data:t.subarray(h,u),type:g};o.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&c<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),u>0&&(f.data=ot(f.data,t.subarray(0,u)),f.state=0))}c<i?(d=this.getNALuType(t,c),h=c,g=d,r=0):r=-1}else r=0}if(h>=0&&r>=0){const f={data:t.subarray(h,i),type:g,state:r};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=ot(f.data,t))}return e.naluState=r,o}}class $s{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>
vendor: 8,950 bytes, line 16
16e?(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&&ce.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 qd extends Zo{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 u,d;switch(l.type){case 1:{let y=!1;o=!0;const E=l.data;if(c&&E.length>4){const v=this.readSliceType(E);(v===2||v===4||v===7||v===9)&&(y=!0)}if(y){var h;(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.frame=!0,n.key=y;break}case 5:o=!0,(u=n)!=null&&u.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,Kr(l.data,1,s.pts,t.samples);break}case 7:{var g,f;o=!0,c=!0;const y=l.data,E=this.readSPS(y);if(!e.sps||e.width!==E.width||e.height!==E.height||((g=e.pixelRatio)==null?void 0:g[0])!==E.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[y];const v=y.subarray(1,4);let T="avc1.";for(let S=0;S<3;S++){let x=v[S].toString(16);x.length<2&&(x="0"+x),T+=x}e.codec=T}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(d=n)!=null&&d.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 $s(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 $s(e);let s=0,i=0,r=0,n=0,o,c,l;const u=t.readUByte.bind(t),d=t.readBits.bind(t),h=t.readUEG.bind(t),g=t.readBoolean.bind(t),f=t.skipBits.bind(t),y=t.skipEG.bind(t),E=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const T=u();if(d(5),f(3),u(),E(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){const p=h();if(p===3&&f(1),E(),E(),f(1),g())for(c=p!==3?8:12,l=0;l<c;l++)g()&&(l<6?v(16,t):v(64,t))}E();const S=h();if(S===0)h();else if(S===1)for(f(1),y(),y(),o=h(),l=0;l<o;l++)y();E(),f(1);const x=h(),A=h(),P=d(1);P===0&&f(1),f(1),g()&&(s=h(),i=h(),r=h(),n=h());let L=[1,1];if(g()&&g())switch(u()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:{L=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((x+1)*16-s*2-i*2),height:(2-P)*(A+1)*16-(P?2:4)*(r+n),pixelRatio:L}}}class jd extends Zo{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 u,d;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 h;(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 19:case 20:o=!0,(u=n)!=null&&u.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,Kr(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=he(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 g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in g.params)e.params[f]=g.params[f]}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 g=this.readPPS(l.data);for(const f in g)e.params[f]=g[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(d=n)!=null&&d.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 $s(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 $s(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(),u=t.readUByte(),d=t.readUByte(),h=t.readUByte(),g=t.readUByte(),f=t.readUByte(),y=t.readUByte(),E=t.readUByte(),v=t.readUByte(),T=[],S=[];for(let se=0;se<s;se++)T.push(t.readBoolean()),S.push(t.readBoolean());if(s>0)for(let se=s;se<8;se++)t.readBits(2);for(let se=0;se<s;se++)T[se]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[se]&&t.readUByte();t.readUEG();const x=t.readUEG();x==3&&t.skipBits(1);const A=t.readUEG(),P=t.readUEG(),L=t.readBoolean();let p=0,D=0,I=0,k=0;L&&(p+=t.readUEG(),D+=t.readUEG(),I+=t.readUEG(),k+=t.readUEG());const N=t.readUEG(),B=t.readUEG(),Y=t.readUEG(),$=t.readBoolean();for(let se=$?0:s;se<=s;se++)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 Te=0;Te<4;Te++)for(let Me=0;Me<(Te===3?2:6);Me++)if(!t.readBoolean())t.readUEG();else{const De=Math.min(64,1<<4+(Te<<1));Te>1&&t.readEG();for(let it=0;it<De;it++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const U=t.readUEG();let H=0;for(let se=0;se<U;se++){let Te=!1;if(se!==0&&(Te=t.readBoolean()),Te){se===U&&t.readUEG(),t.readBoolean(),t.readUEG();let Me=0;for(let st=0;st<=H;st++){const De=t.readBoolean();let it=!1;De||(it=t.readBoolean()),(De||it)&&Me++}H=Me}else{const Me=t.readUEG(),st=t.readUEG();H=Me+st;for(let De=0;De<Me;De++)t.readUEG(),t.readBoolean();for(let De=0;De<st;De++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const se=t.readUEG();for(let Te=0;Te<se;Te++){for(let Me=0;Me<Y+4;Me++)t.readBits(1);t.readBits(1)}}let M=0,F=1,Z=1,ae=!0,ee=1,re=0;t.readBoolean(),t.readBoolean();let pe=!1;if(t.readBoolean()){if(t.readBoolean()){const bt=t.readUByte(),Ce=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Rt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];bt>0&&bt<16?(F=Ce[bt-1],Z=Rt[bt-1]):bt===255&&(F=t.readBits(16),Z=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
vendor: 8,297 bytes, line 16
16=t.readBoolean(),pe&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ee=t.readBits(32),re=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Rt=t.readBoolean(),bs=t.readBoolean();let Yt=!1;(Rt||bs)&&(Yt=t.readBoolean(),Yt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Yt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let gt=0;gt<=s;gt++){ae=t.readBoolean();const Ot=ae||t.readBoolean();let _t=!1;Ot?t.readEG():_t=t.readBoolean();const mt=_t?1:t.readUEG()+1;if(Rt)for(let Ke=0;Ke<mt;Ke++)t.readUEG(),t.readUEG(),Yt&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(bs)for(let Ke=0;Ke<mt;Ke++)t.readUEG(),t.readUEG(),Yt&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let _e=A,Ve=P;if(L){let se=1,Te=1;x===1?se=Te=2:x==2&&(se=2),_e=A-se*D-se*p,Ve=P-Te*k-Te*I}const Le=i?["A","B","C"][i]:"",Gi=o<<24|c<<16|l<<8|u;let Ls=0;for(let se=0;se<32;se++)Ls=(Ls|(Gi>>se&1)<<31-se)>>>0;let Is=Ls.toString(16);return n===1&&Is==="2"&&(Is="6"),{codecString:`hvc1.${Le}${n}.${Is}.${r?"H":"L"}${v}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,u],general_constraint_indicator_flags:[d,h,g,f,y,E],general_level_idc:v,bit_depth:N+8,bit_depth_luma_minus8:N,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:M,chroma_format_idc:x,frame_rate:{fixed:ae,fps:re/ee}},width:_e,height:Ve,pixelRatio:[F,Z]}}readPPS(e){const t=new $s(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 Oe=188;class Gt{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=Gt.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(Oe*5,t-Oe)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let c=i;c<t;c+=Oe)if(e[c]===71&&(t-c===Oe||e[c+Oe]===71)){if(o++,n===-1&&(n=c,n!==0&&(s=Math.min(n+Oe*99,e.length-Oe)+1)),r||(r=Cr(e,c)===0),r&&o>1&&(n===0&&o>2||c+Oe>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:io[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=Gt.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Gt.createTrack("audio",i),this._id3Track=Gt.createTrack("id3"),this._txtTrack=Gt.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 u=n.pid,d=n.pesData,h=o.pid,g=c.pid,f=o.pesData,y=c.pesData,E=null,v=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(e=ot(this.remainderData,e),S=e.length,this.remainderData=null),S<Oe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};const x=Math.max(0,Gt.syncOffset(e));S-=(S-x)%Oe,S<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let A=0;for(let L=x;L<S;L+=Oe)if(e[L]===71){const p=!!(e[L+1]&64),D=Cr(e,L),I=(e[L+3]&48)>>4;let k;if(I>1){if(k=L+5+e[L+4],k===L+Oe)continue}else k=L+4;switch(D){case u:p&&(d&&(r=hs(d,this.logger))&&(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(k,L+Oe)),d.size+=L+Oe-k);break;case h:if(p){if(f&&(r=hs(f,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}f={data:[],size:0}}f&&(f.data.push(e.subarray(k,L+Oe)),f.size+=L+Oe-k);break;case g:p&&(y&&(r=hs(y,this.logger))&&this.parseID3PES(c,r),y={data:[],size:0}),y&&(y.data.push(e.subarray(k,L+Oe)),y.size+=L+Oe-k);break;case 0:p&&(k+=e[k]+1),T=this._pmtId=zd(e,k);break;case T:{p&&(k+=e[k]+1);const N=Xd(e,k,this.typeSupported,s,this.observer,this.logger);u=N.videoPid,u>0&&(n.pid=u,n.segmentCodec=N.segmentVideoCodec),h=N.audioPid,h>0&&(o.pid=h,o.segmentCodec=N.segmentAudioCodec),g=N.id3Pid,g>0&&(c.pid=g),E!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${L} after unknown PID '${E}'. Backtracking to sync byte @${x} to parse all TS packets.`),E=null,L=x-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=D;break}}else A++;A>0&&Pr(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,o.pesData=f,c.pesData=y;const P={audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(P),P}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=hs(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=hs(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=hs(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 Wd(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new qd:e==="hevc"&&(this.videoParser=new jd))}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 d=i.missing,h=i.sample.unit.byteLength;if(d===-1)r=ot(i.sample.unit,r);else{const g=h-d;i.sample.unit.set(r.subarray(0,d),g),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!Mi(r,n);n++);if(n!==s){let d;const h=n<o-1;if(h?d=`AAC PES did not start with ADTS header,offset:${n}`:d="No ADTS header found in AAC PES",Pr(this.observer,new Error(d),h,this.logger),!h)return}Go(e,this.observer,r,n,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const d=Vo(e.samplerate);c=i.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,u;for(;n<o;)if(u=Ko(e,r,n,c,l),n+=u.length,u.missing){this.aacOverFlow=u;break}else for(l++;
vendor: 5,110 bytes, line 16
16n<o-1&&!Mi(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(jo(s,n)){const c=Wo(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=Qo(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=he({},t,{type:this._videoTrack?et.emsg:et.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Cr(a,e){return((a[e+1]&31)<<8)+a[e+2]}function zd(a,e){return(a[e+10]&31)<<8|a[e+11]}function Xd(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 u=Cr(a,e),d=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){rr("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=u);break;case 21:n.id3Pid===-1&&(n.id3Pid=u);break;case 219:if(!s){rr("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=u,n.segmentAudioCodec="mp3");break;case 193:if(!s){rr("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=u,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&d>0){let h=e+5,g=d;for(;g>2;){switch(a[h]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=u,n.segmentAudioCodec="ac3");break}const y=a[h+1]+2;h+=y,g-=y}}break;case 194:case 135:return Pr(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=u,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=d+5}return n}function Pr(a,e,t,s){s.warn(`parsing error: ${e.message}`),a.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function rr(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function hs(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]=ot(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 u=s[7];u&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&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 d=r+9;if(a.size<=d)return null;a.size-=d;const h=new Uint8Array(a.size);for(let g=0,f=c.length;g<f;g++){s=c[g];let y=s.byteLength;if(d)if(d>y){d-=y;continue}else s=s.subarray(d),y-=d,d=0;h.set(s,t),t+=y}return i&&(i-=r+3),{data:h,pts:n,dts:o,len:i}}return null}class Qd{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 Bt=Math.pow(2,32)-1;class R{static init(){R.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 R.types)R.types.hasOwnProperty(e)&&(R.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]);R.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 
vendor: 4,361 bytes, line 16
16Uint8Array([0,0,0,0,0,0,0,0]);R.STTS=R.STSC=R.STCO=r,R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.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]);R.FTYP=R.box(R.types.ftyp,n,c,n,o),R.DINF=R.box(R.types.dinf,R.box(R.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 R.box(R.types.hdlr,R.HDLR_TYPES[e])}static mdat(e){return R.box(R.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Bt+1)),i=Math.floor(t%(Bt+1));return R.box(R.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 R.box(R.types.mdia,R.mdhd(e.timescale||0,e.duration||0),R.hdlr(e.type),R.minf(e))}static mfhd(e){return R.box(R.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"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(e)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(e))}static moof(e,t,s){return R.box(R.types.moof,R.mfhd(e),R.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trak(e[t]);return R.box.apply(null,[R.types.moov,R.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(R.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trex(e[t]);return R.box.apply(null,[R.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Bt+1)),i=Math.floor(t%(Bt+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 R.box(R.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 R.box(R.types.sdtp,s)}static stbl(e){return R.box(R.types.stbl,R.stsd(e),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.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=R.box(R.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,u=e.pixelRatio[0],d=e.pixelRatio[1];return R.box(R.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,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&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 R.box(R.types.mp4a,R.audioStsd(e),R.box(R.types.esds,R.esds(e)))}static mp3(e){return R.box(R.types[".mp3"],R.audioStsd(e))}static ac3(e){return R.box(R.types["ac-3"],R.audioStsd(e),R.box(R.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return R.box(R.types.stsd,R.STSD,R.mp4a(e));if(t==="ac3"&&e.config)return R.box(R.types.stsd,R.STSD,R.ac3(e));if(t==="mp3"&&e.codec==="mp3")return R.box(R.types.stsd,R.STSD,R.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return R.box(R.types.stsd,R.STSD,R.avc1(e));if(t==="hevc"&&e.vps)return R.box(R.types.stsd,R.STSD,R.hvc1(e))}
vendor: 24,035 bytes, line 16
16else 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/(Bt+1)),o=Math.floor(s%(Bt+1));return R.box(R.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=R.sdtp(e),i=e.id,r=Math.floor(t/(Bt+1)),n=Math.floor(t%(Bt+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),R.box(R.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])),R.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,R.box(R.types.trak,R.tkhd(e),R.mdia(e))}static trex(e){const t=e.id;return R.box(R.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,u,d,h;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,u=c.size,d=c.flags,h=c.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&240<<8,d.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return R.box(R.types.trun,n)}static initSegment(e){R.types||R.init();const t=R.moov(e);return ot(R.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 f=0;f<s.length;f+=1){n+=3;for(let y=0;y<s[f].length;y+=1)n+=2+s[f][y].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const c=s.length-1;for(let f=0;f<s.length;f+=1){o.set(new Uint8Array([32+f|(f===c?128:0),0,s[f].length]),n),n+=3;for(let y=0;y<s[f].length;y+=1)o.set(new Uint8Array([s[f][y].length>>8,s[f][y].length&255]),n),n+=2,o.set(s[f][y],n),n+=s[f][y].length}const l=R.box(R.types.hvcC,o),u=e.width,d=e.height,h=e.pixelRatio[0],g=e.pixelRatio[1];return R.box(R.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,u>>8&255,u&255,d>>8&255,d&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,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,g>>24,g>>16&255,g>>8&255,g&255])))}}R.types=void 0;R.HDLR_TYPES=void 0;R.STTS=void 0;R.STSC=void 0;R.STCO=void 0;R.STSZ=void 0;R.VMHD=void 0;R.SMHD=void 0;R.STSD=void 0;R.FTYP=void 0;R.DINF=void 0;const Jo=9e4;function nn(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function Zd(a,e,t=1,s=!1){return nn(a,e,1/t,s)}function Ns(a,e=!1){return nn(a,1e3,1/Jo,e)}function Jd(a,e=1){return nn(a,Jo,1/e)}function Aa(a){const{baseTime:e,timescale:t,trackId:s}=a;return`${e/t} (${e}/${t}) trackId: ${s}`}const eh=10*1e3,th=1024,sh=1152,ih=1536;let fs=null,nr=null;function La(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 Si extends lt{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,fs===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);fs=n?parseInt(n[1]):0}if(nr===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);nr=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&&Aa(t)} > ${e&&Aa(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=Je(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,u,d,h,g,f,y=r,E=r;const v=e.pid>-1,T=t.pid>-1,S=t.samples.length,x=e.samples.length>0,A=o&&S>0||S>1;if((!v||x)&&(!T||A)||this.ISGenerated||o){if(this.ISGenerated){var L,p,D,I;const Y=this.videoTrackConfig;(Y&&(t.width!==Y.width||t.height!==Y.height||((L=t.pixelRatio)==null?void 0:L[0])!==((p=Y.pixelRatio)==null?void 0:p[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((I=Y.pixelRatio)==null?void 0:I[1]))||!Y&&A||this.nextAudioTs===null&&x)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,n));const k=this.isVideoContiguous;let N=-1,B;if(A&&(N=rh(t.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,N>0){this.warn(`Dropped ${N} out of ${S} video samples due to a missing keyframe`);const Y=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(N),t.dropped+=N,E+=(t.samples[0].pts-Y)/t.inputTimeScale,B=E}else N===-1&&(this.warn(`No keyframe found out of ${S} video samples`),f=!1);if(this.ISGenerated){if(x&&A){const Y=this.getVideoStartPts(t.samples),O=(Je(e.samples[0].pts,Y)-Y)/t.inputTimeScale;y+=Math.max(0,O),E+=Math.max(0,-O)}if(x){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,n)),u=this.remuxAudio(e,y,this.isAudioContiguous,n,T||A||c===K.AUDIO?E:void 0),A){const Y=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,E,k,Y)}}else A&&(l=this.remuxVideo(t,E,k,0));l&&(l.firstKeyFrame=N,l.independent=N!==-1,l.firstKeyFramePTS=B)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=el(s,r,this._initPTS,this._initDTS)),i.samples.length&&(h=tl(i,r,this._initPTS))),{audio:u,video:l,initSegment:d,independent:f,text:h,id3:g}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Je(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 u=!l||i,d="audio/mp4",h,g,f,y=-1;if(u&&(h=g=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):R.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(y=e.id,f=e.inputTimeScale,!l||f!==l.timescale?h=g=this.computeInitPts(r[0].pts,f,s,"audio"):u=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:R.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(y=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const E=this.getVideoStartPts(n),v=Je(n[0].dts,E),T=this.computeInitPts(v,f,s,"video"),S=this.computeInitPts(E,f,s,"video");g=Math.min(g,T),h=Math.min(h,S)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${h/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/f} (${h}/${f}) trackId: ${y}`),this._initPTS={baseTime:h,timescale:f,trackId:y},this._initDTS={baseTime:g,timescale:f,trackId:y}):h=f=void 0,{tracks:c,initPTS:h,timescale:f,trackId:y}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],c=n.length,l=this._initPTS,u=l.baseTime*r/l.timescale;let d=this.nextVideoTs,h=8,g=this.videoSampleDuration,f,y,E=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,T=!1;if(!s||d===null){const M=u+t*r,F=n[0].pts-Je(n[0].dts,n[0].pts);fs&&d!==null&&Math.abs(M-F-(d+u))<15e3?s=!0:d=M-F-u}const S=d+u;for(let M=0;M<c;M++){const F=n[M];F.pts=Je(F.pts,S),F.dts=Je(F.dts,S),F.dts<n[M>0?M-1:M].dts&&(T=!0)}T&&n.sort(function(M,F){const Z=M.dts-F.dts,ae=M.pts-F.pts;return Z||ae}),f=n[0].dts,y=n[n.length-1].dts;const x=y-f,A=x?Math.round(x/(c-1)):g||e.inputTimeScale/30;if(s){const M=f-S,F=M>A,Z=M<-1;if((F||Z)&&(F?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ns(M,!0)} ms (${M}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ns(-M,!0)} ms (${M}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Z||S>=n[0].pts||fs)){f=S;const ae=n[0].pts-M;if(F)n[0].dts=f,n[0].pts=ae;else{let ee=!0;for(let re=0;re<n.length&&!(n[re].dts>ae&&ee);re++){const pe=n[re].pts;if(n[re].dts-=M,n[re].pts-=M,re<n.length-1){const ve=n[re+1].pts,_e=n[re].pts,Ve=ve<=_e,Le=ve<=pe;ee=Ve==Le}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ns(ae,!0)}/${Ns(f,!0)}, delta: ${Ns(M,!0)} ms`)}}f=Math.max(0,f);let P=0,L=0,p=f;for(let M=0;M<c;M++){const F=n[M],Z=F.units,ae=Z.length;let ee=0;for(let re=0;re<ae;re++)ee+=Z[re].data.length;L+=ee,P+=ae,F.length=ee,F.dts<p?(F.dts=p,p+=A/4|0||1):p=F.dts,E=Math.min(F.pts,E),v=Math.max(F.pts,v)}y=n[c-1].dts;const D=L+4*P+8;let I;try{I=new Uint8Array(D)}catch(M){this.observer.emit(m.ERROR,m.ERROR,{type:W.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:D,reason:`fail allocating video mdat ${D}`});return}const k=new DataView(I.buffer);k.setUint32(0,D),I.set(R.types.mdat,4);let N=!1,B=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let M=0;M<c;M++){const F=n[M],Z=F.units;let ae=0;for(let pe=0,ve=Z.length;pe<ve;pe++){const _e=Z[pe],Ve=_e.data,Le=_e.data.byteLength;k.setUint32(h,Le),h+=4,I.set(Ve,h),h+=Le,ae+=4+Le}let ee;if(M<c-1)g=n[M+1].dts-F.dts,ee=n[M+1].pts-F.pts;else{const pe=this.config,ve=M>0?F.dts-n[M-1].dts:A;if(ee=M>0?F.pts-n[M-1].pts:A,pe.stretchShortVideoTrack&&this.nextAudioTs!==null){const _e=Math.floor(pe.maxBufferHole*r),Ve=(i?E+i*r:this.nextAudioTs+u)-F.pts;Ve>_e?(g=Ve-ve,g<0?g=ve:N=!0,this.log(`It is approximately ${Ve/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=ve}else g=ve}const re=Math.round(F.pts-F.dts);B=Math.min(B,g),$=Math.max($,g),Y=Math.min(Y,ee),O=Math.max(O,ee),o.push(La(F.key,g,ae,re))}if(o.length){if(fs){if(fs<70){const M=o[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(nr&&O-Y<$-B&&A/$<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let M=f;for(let F=0,Z=o.length;F<Z;F++){const ae=M+o[F].duration,ee=M+o[F].cts;if(F<Z-1){const re=ae+o[F+1].cts;o[F].duration=re-ee}else o[F].duration=F?o[F-1].duration:A;o[F].cts=0,M=ae}}}g=N||!g?A:g;const V=y+g;this.nextVideoTs=d=V-u,this.videoSampleDuration=g,this.isVideoContiguous=!0;const U=R.moof(e.sequenceNumber++,f,he(e,{samples:o})),H="video",X={data1:U,data2:I,startPTS:(E-u)/r,endPTS:(v+g-u)/r,startDTS:(f-u)/r,endDTS:d/r,type:H,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,X}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return sh;case"ac3":return ih;default:return th}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,c=n/o,l=this.getSamplesPerFrame(e),u=l*c,d=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=r!==void 0;let y=e.samples,E=h?0:8,v=this.nextAudioTs||-1;const T=d.baseTime*n/d.timescale,S=T+t*n;if(this.isAudioContiguous=s=s||y.length&&v>0&&(i&&Math.abs(S-(v+T))<9e3||Math.abs(Je(y[0].pts,S)-(v+T))<20*u),y.forEach(function(O){O.pts=Je(O.pts,S)}),!s||v<0){const O=y.length;if(y=y.filter(V=>V.pts>=0),O!==y.length&&this.warn(`Removed ${y.length-O} of ${O} samples (initPTS ${T} / ${n})`),!y.length)return;r===0?v=0:i&&!f?v=Math.max(0,S-T):v=y[0].pts-T}if(e.segmentCodec==="aac"){const O=this.config.maxAudioFramesDrift;for(let V=0,U=v+T;V<y.length;V++){const H=y[V],X=H.pts,M=X-U,F=Math.abs(1e3*M/n);if(M<=-O*u&&f)V===0&&(this.warn(`Audio frame @ ${(X/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*M/n)} ms.`),this.nextAudioTs=v=X-T,U=X);else if(M>=O*u&&F<eh&&f){let Z=Math.round(M/u);for(U=X-Z*u;U<0&&Z&&u;)Z--,U+=u;V===0&&(this.nextAudioTs=v=U-T),this.warn(`Injecting ${Z} audio frames @ ${((U-T)/n).toFixed(3)}s due to ${Math.round(1e3*M/n)} ms gap.`);for(let ae=0;ae<Z;ae++){let ee=Qd.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ee||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ee=H.unit.subarray()),y.splice(V,0,{unit:ee,pts:U}),U+=u,V++}}H.pts=U,U+=u}}let x=null,A=null,P,L=0,p=y.length;for(;p--;)L+=y[p].unit.byteLength;for(let O=0,V=y.length;O<V;O++){const U=y[O],H=U.unit;let X=U.pts;if(A!==null){const F=g[O-1];F.duration=Math.round((X-A)/c)}else if(s&&e.segmentCodec==="aac"&&(X=v+T),x=X,L>0){L+=E;try{P=new Uint8Array(L)}catch(F){this.observer.emit(m.ERROR,m.ERROR,{type:W.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:F,bytes:L,reason:`fail allocating audio mdat ${L}`});return}h||(new DataView(P.buffer).setUint32(0,L),P.set(R.types.mdat,4))}else return;P.set(H,E);const M=H.byteLength;E+=M,g.push(La(!0,l,M,0)),A=X}const D=g.length;if(!D)return;const I=g[g.length-1];v=A-T,this.nextAudioTs=v+c*I.duration;const k=h?new Uint8Array(0):R.moof(e.sequenceNumber++,x/c,he({},e,{samples:g}));e.samples=[];const N=(x-T)/n,B=this.nextAudioTs/n,$={data1:k,data2:P,startPTS:N,endPTS:B,startDTS:N,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,$}}function Je(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 rh(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function el(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=Je(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=Je(c.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function tl(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=Je(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 nh extends lt{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=ao(e);if(t)Wc(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=Ia(r,fe.AUDIO,this)),n&&(i=Ia(n,fe.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:u}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};G(u)||(u=this.lastEndTime=r||0);const h=t.samples;if(!h.length)return d;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(h),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const y=jc(h,f,this),E=f.audio?y[f.audio.id]:null,v=f.video?y[f.video.id]:null,T=li(v,1/0),S=li(E,1/0),x=li(v,0,!0),A=li(E,0,!0);let P=r,L=0;const p=E&&(!v||!l&&S<T||l&&l.trackId===f.audio.id),D=p?E:v;if(D){const U=D.timescale,H=D.start-r*U,X=p?f.audio.id:f.video.id;P=D.start/U,L=p?A-S:x-T,(n||!l)&&(ah(l,P,r,L)||U!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${H/U} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${P-r} (${H}/${U}) trackId: ${X}`),l=null,g.initPTS=H,g.timescale=U,g.trackId=X)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(g.initPTS=l.baseTime,g.timescale=l.timescale,g.trackId=l.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=P,g.timescale=1,g.trackId=-1),this.initPTS=l={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});const I=P-l.baseTime/l.timescale,k=I+L;L>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const N=!!f.audio,B=!!f.video;let Y="";N&&(Y+="audio"),B&&(Y+="video");const $=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),O={data1:h,startPTS:I,startDTS:I,endPTS:k,endDTS:k,type:Y,hasAudio:N,hasVideo:B,nb:1,dropped:0,encrypted:$};d.audio=N&&!B?O:void 0,d.video=B?O:void 0;const V=v==null?void 0:v.sampleCount;if(V){const U=v.keyFrameIndex,H=U!==-1;O.nb=V,O.dropped=U===0||this.isVideoContiguous?0:H?U:V,O.independent=H,O.firstKeyFrame=U,H&&v.keyFrameStart&&(O.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=H),this.isVideoContiguous||(this.isVideoContiguous=H),O.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${U}/${V} dropped: ${O.dropped} start: ${O.firstKeyFramePTS||"NA"}`)}return d.initSegment=g,d.id3=el(s,r,l,l),i.samples.length&&(d.text=tl(i,r,l)),d}}function li(a,e,t=!1){return(a==null?void 0:a.start)!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function ah(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 Ia(a,e,t){const s=a.codec;return s&&s.length>4?s:e===fe.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Ri(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 wt;try{wt=self.performance.now.bind(self.performance)}catch{wt=Date.now}const xi=[{demux:Yd,remux:nh},{demux:Gt,remux:Si},{demux:Gd,remux:Si},{demux:Kd,remux:Si}];xi.splice(2,0,{demux:Vd,remux:Si});class ba{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=wt();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:u,trackSwitch:d,accurateTimeOffset:h,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:y,videoCodec:E,defaultInitPts:v,duration:T,initSegmentData:S}=c,x=oh(n,t);if(x&&vs(x.method)){const p=this.getDecrypter(),D=zr(x.method);if(p.isSync()){let I=p.softwareDecrypt(n,x.key.buffer,x.iv.buffer,D);if(s.part>-1){const N=p.flush();I=N&&N.buffer}if(!I)return r.executeEnd=wt(),ar(s);n=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=p.webCryptoDecrypt(n,x.key.buffer,x.iv.buffer,D).then(I=>{const k=this.push(I,null,s);return this.decryptionPromise=null,k}),this.decryptionPromise}const A=this.needsProbing(u,d);if(A){const p=this.configureTransmuxer(n);if(p)return this.logger.warn(`[transmuxer] ${p.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:p,reason:p.message}),r.executeEnd=wt(),ar(s)}(u||d||f||A)&&this.resetInitSegment(S,y,E,T,t),(u||f||A)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const P=this.transmux(n,x,g,h,s);this.asyncResult=qs(P);const L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,r.executeEnd=wt(),P}flush(e){const t=e.transmuxing;t.executeStart=wt();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 d=s.flush();d&&n.push(this.push(d.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=wt();const d=[ar(e)];return this.asyncResult?Promise.resolve(d):d}const u=c.flush(o);return qs(u)?(this.asyncResult=!0,u.then(d=>(this.flushRemux(n,d,e),n))):(this.flushRemux(n,u,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===K.MAIN?"level":"track"} ${s.level}`);const u=this.remuxer.remux(i,r,n,o,l,c,!0,this.id);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=wt()}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}))}
vendor: 3,950 bytes, line 16
16configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let d=0,h=xi.length;d<h;d++){var n;if((n=xi[d].demux)!=null&&n.probe(e,this.logger)){r=xi[d];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,u=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(s,t,i,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new qr(this.config)),e}}function oh(a,e){let t=null;return a.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const ar=a=>({remuxResult:{},chunkMeta:a});function qs(a){return"then"in a&&a.then instanceof Function}class lh{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 ch{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 Ra=0;class sl{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ra++,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,u=this.hls;if(!(!u||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var d;const h=(d=this.workerContext)==null?void 0:d.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{u.logger[l.data.logType]&&u.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,u.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:W.OTHER_ERROR,details:_.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 Zr,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=Vn(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||fd()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=md(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=gd());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ge(r)})}catch(u){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new ba(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new ba(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Ra++;const t=this.hls.config,s=Vn(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,c
vendor: 19,986 bytes, lines 16-22
16onfig:ge(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),pd(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,u){var d,h;l.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:f}=this,y=n?n.start:r.start,E=r.decryptdata,v=this.frag,T=!(v&&r.cc===v.cc),S=!(v&&l.level===v.level),x=v?l.sn-v.sn:-1,A=this.part?l.part-this.part.index:-1,P=x===0&&l.id>1&&l.id===(v==null?void 0:v.stats.chunkCount),L=!S&&(x===1||x===0&&(A===1||P&&A<=0)),p=self.performance.now();(S||x||r.stats.parsing.start===0)&&(r.stats.parsing.start=p),n&&(A||!L)&&(n.stats.parsing.start=p);const D=!(v&&((d=r.initSegment)==null?void 0:d.url)===((h=v.initSegment)==null?void 0:h.url)),I=new ch(T,L,c,S,y,D);if(!L||T||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===K.MAIN?"level":"track"}: ${l.level} id: ${l.id}
17        discontinuity: ${T}
18        trackSwitch: ${S}
19        contiguous: ${L}
20        accurateTimeOffset: ${c}
21        timeOffset: ${y}
22        initSegmentChange: ${D}`);const k=new lh(s,i,t,o,u);this.configureTransmuxer(k)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:E,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(f){const k=f.push(e,E,l,I);qs(k)?k.then(N=>{this.handleTransmuxComplete(N)}).catch(N=>{this.transmuxerError(N,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(k)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);qs(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){!this.hls||(this.error=e,this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const _a=100;class uh extends Qr{constructor(e,t,s){super(e,t,s,"audio-stream-controller",K.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;!e||(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){if(s===K.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===w.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l==null?void 0:l.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===w.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(i==null?void 0:i.cc)===t.cc)return;const r=(i||e).cc,n=this.getLevelDetails(),o=this.getLoadPosition(),c=Eo(n,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===w.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=w.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(_a),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=w.IDLE):this.state=w.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case w.IDLE:this.doTickIdle();break;case w.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e==null?void 0:e[t],i=s==null?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=w.WAITING_INIT_PTS}break}case w.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case w.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=w.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=w.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;!(e!=null&&e.readyState)||(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=w.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,fe.AUDIO,K.AUDIO));const u=this.getFwdBufferInfo(l,K.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=w.ENDED;return}const d=u.len,h=t.maxBufferLength,g=c.fragments,f=g[0].start,y=this.getLoadPosition(),E=this.flushing?y:u.end;if(this.switchingTrack&&i){const S=y;c.PTSKnown&&S<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(d>=h&&!this.switchingTrack&&E<g[g.length-1].start)return;let v=this.getNextFragment(E,c);if(v&&this.isLoopLoading(v,E)&&(v=this.getNextFragmentLoopLoading(v,c,u,K.MAIN,h)),!v){this.bufferFlushed=!0;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&be(v)&&!v.endList&&(!c.live||!this.loadingParts&&E<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===ke.OK&&(this.mainFragLoading=T=null),T&&be(T))){if(v.start>T.end){const x=this.fragmentTracker.getFragAtPos(E,K.MAIN);x&&x.end>T.end&&(T=x,this.mainFragLoading={frag:x,targetBufferTime:null})}if(v.start>T.end)return}this.loadFragment(v,o,E)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Hs(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==w.STOPPED&&(this.setInterval(_a),this.state=w.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${n} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==w.STOPPED&&(this.state=w.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const u=i[n];let d=0;if(r.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(u.details){var h;d=this.alignPlaylists(r,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}r.alignedSliding||(Fo(r,l),r.alignedSliding||Oi(r,l),d=r.fragmentStart)}u.details=r,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===w.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=w.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const u=l.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new sl(this.hls,K.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const E=i?i.index:-1,v=E!==-1,T=new jr(s.level,s.sn,s.stats.chunkCount,r.byteLength,E,v);h.push(r,f,d,"",s,i,u.totalduration,!1,T,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:y}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new No,complete:!1};y.push(new Uint8Array(r)),this.state!==w.STOPPED&&(this.state=w.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===K.MAIN&&be(t.frag)&&(this.mainFragLoading=t,this.state===w.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==K.AUDIO){!this.audioOnly&&s.type===K.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(be(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,le({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=w.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(K.AUDIO,t);break;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===w.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===ie.AUDIO_TRACK&&(this.state=w.IDLE);break;case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case _.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==fe.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==fe.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===w.ENDED&&(this.state=w.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,K.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:c,part:l,level:u}=o,{details:d}=u,{audio:h,text:g,id3:f,initSegment:y}=r;if(this.fragContextChanged(c)||!d){this.fragmentTracker.removeFragment(c);return}if(this.state=w.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),y!=null&&y.tracks){const E=c.initSegment||c;if(this.unhandledEncryptionError(y,c))return;this._bufferInitSegment(u,y.tracks,E,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:s,tracks:y.tracks})}if(h){const{startPTS:E,endPTS:v,startDTS:T,endDTS:S}=h;l&&(l.elementaryStreams[fe.AUDIO]={startPTS:E,endPTS:v,startDTS:T,endDTS:S}),c.setElementaryStreamInfo(fe.AUDIO,E,v,T,S),this.bufferFragmentData(h,c,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const E=he({id:s,frag:c,details:d},f);i.trigger(m.FRAG_PARSING_METADATA,E)}if(g){const E=he({id:s,frag:c,details:d},g);i.trigger(m.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,s,i){if(this.state!==w.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=K.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===ke.NOT_LOADED||i===ke.PARTIAL){var r;if(!be(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=w.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&Oi(t.details,n)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o}=this.bufferedTrack;es({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o},e,Jt)||(Di(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,le({},e))}}class an extends lt{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t==null?void 0:t.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const o=i[n];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=n;break}else c===e.substring(0,c.length)&&(r=n)}if(r!==-1){const n=i[r],o=parseInt(n["LAST-MSN"])||t.lastPartSn;let c=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&u>t.partTarget&&(c+=1)}const l=s&&Kn(s);return new Hn(o,c>=0?c:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const u=Math.max(c||0,0);i.appliedTimelineOffset=u,i.fragments.forEach(d=>{d.setStart(d.playlistOffset+u)})}if(i.live||s!=null&&s.live){const u="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){sd(s,i,this);const T=i.playlistParsingError;if(T){this.warn(T);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var l;const{networkDetails:x}=t;S.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:T,reason:T.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:x,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,g=(i.edge-h)*1e3,f=Po(i,g);if(i.requestScheduled+f<n?i.requestScheduled=n:i.requestScheduled+=f,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let y,E,v;if(i.canBlockReload&&i.endSN&&i.advanced){const T=this.hls.config.lowLatencyMode,S=i.lastPartSn,x=i.endSN,A=i.lastPartIndex,P=A!==-1,L=S===x;P?L?(E=x+1,v=T?0:A):(E=S,v=T?A+1:i.maxPartIndex):E=x+1;const p=i.age,D=p+i.ageHeader;let I=Math.min(D-i.partTarget,i.targetduration*1.5);if(I>0){if(D>i.targetduration*3)this.log(`Playlist last advanced ${p.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&D-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${I} with playlist age: ${i.age}`),I=0;
vendor: 9,796 bytes, lines 22-25
22else{const k=Math.floor(I/i.targetduration);if(E+=k,v!==void 0){const N=Math.round(I%i.targetduration/i.partTarget);v+=N}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${p.toFixed(2)}s goal: ${I} skip sn ${k} to part ${v}`)}i.tuneInGoal=I}if(y=this.getDeliveryDirectives(i,t.deliveryDirectives,E,v),T||!L){i.requestScheduled=n,this.loadingPlaylist(u,y);return}}else(i.canBlockReload||i.canSkipUntil)&&(y=this.getDeliveryDirectives(i,t.deliveryDirectives,E,v));y&&E!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(u,y,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=i.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const o=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Kn(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=vi.No),new Hn(s,i,r)}checkRetry(e){const t=e.details,s=Ci(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===Ne.RetryRequest||!i.resolved&&r===Ne.SendAlternateToPenaltyBox);if(c){var l;if(n>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Wr(o,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function il(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!js(a[t].attrs,e[t].attrs))return!1;return!0}function js(a,e,t){const s=a["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>a[i]!==e[i])}function kr(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}class dh extends an{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=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.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=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.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${n==null?void 0:n.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Audio 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.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,g)=>{h.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!r&&c){const h=xt(c,o,Jt);if(h>-1)r=o[h];else{const g=xt(c,this.tracks);r=this.tracks[g]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,u);const d=this.trackId;if(l!==-1&&d===-1)this.setAudioTrack(l);else if(o.length&&d===-1){var n;const h=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===ie.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&es(e,i,Jt))return i;const r=xt(e,this.tracksInGroup,Jt);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const o=Au(e,t.levels,s,n,Jt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const n=xt(e,s);if(n>-1)return s[n]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,le({},i)),r))return;const n=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||es(e,i,Jt)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const u=t[l];if(es({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c},u,Jt))return l}for(let l=0;l<t.length;l++){const u=t[l];if(js(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const u=t[l];if(js(e.attrs,u.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;!this.shouldLoadPlaylist(t)||Di(t.url,this.hls)&&this.scheduleLoading(t,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==null?void 0:n.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${(t==null?void 0: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.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class hh{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const n=(s=this.tracks[e])==null?void 0:s.buffer;n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
23${this.list("video")}
24${this.list("audio")}
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==null?void 0: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 Da=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rl="HlsJsTrackRemovedError";
25class fh extends Error{constructor(e){super(e),this.name=rl}}class gh extends lt{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_ATTA
vendor: 1,637 bytes, line 25
25CHED,{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=Fc(Kt(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;
vendor: 21,016 bytes, lines 25-27
25e.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?he(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=he({},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=Kt(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,Ca(s),mh(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})
26required tracks: ${ge(s,(c,l)=>c==="initSegment"?void 0:l)};
27transfer tracks: ${ge(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!Ja(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,u=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(u-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,r.forEach(c=>{const l=c,u=i[l];if(u){const d=u.buffer;if(d){const h=this.fragmentTracker,g=u.id;if(h.hasFragments(g)||h.hasParts(g)){const E=J.getBuffered(d);h.detectEvictedFragments(l,E,g,null,!0)}const f=or(l),y=[l,d];this.sourceBuffers[f]=y,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,u)}}}),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&&Ca(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[or(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new hh(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,u;const d=t[c],{id:h,codec:g,levelCodec:f,container:y,metadata:E,supplemental:v}=d;let T=i[c];const S=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],x=S!=null&&S.buffer?S:T,A=(x==null?void 0:x.pendingCodec)||(x==null?void 0:x.codec),P=x==null?void 0:x.levelCodec;T||(T=i[c]={buffer:void 0,listeners:[],codec:g,supplemental:v,container:y,levelCodec:f,metadata:E,id:h});const L=Ei(A,P),p=L==null?void 0:L.replace(Da,"$1");let D=Ei(g,f);const I=(u=D)==null?void 0:u.replace(Da,"$1");D&&L&&p!==I&&(c.slice(0,5)==="audio"&&(D=Ri(D,this.appendSource)),this.log(`switching codec ${A} to ${D}`),D!==(T.pendingCodec||T.codec)&&(T.pendingCodec=D),T.container=y,this.appendChangeType(c,y,D))}),(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,K.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&&J.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,K.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:u}=t,d=l.buffering[r],{sn:h,cc:g}=o,f=self.performance.now();d.start=f;const y=o.stats.buffering,E=c?c.stats.buffering:null;y.start===0&&(y.start=f),E&&E.start===0&&(E.start=f);const v=s.audio;let T=!1;r==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=s.video,x=S==null?void 0:S.buffer;if(x&&h!=="initSegment"){const L=c||o,p=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const I=L.start+L.duration*.05,k=x.buffered,N=this.currentOp("video");!k.length&&!N?this.blockAudio(L):!N&&!J.isBuffered(x,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(L)}else if(r==="video"){const D=L.end;if(p){const I=p.frag.start;(D>I||D<this.lastVideoAppendEnd||J.isBuffered(x,I))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const A=(c||o).start,P={label:`append-${r}`,execute:()=>{var L;d.executeStart=self.performance.now();const p=(L=this.tracks[r])==null?void 0:L.buffer;p&&(T?this.updateTimestampOffset(p,A,.1,r,h,g):u!==void 0&&G(u)&&this.updateTimestampOffset(p,u,1e-6,r,h,g)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const L=self.performance.now();d.executeEnd=d.end=L,y.first===0&&(y.first=L),E&&E.first===0&&(E.first=L);const p={};this.sourceBuffers.forEach(([D,I])=>{D&&(p[D]=J.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:p})},onError:L=>{var p;const D={type:W.MEDIA_ERROR,parent:o.type,details:_.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:L,err:L,fatal:!1},I=(p=this.media)==null?void 0:p.error;if(L.code===DOMException.QUOTA_EXCEEDED_ERR||L.name=="QuotaExceededError"||"quota"in L)D.details=_.BUFFER_FULL_ERROR;else if(L.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)D.errorAction=Es(!0);else if(L.name===rl&&this.sourceBufferCount===0)D.errorAction=Es(!0);else{const k=++this.appendErrors[r];this.warn(`Failed ${k}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I||"no media error"})`),(k>=this.hls.config.appendErrorMaxRetry||!!I)&&(D.fatal=!0)}this.hls.trigger(m.ERROR,D)}};this.log(`queuing "${r}" append sn: ${h}${c?" p: "+c.index:""} of ${o.type===K.MAIN?"level":"track"} ${o.level} cc: ${g}`),this.append(P,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[fe.AUDIOVIDEO]?r.push("audiovideo"):(n[fe.AUDIO]&&r.push("audio"),n[fe.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===_.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;G(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(G(o)&&o>=0){const l=Math.max(o,n),u=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,u)}const c=i.frontBufferFlushThreshold;if(G(c)&&c>0){const l=Math.max(i.maxBufferLength,c),u=Math.max(l,n),d=Math.floor(r/n)*n+u;this.flushFrontBuffer(r,n,d)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=J.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=J.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==null?void 0: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),u=Math.max(l,i);return{duration:1/0,start:l,end:u}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return G(r)?{duration:r}:null;const n=this.media.duration,o=G(s.duration)?s.duration:0;return i>o&&i>n||!G(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(G(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}) ${ge(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:W.MEDIA_ERROR,details:_.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":""} ${ge(o)}`);try{const u=s.addSourceBuffer(l),d=or(n),h=[n,u];t[d]=h,o.buffer=u}catch(u){var i;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,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")&&Vs(s,"video")&&(i=ru(i,s));const r=Ei(i,e.levelCodec);return r?t.slice(0,5)==="audio"?Ri(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==null?void 0: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:W.MEDIA_ERROR,details:_.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==null?void 0: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=G(i.duration)?i.duration:1/0,l=G(r.duration)?r.duration:1/0,u=Math.max(0,t),d=Math.min(s,c,l);d>u&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${u},${d}] from the ${e} SourceBuffer`),o.remove(u,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s==null?void 0:s.buffer;if(!i)throw new fh(`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}
27`),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 Ca(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function mh(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function or(a){return a==="audio"?1:0}class on{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_ATTA
vendor: 3,501 bytes, line 27
27CHING,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&&G(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,on.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 ph={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",
vendor: 4,183 bytes, line 27
27KEY:"k",OTHER:"o"},We=ph,yh={HLS:"h"},Eh=yh;class Lt{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Lt?s:new Lt(s))),this.value=e,this.params=t}}const vh="Dict";function Th(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 Sh(a,e,t,s){return new Error(`failed to ${a} "${Th(e)}" as ${t}`,{cause:s})}function It(a,e,t){return Sh("serialize",a,e,t)}class nl{constructor(e){this.description=e}}const Pa="Bare Item",xh="Boolean";function Ah(a){if(typeof a!="boolean")throw It(a,xh);return a?"?1":"?0"}function Lh(a){return btoa(String.fromCharCode(...a))}const Ih="Byte Sequence";function bh(a){if(ArrayBuffer.isView(a)===!1)throw It(a,Ih);return`:${Lh(a)}:`}const Rh="Integer";function _h(a){return a<-999999999999999||999999999999999<a}function al(a){if(_h(a))throw It(a,Rh);return a.toString()}function Dh(a){return`@${al(a.getTime()/1e3)}`}function ol(a,e){if(a<0)return-ol(-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 Ch="Decimal";function Ph(a){const e=ol(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw It(a,Ch);const t=e.toString();return t.includes(".")?t:`${t}.0`}const kh="String",wh=/[\x00-\x1f\x7f]+/;function Oh(a){if(wh.test(a))throw It(a,kh);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Mh(a){return a.description||a.toString().slice(7,-1)}const Fh="Token";function ka(a){const e=Mh(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw It(e,Fh);return e}function wr(a){switch(typeof a){case"number":if(!G(a))throw It(a,Pa);return Number.isInteger(a)?al(a):Ph(a);case"string":return Oh(a);case"symbol":return ka(a);case"boolean":return Ah(a);case"object":if(a instanceof Date)return Dh(a);if(a instanceof Uint8Array)return bh(a);if(a instanceof nl)return ka(a);default:throw It(a,Pa)}}const Nh="Key";function Or(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw It(a,Nh);return a}function ln(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${Or(e)}`:`;${Or(e)}=${wr(t)}`).join("")}function ll(a){return a instanceof Lt?`${wr(a.value)}${ln(a.params)}`:wr(a)}function Bh(a){return`(${a.value.map(ll).join(" ")})${ln(a.params)}`}function Uh(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw It(a,vh);const t=a instanceof Map?a.entries():Object.entries(a),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Lt||(r=new Lt(r));let n=Or(i);return r.value===!0?n+=ln(r.params):(n+="=",Array.isArray(r.value)?n+=Bh(r):n+=ll(r)),n}).join(`,${s}`)}function cl(a,e){return Uh(a,e)}const Et="CMCD-Object",xe="CMCD-Request",Xt="CMCD-Session",Ut="CMCD-Status",$h={br:Et,ab:Et,d:Et,ot:Et,tb:Et,tpb:Et,lb:Et,tab:Et,lab:Et,url:Et,pb:xe,bl:xe,tbl:xe,dl:xe,ltc:xe,mtp:xe,nor:xe,nrr:xe,rc:xe,sn:xe,sta:xe,su:xe,ttfb:xe,ttfbb:xe,ttlb:xe,cmsdd:xe,cmsds:xe,smrt:xe,df:xe,cs:xe,ts:xe,cid:Xt,pr:Xt,sf:Xt,sid:Xt,st:Xt,v:Xt,msd:Xt,bs:Ut,bsd:Ut,cdn:Ut,rtp:Ut,bg:Ut,pt:Ut,ec:Ut,e:Ut},Gh={REQUEST:xe};function Vh(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 Kh(a,e){const t={};if(!a)return t;const s=Object.keys(a),i=e?Vh(e):{};return s.reduce((r,n)=>{var o;const c=$h[n]||i[n]||Gh.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[n]=a[n],r},t)}function Hh(a){return["ot","sf","st","e","sta"].includes(a)}function Yh(a){return typeof a=="number"?G(a):a!=null&&a!==""&&a!==!1}const ul="event";function Wh(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 Ai=a=>Math.round(a),Mr=(a,e)=>Array.isArray(a)?a.map(t=>Mr(t,e)):a instanceof Lt&&typeof a.value=="string"?new Lt(Mr(a.value,e),a.params):(e.baseUrl&&(a=Wh(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),ci=a=>Ai(a/100)*100,qh=(a,e)=>{let t=a;return e.version>=2&&(a instanceof Lt&&typeof a.value=="string"?t=new Lt([a]):typeof a=="str
27ing"&&(t=[a])),Mr(t,e)},jh={br:Ai,d:Ai,bl:ci,dl:ci,mtp:ci,nor:qh,rtp:ci,tb:Ai},dl="request",hl="response",cn=["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"],zh=["e"],Xh=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function $i(a){return Xh.test(a)}function Qh(a){return cn.includes(a)||zh.includes(a)||$i(a)}const fl=["d","dl","nor","ot","rtp","su"];function Zh(a){return cn.includes(a)||fl.includes(a)||$i(a)}const Jh=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ef(a){return cn.includes(a)||fl.includes(a)||Jh.includes(a)||$i(a)}const tf=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function sf(a){return tf.includes(a)||$i(a)}const rf={[hl]:ef,[ul]:Qh,[dl]:Zh};function gl(a,e={}){const t={};if(a==null||typeof a!="object")return t;const s=e.version||a.v||1,i=e.reportingMode||dl,r=s===1?sf:rf[i];let n=Object.keys(a).filter(r);const o=e.filter;typeof o=="function"&&(n=n.filter(o));const c=i===hl||i===ul;c&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");const l=he({},jh,e.formatters),u={version:s,reportingMode:i,baseUrl:e.baseUrl};return n.sort().forEach(d=>{let h=a[d];const g=l[d];if(typeof g=="function"&&(h=g(h,u)),d==="v"){if(s===1)return;h=s}d=="pr"&&h===1||(c&&d==="ts"&&!G(h)&&(h=Date.now()),Yh(h)&&(Hh(d)&&typeof h=="string"&&(h=new nl(h)),t[d]=h))}),t}function nf(a,e={}){const t={};if(!a)return t;const s=gl(a,e),i=Kh(s,e==null?void 0:e.customHeaderMap);return Object.entries(i).reduce((r,[n,o])=>{const c=cl(o,{whitespace:!1});return c&&(r[n]=c),r},t)}function af(a,e,t){return he(a,nf(e,t))}const of="CMCD";function lf(a,e={}){return a?cl(gl(a,e),{whitespace:!1}):""}function cf(a,e={}){if(!a)return"";const t=lf(a,e);return encodeURIComponent(t)}function uf(a,e={}){if(!a)return"";const t=cf(a,e);return`${of}=${t}`}const wa=/CMCD=[^&#]+/;function df(a,e,t){const s=uf(e,t);if(!s)return a;if(wa.test(a))return a.replace(wa,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class hf{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:We.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===We.VIDEO||c===We.AUDIO||c==We.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const u=n?this.getNextPart(n):this.getNextFrag(r);u!=null&&u.url&&u.url!==r.url&&(l.nor=u.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;
27e.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:Eh.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){he(t,this.createData());const s=t.ot===We.INIT||t.ot===We.VIDEO||t.ot===We.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={}),af(e.headers,t,r)):e.url=df(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 We.TIMED_TEXT;if(e.sn==="initSegment")return We.INIT;if(t==="audio")return We.AUDIO;if(t==="main")return this.hls.audioTracks.length?We.VIDEO:We.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===We.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===We.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:J.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 ff=3e5;class gf extends lt{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)}
vendor: 3,514 bytes, line 27
27startLoad(){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==null?void 0:s.action)===Ne.SendAlternateToPenaltyBox&&s.flags===Ze.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===_.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: ${ge(r)} penalized: ${ge(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]>ff&&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,Oo(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===ie.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===ie.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(u=>u.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(u=>{const d=new ye(u.attrs);d["PATHWAY-ID"]=n;const h=d.AUDIO&&`${d.AUDIO}_clone_${n}`,g=d.SUBTITLES&&`${d.SUBTITLES}_clone_${n}`;
27h&&(s[d.AUDIO]=h,d.AUDIO=h),g&&(i[d.SUBTITLES]=g,d.SUBTITLES=g);const f=ml(u.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new Hs({attrs:d,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let E=1;E<u.audioGroups.length;E++)y.addGroupId("audio",`${u.audioGroups[E]}_clone_${n}`);if(u.subtitleGroups)for(let E=1;E<u.subtitleGroups.length;E++)y.addGroupId("text",`${u.subtitleGroups[E]}_clone_${n}`);return y});t.push(...l),Oa(this.audioTracks,s,c,n),Oa(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 u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+u)}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:(u,d,h,g)=>{this.log(`Loaded steering manifest: "${i}"`);const f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":y,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":v}=f;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||h.url),E&&this.clonePathways(E);const T={steeringManifest:f,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v)},onError:(u,d,h,g)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${d.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let f=this.timeToLoad*1e3;if(u.code===429){const y=this.loader;if(typeof(y==null?void 0:y.getResponseHeader)=="function"){const E=y.getResponseHeader("Retry-After");E&&(f=parseFloat(E)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,f)},onTimeout:(u,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.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 Oa(a,e,t,s){!a||Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=he({},n);return o.details=void 0,o.attrs=new ye(o.attrs),o.url=o.attrs.URI=ml(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 ml(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n==null?void 0: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 Ts extends lt{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=Ts.CDMCleanupPromise?[Ts.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=Bs(this.config));const o=n.map(Ji).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=Ti(n);if(s!=="sinf"||o!==Ee.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const g=Pe(new Uint8Array(i)),f=Xr(JSON.parse(g).sinf),y=lo(f);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}const l=Be(c),{keyIdToKeySessionPromise:u,mediaKeySessions:d}=this;let h=u[l];for(let g=0;g<d.length;g++){const f=d[g],y=f.decryptdata;if(!y.keyId)continue;const E=Be(y.keyId);if(ki(c,y.keyId)||y.uri.replace(/-/g,"").indexOf(l)!==-1){if(h=u[E],!h)continue;if(y.pssh)break;delete u[E],y.pssh=new Uint8Array(i),y.keyId=c,h=u[l]=h.then(()=>this.generateRequestWithPreferredKeySession(f,s,i,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${d.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}
27registerListeners(){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==null?void 0:t[e];if(i)return i.licenseUrl;if(e===Ee.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==null?void 0: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 u=l.shift();this.getMediaKeysPromise(u,i,r).then(d=>n({keySystem:u,mediaKeys:d})).catch(d=>{l.length?c(l):d instanceof Qe?o(d):o(new Qe({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.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 bo===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=qu(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: ${ge(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 u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const d=c.mediaKeys=l.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,u.then(g=>g?this.setMediaKeysServerCertificate(h,e,g):h)));return d.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),d})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Be(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=ui(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 ${Be(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})=>Ji(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=Ji(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=Bs(this.config),s=e.map(Ti).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=mf(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=ui(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=Ma(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",u=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,u,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return n.catch(o=>{if(o instanceof Qe){const c=le({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Qe(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 Qe){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Be(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}
vendor: 13,107 bytes, line 28
28getKeySystemForKeyPromise(e){const t=ui(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Ti(e.keyFormat),r=i?[i]:Bs(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Bs(this.config)),e.length===0)throw new Qe({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ge({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 f=n.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=f.initData?f.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=ui(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 Zr,u=e._onmessage=f=>{const y=e.mediaKeysSession;if(!y){l.emit("error",new Error("invalid state"));return}const{messageType:E,message:v}=f;this.log(`"${E}" message event for session "${y.sessionId}" message size: ${v.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,v).catch(T=>{l.eventNames().length?l.emit("error",T):this.handleError(T)}):E==="license-release"?e.keySystem===Ee.FAIRPLAY&&this.updateKeySession(e,Rr("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${E}"`)},d=(f,y)=>{y.keyStatus=f;let E;f.startsWith("usable")?l.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?E=Ma(f,y.decryptdata):f==="expired"?E=new Error(`key expired (keyId: ${o})`):f==="released"?E=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),E&&(l.eventNames().length?l.emit("error",E):this.handleError(E))},h=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const E=this.getKeyStatuses(e);if(!Object.keys(E).some(x=>E[x]!=="status-pending"))return;if(E[o]==="expired"){this.log(`Expired key ${ge(E)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=E[o];if(T)d(T,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),d(A,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${1e3}ms`),T="internal-error",d(T,e)},1e3)),this.log(`No status for keyId ${o} (${ge(E)}).`)}};He(e.mediaKeysSession,"message",u),He(e.mediaKeysSession,"keystatuseschange",h);const g=new Promise((f,y)=>{l.on("error",y),l.on("resolved",f)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new Qe({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))).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);if(e.keySystem===Ee.PLAYREADY&&r.length===16){const o=Be(r);t[o]=s,Lo(r)}const n=Be(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,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,g,f,y)=>{n(h.data)},onError:(h,g,f,y)=>{o(new Qe({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:le({url:c.url,data:void 0},h)},`"${e}" certificate request failed (${r}). Status: ${h.code} (${h.text})`))},onTimeout:(h,g,f)=>{o(new Qe({type:W.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(h,g,f)=>{o(new Error("aborted"))}};i.load(c,u,d)})):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 Qe({type:W.KEY_SYSTEM_ERROR,details:_.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 Qe({type:W.KEY_SYSTEM_ERROR,details:_.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 u;for(let d=0,h=r.length;d<h;d++){var n,o;u=r[d];const g=(n=u.querySelector("name"))==null?void 0:n.textContent,f=(o=u.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const c=i.querySelector("Challenge"),l=c==null?void 0:c.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Rr(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(u){this.error(u)}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 Qe({type:W.KEY_SYSTEM_ERROR,details:_.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 u=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} 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==Ee.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,He(s,"encrypted",this.onMediaEncrypted),He(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(je(e,"encrypted",this.onMediaEncrypted),je(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,Vt.clearKeyUriToKeyIdMap();const r=i.length;Ts.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:W.OTHER_ERROR,details:_.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:W.OTHER_ERROR,details:_.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: ${Be((i==null?void 0: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(zu(o)?new Promise((l,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(u)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.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:W.OTHER_ERROR,details:_.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Ts.CDMCleanupPromise=void 0;function ui(a){if(!a)throw new Error("Could not read keyId of undefined decryptdata");if(a.keyId===null)throw new Error("keyId is null");return Be(a.keyId)}function mf(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 Qe 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 Ma(a,e){const t=a==="output-restricted",s=t?_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Qe({type:W.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class pf{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}
vendor: 6,129 bytes, line 28
28registerListeners(){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 u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=u)&&(u=u-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,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 pl(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 yl(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){ce.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){ce.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function ys(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 Fr(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=Ef(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 yf(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 Ef(a,e,t){const s=[],i=yf(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 Li(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 vf extends an{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=Li(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;
vendor: 9,402 bytes, line 28
28Li(s.textTracks).forEach(n=>{ys(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==null?void 0: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==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(n=>(i==null?void 0:i.indexOf(n))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(u=>u.default)&&(this.selectDefaultTrack=!1),n.forEach((u,d)=>{u.id=d});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const u=xt(o,n);if(u>-1)r=n[u];else{const d=xt(o,this.tracks);r=this.tracks[d]}}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==null?void 0: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||es(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(js(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(js(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(kr(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===ie.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&&es(e,s))return s;const i=xt(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=xt(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==null?void 0:n.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${(t==null?void 0: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=Li(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>kr(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||!G(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:u}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:c,type:l,url:u});const d=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(d)}}function Tf(){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 Gs(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const Ss=.025;let Fi=function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a}({});function Sf(a,e,t){return`${a.identifier}-${t+1}-${Gs(e)}`}class xf{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 lr(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=lr(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=G(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 lr(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)<Ss))}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"?Fi.Range:Fi.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 Af(this)}}function lr(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<Ss)?e.start:e.start+e.duration}function El(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function cr(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function Af(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function gs(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Lf{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetail
vendor: 4,234 bytes, line 28
28s=!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 u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,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=El(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=J.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=J.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: ${gs(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Fa=.033;class If extends lt{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={}
vendor: 11,712 bytes, lines 28-29
28,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,u)=>{const d=l.cue.pre,h=l.cue.post,g=u.cue.pre,f=u.cue.post;if(d&&!g)return-1;if(g&&!d||h&&!f)return 1;if(f&&!h)return-1;if(!d&&!g&&!h&&!f){const y=l.startTime,E=u.startTime;if(y!==E)return y-E}return l.dateRange.tagOrder-u.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==null?void 0: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 xf(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((u,d)=>{const h=u.cue.pre,g=u.cue.post,f=e[d-1]||null,y=u.appendInPlace,E=g?r:u.startOffset,v=u.duration,T=u.timelineOccupancy===Fi.Range?v:0,S=u.resumptionOffset,x=(f==null?void 0:f.startTime)===E,A=E+u.cumulativeDuration;let P=y?A+v:E+S;if(h||!g&&E<=0){const p=l;l+=T,u.timelineStart=A;const D=n;n+=v,s.push({event:u,start:A,end:P,playout:{start:D,end:n},integrated:{start:p,end:l}})}else if(E<=r){if(!x){const I=E-c;if(I>Fa){const k=c,N=l;l+=I;const B=n;n+=I;const Y={previousEvent:e[d-1]||null,nextEvent:u,start:k,end:k+I,playout:{start:B,end:n},integrated:{start:N,end:l}};s.push(Y)}else I>0&&f&&(f.cumulativeDuration+=I,s[s.length-1].end=E)}g&&(P=A),u.timelineStart=A;const p=l;l+=T;const D=n;n+=v,s.push({event:u,start:A,end:P,playout:{start:D,end:n},integrated:{start:p,end:l}})}else return;const L=u.resumeTime;g||L>r?c=r:c=L}),c<r){var o;const u=c,d=l,h=r-c;l+=h;const g=n;n+=h,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:u+h,playout:{start:g,end:n},integrated:{start:d,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,u=o.cue.post,d=l?0:u?i:o.startTime;this.updateAssetDurations(o),n===d?o.cumulativeDuration=r:(r=0,n=d),!u&&o.snapOptions.in&&(o.resumeAnchor=ts(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<Fa&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const g=G(o.resumeOffset)?o.resumeOffset:o.duration;r+=g})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Ss?(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=ts(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 u=n==="audio"?.175:0;return Math.abs(l.start-s)<Ss+u||Math.abs(l.end-s)<Ss+u?!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 ut(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class bf{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=El(s,this.hls.sessionId,e.baseUrl)}catch(h){const g=this.assignAssetListError(e,_.ASSET_LIST_LOAD_ERROR,h,s);this.hls.trigger(m.ERROR,g);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,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,g,f,y)=>{const E=h.data,v=E==null?void 0:E.ASSETS;if(!Array.isArray(v)){const T=this.assignAssetListError(e,_.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,g,y);this.hls.trigger(m.ERROR,T);return}e.assetListResponse=E,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:E,networkDetails:y})},onError:(h,g,f,y)=>{const E=this.assignAssetListError(e,_.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${g.url})`),g.url,y,f);this.hls.trigger(m.ERROR,E)},onTimeout:(h,g,f)=>{const y=this.assignAssetListError(e,_.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,h,f);this.hls.trigger(m.ERROR,y)}};return o.load(c,u,d),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:W.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function Na(a){var e;a==null||(e=a.play())==null||e.catch(()=>{})}function di(a,e){return`[${a}] Advancing timeline position to ${e}`}class Rf extends lt{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 g=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(s);if(f===-1&&(f=g+(n?-1:1),this.log(`seeked ${n?"back ":""}to position not covered by schedule ${s} (resolving from ${g} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!n&&f>g){const y=this.schedule.findJumpRestrictedIndex(g+1,f);if(y>g){this.setSchedulePosition(y);return}}this.setSchedulePosition(f);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const g=o.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,g))}return}const u=l.timelineStart,d=l.duration||0;if(n&&s<u||s>=u+d){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(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,u=s.map(y=>y.identifier),d=!!(o.length||u.length);(d||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
29Schedule: ${c.map(y=>ut(y))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let h=null,g=null;n&&(h=this.updateItem(n,this.timelinePos),this.itemsMatch(n,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(g=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,g)?this.bufferingItem=g:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),s.forEach(y=>{y.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){const E=y.assetItem.timelineStart,v=y.timelineOffset-E;if(v)try{y.timelineOffset=E}catch(T){Math.abs(v)>Ss&&this.warn(`${T} ("${y.assetId}" ${y.timelineOffset}->${E})`)}}}),d||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:u}),this.isInterstitial(n)&&u.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(h,n),f&&g!==h&&this.trimInPlace(g,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new bf(e),this.schedule=new If(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;
vendor: 5,692 bytes, line 29
29e&&(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){je(e,"play",this.onPlay),je(e,"pause",this.onPause),je(e,"seeking",this.onSeeking),je(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;He(s,"seeking",this.onSeeking),He(s,"timeupdate",this.onTimeupdate),He(s,"play",this.onPlay),He(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=d=>d&&e.getAssetPlayer(d.identifier),i=(d,h,g,f,y)=>{if(d){let E=d[h].start;const v=d.event;if(v){if(h==="playout"||v.timelineOccupancy!==Fi.Point){const T=s(g);(T==null?void 0:T.interstitial)===v&&(E+=T.assetItem.startOffset+T[y])}}else{const T=f==="bufferedPos"?n():e[f];E+=T-d.start}return E}return 0},r=(d,h)=>{var g;if(d!==0&&h!=="primary"&&(g=e.schedule)!=null&&g.length){var f;const y=e.schedule.findItemIndexAtTime(d),E=(f=e.schedule.items)==null?void 0:f[y];if(E){const v=E[h].start-E.start;return d+v}}return d},n=()=>{const d=e.bufferedPos;return d===Number.MAX_VALUE?o("primary"):Math.max(d,0)},o=d=>{var h,g;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[d])||0},c=(d,h)=>{var g,f;const y=e.effectivePlayingItem;if(y!=null&&(g=y.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${h}"`);const E=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(d,h),T=(f=e.schedule.items)==null?void 0:f[v],S=e.getBufferingPlayer(),x=S==null?void 0:S.interstitial,A=x==null?void 0:x.appendInPlace,P=E&&e.itemsMatch(E,T);if(E&&(A||P)){const L=s(e.playingAsset),p=(L==null?void 0:L.media)||e.primaryMedia;if(p){const D=h==="primary"?p.currentTime:i(E,h,e.playingAsset,"timelinePos","currentTime"),I=d-D,k=(A?D:p.currentTime)+I;if(k>=0&&(!L||A||k<=L.duration)){p.currentTime=k;return}}}if(T){let L=d;if(h!=="primary"){const D=T[h].start,I=d-D;L=T.start+I}const p=!e.isInterstitial(T);if((!e.isInterstitial(E)||E.event.appendInPlace)&&(p||T.event.appendInPlace)){const D=e.media||(A?S==null?void 0:S.media:null);D&&(D.currentTime=L)}else if(E){const D=e.findItemIndex(E);if(v>D){const k=e.schedule.findJumpRestrictedIndex(D+1,v);if(k>D){e.setSchedulePosition(k);return}}let I=0;if(p)e.timelinePos=L,e.checkBuffer();
vendor: 33,742 bytes, line 29
29else{const k=T.event.assetList,N=d-(T[h]||T).start;for(let B=k.length;B--;){const Y=k[B];if(Y.duration&&N>=Y.startOffset&&N<Y.startOffset+Y.duration){I=B;break}}}e.setSchedulePosition(v,I)}}},l=()=>{const d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;const h=t();return e.isInterstitial(h)?h:null},u={get bufferedEnd(){const d=t(),h=e.bufferingItem;if(h&&h===d){var g;return i(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const d=l(),h=e.effectivePlayingItem;return h&&h===d?i(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(d){const h=l(),g=e.effectivePlayingItem;g&&g===h&&c(d+g.playout.start,"playout")},get duration(){const d=l();return d?d.playout.end-d.playout.start:0},get assetPlayers(){var d;const h=(d=l())==null?void 0:d.event.assetList;return h?h.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var d;const h=(d=l())==null?void 0:d.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return l()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const d=t();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return n()},get currentTime(){const d=e.timelinePos;return d>0?d:0},set currentTime(d){c(d,"primary")},get duration(){return o("primary")},get seekableStart(){var d;return((d=e.primaryDetails)==null?void 0:d.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(d){c(d,"integrated")},get duration(){return o("integrated")},get seekableStart(){var d;return r(((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0,"integrated")}},skip:()=>{const d=e.effectivePlayingItem,h=d==null?void 0:d.event;if(h&&!h.restrictions.skip){const g=e.findItemIndex(d);if(h.appendInPlace){const f=d.playout.start+d.event.duration;c(f+.001,"playout")}else e.advanceAfterAssetEnded(h,g,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||!G(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} ${ge(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 u;if(n.media)c&&(r=n.transferMedia(),this.detachedData=r),u="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),u=`${f}`):u="detached MediaSource"}else u="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ge(r)}`);else if(!this.detachedData||n.media===t){const f=this.playerQueue;f.length>1&&f.forEach(y=>{if(o&&y.interstitial.appendInPlace!==c){const E=y.interstitial;this.clearInterstitial(y.interstitial,null),E.appendInPlace=!1,E.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${E}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const d=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",h=d&&r?r:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);const g=this.schedule;if(h===r&&g){const f=o&&e.assetId===g.assetIdAtEnd;h.overrides={duration:g.duration,endOfStream:!o||f,cueRemoval:!o}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0: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(di("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=cr(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=cr(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(di("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&&ut(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const u=n.event,d=this.playingAsset,h=d==null?void 0:d.identifier,g=h?this.getAssetPlayer(h):null;if(g&&h&&(!this.eventItemsMatch(n,r)||t!==void 0&&h!==u.assetList[t].identifier)){var c;const f=u.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${u.assetList.length} ${gs(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:f,event:u,schedule:i.slice(0),scheduleIndex:e,player:g}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(h,r),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${ut(n)}`),u.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:u,schedule:i.slice(0),scheduleIndex:e}),u.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(r&&f){const y=this.findItemIndex(r);this.advanceSchedule(y,f,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(u=>{const d=u.interstitial,h=n.findEventIndex(d.identifier);(h<e||h>e+1)&&this.clearInterstitial(d,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(s===void 0){s=n.findAssetIndex(u,this.timelinePos);const f=cr(u,s-1);if(u.isAssetPastPlayoutLimit(f)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=f}const d=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let h=this.preloadAssets(u,s);if(this.eventItemsMatch(o,d||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${ut(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const g=u.assetList[s];if(!g){this.advanceAfterAssetEnded(u,e,s||0);return}if(h||(h=this.getAssetPlayer(g.identifier)),h===null||h.destroyed){const f=u.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${u}`),h=this.createAssetPlayer(u,g,s),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(h,s,t,e,c),this.shouldPlay&&Na(h.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Na(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 ${ut(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(di("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 ${ut(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:J.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(di("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=le(le({},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=le(le({},this.altSelection),{},{audio:s});return}const r=le(le({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=le(le({},this.altSelection),{},{subtitles:s});return}const r=le(le({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Wn(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Wn(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=J.bufferInfo(this.primaryMedia,s,0);if(i.end>s||(i.nextStart||0)>s){this.log(`trim buffered interstitial ${ut(e)} (was ${ut(t)})`);const r=!0;this.attachPrimary(s,null,r),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=J.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 u=this.findItemIndex(r),d=Math.min(u+1,t.length-1),h=t[d];if((c===-1&&r&&e>=r.end||(l=h.event)!=null&&l.appendInPlace&&e+.01>=h.start)&&(c=d),this.isInterstitial(r)){const g=r.event;if(d-o>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,c>u&&c>o)this.bufferedToItem(h);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&h.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.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 ${ut(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,d)=>{const h=this.getAssetPlayer(u.identifier);h&&(d===l&&h.loadSource(),h.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 h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){const h=u-c;h>0&&(l=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${u} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const d=this.assetListLoader.loadAssetList(e,l);d&&(e.assetListLoader=d)}else if(!n&&i){for(let l=t;l<i;l++){const u=e.assetList[l],d=this.getAssetPlayerQueueIndex(u.identifier);(d===-1||this.playerQueue[d].destroyed)&&!u.error&&this.createAssetPlayer(e,u,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:Sf(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=he({},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 u=0;if(this.primaryLive||e.appendInPlace){const x=this.timelinePos-t.timelineStart;if(x>1){const A=t.duration;A&&x<A&&(u=x)}}const d=t.identifier,h=le(le({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const g=h.cmcd;g!=null&&g.sessionId&&g.contentId&&(h.cmcd=he({},g,{contentId:Gs(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const f=new Lf(this.HlsPlayerClass,h,e,t);this.playerQueue.push(f),e.assetList[s]=t;let y=!0;const E=x=>{if(x.live){var A;const p=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:p},I=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,I,s,p.message);return}const P=x.edge-x.fragmentStart,L=t.duration;(y||L===null||P>L)&&(y=!1,this.log(`Interstitial asset "${d}" duration change ${L} > ${P}`),t.duration=P,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(x,{details:A})=>E(A)),f.on(m.LEVEL_PTS_UPDATED,(x,{details:A})=>E(A)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(x,A)=>{const P=this.getAssetPlayer(d);if(P&&A.tracks){P.off(m.BUFFER_CODECS,v),P.tracks=A.tracks;const L=this.primaryMedia;this.bufferingAsset===P.assetItem&&L&&!P.media&&this.bufferAssetPlayer(P,L)}};f.on(m.BUFFER_CODECS,v);const T=()=>{var x;const A=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;const P=this.schedule.findEventIndex(e.identifier),L=(x=this.schedule.items)==null?void 0:x[P];this.isInterstitial(L)&&this.advanceAssetBuffering(L,t)};f.on(m.BUFFERED_TO_END,T);const S=x=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const P=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,P,x)};return f.once(m.MEDIA_ENDED,S(s)),f.once(m.PLAYOUT_LIMIT_REACHED,S(1/0)),f.on(m.ERROR,(x,A)=>{if(!this.schedule)return;const P=this.getAssetPlayer(d);if(A.details===_.BUFFER_STALLED_ERROR){if(P!=null&&P.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${d}`),P={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(P,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${gs(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}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&&ut(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,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,s[i]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${gs(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 u=r.appendInPlace;if(u&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const d=(l==null?void 0:l.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(u&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!Ja(d,e.tracks)){const h=new Error(`Asset ${gs(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),g={fatal:!0,type:W.OTHER_ERROR,details:_.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},f=r.findAssetIndex(n);this.handleAssetItemError(g,r,o,f,h.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 u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===_.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&gs(n)} ${e.error}`),!this.schedule)return;const o=(n==null?void 0:n.identifier)||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,u=this.schedule.items,d=he({},e,{fatal:!1,errorAction:Es(!0),asset:n,assetListIndex:i,event:t,schedule:u,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const h=this.playingAsset,g=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(o,null),n.error=f),!t.assetList.some(y=>!y.error))t.error=f;else for(let y=i;y<t.assetList.length;y++)this.resetAssetPlayer(t.assetList[y].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,s,i):g&&g.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${ut(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}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 u=0;o.forEach((y,E)=>{const v=parseFloat(y.DURATION);this.createAsset(r,E,u,c+u,v,y.URI),u+=v}),r.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${l}) ${r}`);const d=this.waitingItem,h=(d==null?void 0:d.event.identifier)===n;this.updateSchedule();const g=(i=this.bufferingItem)==null?void 0:i.event;if(h){var f;const y=this.schedule.findEventIndex(n),E=(f=this.schedule.items)==null?void 0:f[y];if(E){if(!this.playingItem&&this.timelinePos>E.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==y){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(E)}this.setSchedulePosition(y)}else if((g==null?void 0:g.identifier)===n){const y=r.assetList[0];if(y){const E=this.getAssetPlayer(y.identifier);if(g.appendInPlace){const v=this.primaryMedia;E&&v&&this.bufferAssetPlayer(E,v)}else E&&E.loadSource()}}}onError(e,t){if(!!this.schedule)switch(t.details){case _.ASSET_LIST_PARSING_ERROR:case _.ASSET_LIST_LOAD_ERROR:case _.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case _.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 Ba=500;class _f extends Qr{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",K.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=w.IDLE,this.setInterval(Ba),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)||(be(s)&&(this.fragPrevious=s),this.state=w.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,K.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===K.SUBTITLE&&(t.details===_.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==w.STOPPED&&(this.state=w.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&il(this.levels,t)){this.levels=t.map(s=>new Hs(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Hs(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,K.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!==w.STOPPED&&this.setInterval(Ba)}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 d=this.mainDetails;if(!d){this.startFragRequested=!1;return}const h=d.fragments[0];if(!c.details)n.hasProgramDateTime&&d.hasProgramDateTime?(Oi(n,d),l=n.fragmentStart):h&&(l=h.start,Dr(n,l));else{var u;l=this.alignPlaylists(n,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),l===0&&h&&(l=h.start,Dr(n,l))}d&&!this.startFragRequested&&this.setStartPosition(d,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===w.IDLE&&(ts(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&&vs(i.method)){const n=performance.now();
vendor: 28,995 bytes, lines 29-40
29this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,zr(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.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=w.IDLE})}}doTick(){if(!this.media){this.state=w.IDLE;return}if(this.state===w.IDLE){const{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=J.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=n,l=s.details,u=this.hls.maxBufferLength+l.levelTargetDuration;if(c>u)return;const d=l.fragments,h=d.length,g=l.edge;let f=null;const y=this.fragPrevious;if(o<g){const T=i.maxFragLookUpTolerance,S=o>g-T?0:T;f=ts(y,d,Math.max(d[0].start,o),S),!f&&y&&y.start<d[0].start&&(f=d[0])}else f=d[h-1];if(f=this.filterReplacedPrimary(f,s.details),!f)return;const E=f.sn-l.startSN,v=d[E-1];if(v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===ke.NOT_LOADED&&(f=v),this.fragmentTracker.getState(f)===ke.NOT_LOADED){const T=this.mapToInitFragWhenRequired(f);T&&this.loadFragment(T,s,o)}}}loadFragment(e,t,s){be(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Df(this.tracksBuffered[this.currentTrackId]||[])}}class Df{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 Cf={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},vl=a=>String.fromCharCode(Cf[a]||a),ht=15,Pt=100,Pf={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},kf={17:2,18:4,21:6,22:8,23:10,19:13,20:15},wf={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Of={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Mf=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ff{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ce.log(`${this.time} [${e}] ${s}`)}}}const Qt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Tl{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 Nf{constructor(){this.uchar=" ",this.penState=new Tl}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 Bf{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Tl,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Pt;t++)this.chars.push(new Nf);this.logger=e}equals(e){for(let t=0;t<Pt;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Pt;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Pt;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>Pt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Pt)}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=vl(e);if(this.pos>=Pt){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<Pt;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<Pt;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 ur{constructor(e){this.rows=[],this.currRow=ht-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ht;t++)this.rows.push(new Bf(e));this.logger=e}reset(){for(let e=0;e<ht;e++)this.rows[e].clear();this.currRow=ht-1}equals(e){let t=!0;for(let s=0;s<ht;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<ht;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ht;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 = "+ge(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<ht;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 = "+ge(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<ht;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`)),s}getTextAndFormat(){return this.rows}}class Ua{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 ur(s),this.nonDisplayedMemory=new ur(s),this.lastOutputScreen=new ur(s),this.currRollUpRow=this.displayedMemory.rows[ht-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[ht-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: "+ge(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 $a{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=$f(),this.logger=void 0;const i=this.logger=new Ff;this.channels=[null,new Ua(e,t,i),new Ua(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,()=>"["+Qt([t[s],t[s+1]])+"] -> ("+Qt([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Uf(i,r,c)){hi(null,null,c),this.logger.log(3,()=>"Repeated command ("+Qt([i,r])+") is dropped");continue}hi(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 hi(null,null,c);if(!n&&(o=this.parseChars(i,r),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Qt([i,r])+" orig: "+Qt([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 ("+Qt([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?Pf[e]:wf[e]:s=n===1?kf[e]:Of[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 '"+vl(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 =  "+Qt(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=Mf[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()}hi(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 hi(a,e,t){t.a=a,t.b=e}function Uf(a,e,t){return t.a===a&&t.b===e}function $f(){return{a:null,b:null}}var un=function(){if(wi!=null&&wi.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 u=arguments[l];for(const d in u)o[d]=u[d]}return o}function n(o,c,l){const u=this,d={enumerable:!0};u.hasBeenReset=!1;let h="",g=!1,f=o,y=c,E=l,v=null,T="",S=!0,x="auto",A="start",P=50,L="middle",p=50,D="middle";Object.defineProperty(u,"id",r({},d,{get:function(){return h},set:function(I){h=""+I}})),Object.defineProperty(u,"pauseOnExit",r({},d,{get:function(){return g},set:function(I){g=!!I}})),Object.defineProperty(u,"startTime",r({},d,{get:function(){return f},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");f=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",r({},d,{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(u,"text",r({},d,{get:function(){return E},set:function(I){E=""+I,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",r({},d,{get:function(){return v},set:function(I){v=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",r({},d,{get:function(){return T},set:function(I){const k=s(I);if(k===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",r({},d,{get:function(){return S},set:function(I){S=!!I,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",r({},d,{get:function(){return x},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");x=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",r({},d,{get:function(){return A},set:function(I){const k=i(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");A=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",r({},d,{get:function(){return P},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");P=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",r({},d,{get:function(){return L},set:function(I){const k=i(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");L=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",r({},d,{get:function(){return p},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",r({},d,{get:function(){return D},set:function(I){const k=i(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");D=k,this.hasBeenReset=!0}})),u.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Gf{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Sl(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 Vf{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 xl(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 Nr=new un(0,0,""),fi=Nr.align==="middle"?"middle":"center";function Kf(a,e,t){const s=a;function i(){const o=Sl(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 Vf;xl(o,function(h,g){let f;switch(h){case"region":for(let y=t.length-1;y>=0;y--)if(t[y].id===g){l.set(h,t[y].region);break}break;case"vertical":l.alt(h,g,["rl","lr"]);break;case"line":f=g.split(","),l.integer(h,f[0]),l.percent(h,f[0])&&l.set("snapToLines",!1),l.alt(h,f[0],["auto"]),f.length===2&&l.alt("lineAlign",f[1],["start",fi,"end"]);break;case"position":f=g.split(","),l.percent(h,f[0]),f.length===2&&l.alt("positionAlign",f[1],["start",fi,"end","line-left","line-right","auto"]);break;case"size":l.percent(h,g);break;case"align":l.alt(h,g,["start",fi,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let u=l.get("line","auto");u==="auto"&&Nr.line===-1&&(u=-1),c.line=u,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",fi);let d=l.get("position","auto");d==="auto"&&Nr.position===50&&(d=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=d}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 Al(a){return a.replace(/<br(?: \/)?>/gi,`
31`)}class Hf{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Gf,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=Al(r);n<r.length&&r[n]!=="\r"&&r[n]!==`
32`;)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===`
33`&&++n,t.buffer=r.slice(n),o}function i(r){xl(r,function(n,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new un(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Kf(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
34`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
35
36`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Yf=/\r\n|\n\r|\n|\r/g,dr=function(e,t,s=0){return e.slice(s,s+t.length)===t},Wf=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!G(t)||!G(s)||!G(i)||!G(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=60*60*1e3*r,t};function dn(a,e,t){return Gs(a.toString())+Gs(e.toString())+Gs(t)}const qf=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function jf(a,e,t,s,i,r,n){const o=new Hf,c=tt(new Uint8Array(a)).trim().replace(Yf,`
37`).split(`
38`),l=[],u=e?Jd(e.baseTime,e.timescale):0;let d="00:00.000",h=0,g=0,f,y=!0;o.oncue=function(E){const v=t[s];let T=t.ccOffset;const S=(h-u)/9e4;if(v!=null&&v.new&&(g!==void 0?T=t.ccOffset=v.start:qf(t,s,S)),S){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}T=S-t.presentationOffset}const x=E.endTime-E.startTime,A=Je((E.startTime+T-g)*9e4,i*9e4)/9e4;E.startTime=Math.max(A,0),E.endTime=Math.max(A+x,0);const P=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(P)),E.id||(E.id=dn(E.startTime,E.endTime,P)),E.endTime>0&&l.push(E)},o.onparsingerror=function(E){f=E},o.onflush=function(){if(f){n(f);return}r(l)},c.forEach(E=>{if(y)if(dr(E,"X-TIMESTAMP-MAP=")){y=!1,E.slice(16).split(",").forEach(v=>{dr(v,"LOCAL:")?d=v.slice(6):dr(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{g=Wf(d)/1e3}catch(v){f=v}return}else E===""&&(y=!1);o.parse(E+`
39`)}),o.flush()}const hr="stpp.ttml.im1t",Ll=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Il=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,zf={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ga(a,e,t,s){const i=te(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>tt(o)),n=Zd(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Xf(o,n)))}catch(o){s(o)}}function Xf(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((d,h)=>(d[h]=i.getAttribute(`ttp:${h}`)||r[h],d),{}),o=i.getAttribute("xml:space")!=="preserve",c=Va(fr(i,"styling","style")),l=Va(fr(i,"layout","region")),u=fr(i,"body","[begin]");return[].map.call(u,d=>{const h=bl(d,o);if(!h||!d.hasAttribute("begin"))return null;const g=mr(d.getAttribute("begin"),n),f=mr(d.getAttribute("dur"),n);let y=mr(d.getAttribute("end"),n);if(g===null)throw Ka(d);if(y===null){if(f===null)throw Ka(d);y=g+f}const E=new un(g-e,y-e,h);E.id=dn(E.startTime,E.endTime,E.text);const v=l[d.getAttribute("region")],T=c[d.getAttribute("style")],S=Qf(v,T,c),{textAlign:x}=S;if(x){const A=zf[x];A&&(E.lineAlign=A),E.align=x}return he(E,S),E}).filter(d=>d!==null)}function fr(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Va(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function bl(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
40`:(r=s.childNodes)!=null&&r.length?bl(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Qf(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,c)=>{const l=gr(e,s,c)||gr(a,s,c)||gr(i,s,c);return l&&(o[c]=l),o},{})}function gr(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function Ka(a){return new Error(`Could not parse ttml timestamp ${a}`)}function mr(a,e){if(!a)return null;let t=Sl(a);return t===null&&(Ll.test(a)?t=Zf(a,e):Il.test(a)&&(t=Jf(a,e))),t}function Zf(a,e){const t=Ll.exec(a),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function Jf(a,e){const t=Il.exec(a),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class gi{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class eg{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Ya(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}}
vendor: 3,593 bytes, line 40
40,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_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){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_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new gi(this,"textTrack1"),t=new gi(this,"textTrack2"),s=new gi(this,"textTrack3"),i=new gi(this,"textTrack4");this.cea608Parser1=new $a(1,e,t),this.cea608Parser2=new $a(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const c=r[o],l=tg(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),n=!0,l/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:o}=this;s===K.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,c):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Ha(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(r,n);if(o)s[e]=o,ys(s[e]),pl(s[e],i);else{const c=this.createTextTrack("captions",r,n);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(!!i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;
vendor: 9,813 bytes, line 40
40Object.keys(i).forEach(r=>{ys(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Ya(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)ys(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===hr);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(il(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media,o=n?Li(n.textTracks):null;if(this.tracks.forEach((c,l)=>{let u;if(o){let d=null;for(let h=0;h<o.length;h++)if(o[h]&&Ha(o[h],c)){d=o[h],o[h]=null;break}d&&(u=d)}if(u)ys(u);else{const d=Rl(c);u=this.createTextTrack(d,c.name,c.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,n=this.captionsProperties[r];!n||(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===K.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:o}=this,{cc:c,sn:l}=t.frag,u=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(l!==o+1||l===o&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===K.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===hr?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Ga(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?ot(s.initSegment.data,new Uint8Array(i)).buffer:i;jf(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,u=>{this._appendCues(u,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},u=>{const d=u.message==="Missing initPTS for VTT MPEGTS";d?n.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${u}`),!(d&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:u})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Ga(t,this.initPTS[e.cc],()=>{s.textCodec=hr,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>yl(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===K.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===K.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const n=i[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(n);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>Fr(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>Fr(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&n)!==0){const u=3&n;(u===0||u===1)&&(t[u].push(o),t[u].push(c))}}return t}}function Rl(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Ha(a,e){return!!a&&a.kind===Rl(e)&&kr(e,a)}function tg(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function Ya(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const sg=/\s/,ig={newCue(a,e,t,s){const i=[];let r,n,o,c,l;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(r=s.rows[h],o=!0,c=0,l="",!r.isEmpty()){var d;for(let y=0;y<r.chars.length;y++)sg.test(r.chars[y].uchar)&&o?c++:(l+=r.chars[y].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const g=Al(l.trim()),f=dn(e,t,g);a!=null&&(d=a.cues)!=null&&d.getCueById(f)||(n=new u(e,t,g),n.id=f,n.line=h+1,n.align="left",n.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(n))}return a&&i.length&&(i.sort((h,g)=>h.line==="auto"||g.line==="auto"?0:h.line>8&&g.line>8?g.line-h.line:h.line-g.line),i.forEach(h=>yl(a,h))),i}};function rg(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const ng=/(\d+)-(\d+)\/(\d+)/;class Wa{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||cg,this.controller=new self.AbortController,this.stats=new Vr}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=ag(e,this.controller.signal),n=e.responseType==="arraybuffer",o=n?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&G(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(qs(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var h;this.response=this.loader=d;const g=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(g-i.loading.start)),!d.ok){const{status:y,statusText:E}=d;throw new ug(E||"fetch, bad network response",y,d)}i.loading.first=g,i.total=lg(d.headers)||i.total;const f=(h=this.callbacks)==null?void 0:h.onProgress;return f&&G(t.highWaterMark)?this.loadProgressively(d,i,e,t.highWaterMark,f):n?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var h,g;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const y=d[o];y&&(i.loaded=i.total=y);const E={url:f.url,data:d,code:f.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!G(t.highWaterMark)&&v(i,e,d,f),(g=this.callbacks)==null||g.onSuccess(E,i,e,f)}).catch(d=>{var h;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const g=d&&d.code||0,f=d?d.message:null;(h=this.callbacks)==null||h.onError({code:g,text:f},e,d?d.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new No,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=l.value,d=u.length;return t.loaded+=d,d<i||n.dataLength?(n.push(u),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,u.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function ag(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(he({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function og(a){const e=ng.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function lg(a){const e=a.get("Content-Range");if(e){const s=og(e);
vendor: 5,623 bytes, line 40
40if(G(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}function cg(a,e){return new self.Request(a.url,e)}class ug extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const dg=/^age:\s*[\d.]+\s*$/im;class _l{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Vr,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&G(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,u=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const f=u!=null?u:t.response;if(f!=null){var n,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const y=t.responseType==="arraybuffer"?f.byteLength:f.length;s.loaded=s.total=y,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const E=(n=this.callbacks)==null?void 0:n.onProgress;E&&E(s,e,f,t);const v={url:t.responseURL,data:f,code:l};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}const d=r.loadPolicy.errorRetry,h=s.retry,g={url:e.url,data:void 0,code:l};if(Pi(d,h,!1,g))this.retry(d);else{var c;ce.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Pi(e,t,!0))this.retry(e);else{var s;ce.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Wr(e,s.retry),s.retry++,ce.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&dg.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const hg={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},fg=le(le({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftw
vendor: 6,052 bytes, line 40
40areAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:_l,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Lu,bufferController:gh,capLevelController:on,errorController:Du,fpsController:pf,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:bo,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:hg},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},gg()),{},{subtitleStreamController:_f,subtitleTrackController:vf,timelineController:eg,audioStreamController:uh,audioTrackController:dh,emeController:Ts,cmcdController:hf,contentSteeringController:gf,interstitialsController:Rf});function gg(){return{cueHandler:ig,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function mg(a,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Br(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(u=>{const d=`${n}Loading${u}`,h=e[d];if(h!==void 0&&c){l.push(d);const g=s[o].default;switch(e[o]={default:g},u){case"TimeOut":g.maxLoadTimeMs=h,g.maxTimeToFirstByteMs=h;break;case"MaxRetry":g.errorRetry.maxNumRetry=h,g.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":g.errorRetry.retryDelayMs=h,g.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=h,g.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ge(e[o])}`)}),le(le({},s),e)}function Br(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Br):Object.keys(a).reduce((e,t)=>(e[t]=Br(a[t]),e),{}):a}function pg(a,e){const t=a.loader;t!==Wa&&t!==_l?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):rg()&&(a.loader=Wa,a.progressive=!0,a.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Ii=2,yg=.1,Eg=.05,vg=100;class Tg extends So{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;
vendor: 25,215 bytes, line 40
40e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(vg),this.mediaSource=t.mediaSource;const s=this.media=t.media;He(s,"playing",this.onMediaPlaying),He(s,"waiting",this.onMediaWaiting),He(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(je(s,"playing",this.onMediaPlaying),je(s,"waiting",this.onMediaWaiting),je(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,c=this.seeking&&!o,l=!this.seeking&&o,u=n.paused&&!o||n.ended||n.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!J.getBuffered(n).length){this.nudgeRetry=0;return}const d=J.bufferInfo(n,e,0),h=d.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const P=qa(this.hls.inFlightFragments,e),L=d.len>Ii,p=!h||P||h-e>Ii&&!g.getPartialFragment(e);if(L||p)return;this.moved=!1}const f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(d.len>0)&&!h)return;const L=Math.max(h,d.start||0)-e,D=!!(f!=null&&f.live)?f.targetduration*2:Ii,I=mi(e,g);if(L>0&&(L<=D||I)){n.paused||this._trySkipBufferHole(I);return}}const y=r.detectStallWithCurrentTimeMs,E=self.performance.now(),v=this.waiting;let T=this.stalled;if(T===null)if(v>0&&E-v<y)T=this.stalled=v;else{this.stalled=E;return}const S=E-T;if(!o&&(S>=y||v)&&this.hls){var x;if(((x=this.mediaSource)==null?void 0:x.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-((f==null?void 0:f.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const A=J.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(A,S,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=J.bufferedInfo(J.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=J.timeRangesToArray(i),o=J.bufferedInfo(n,t,0).bufferedIndex;if(o>-1&&o<n.length-1){const c=J.bufferedInfo(n,e,0).bufferedIndex,l=n[o].end,u=n[o+1].start;if((c===-1||c>o)&&u-l<1&&e-l<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${u} buffered index: ${c}`);this.warn(d.message),this.media.currentTime+=1e-6;let h=mi(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const g=J.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!n||!c)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,u=mi(s,n);if((u||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const d=e.buffered,h=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||h))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,K.MAIN),n=s.getFragAtPos(i,K.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ge(e)})`);this.warn(n.message),t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,o=J.bufferInfo(i,n,0),c=n<o.start?o.start:o.nextStart;if(c&&this.hls){const u=o.len<=r.maxBufferHole,d=o.len>0&&o.len<1&&i.readyState<3,h=c-n;if(h>0&&(u||d)){if(h>r.maxBufferHole){let f=!1;if(n===0){const y=s.getAppendedFrag(0,K.MAIN);y&&c<y.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||qa(this.hls.inFlightFragments,c))return 0;let E=!1,v=e.end;for(;v<c;){const T=mi(v,s);if(T)v+=T.duration;else{E=!0;break}}if(E)return 0}}const g=Math.max(c+Eg,n+yg);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${g}`),this.moved=!0,i.currentTime=g,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${g}`),y={type:W.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?y.part=e:y.frag=e),this.hls.trigger(m.ERROR,y)}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t==null?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=n+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${n} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function qa(a,e){const t=ja(a.main);if(t&&t.start<=e)return t;const s=ja(a.audio);return s&&s.start<=e?s:null}function ja(a){if(!a)return null;switch(a.state){case w.IDLE:case w.STOPPED:case w.ENDED:case w.ERROR:return null}return a.frag}function mi(a,e){return e.getAppendedFrag(a,K.MAIN)||e.getPartialFragment(a)}const Sg=.25;function Ur(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function pr(a,e,t,s,i){let r=new a(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new a(e,t,ge(i?le({type:i},s):s))}return r}const pi=(()=>{const a=Ur();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class xg{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{!this.hls||this.hls.trigger(m.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;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.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&ys(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(!!this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return pl(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Ur();if(!!n)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===et.emsg&&!s||!i)continue;const l=Ho(r[o].data),u=r[o].pts;let d=u+r[o].duration;d>pi&&(d=pi),d-u<=0&&(d=u+Sg);for(let g=0;g<l.length;g++){const f=l[g];if(!Yo(f)){this.updateId3CueEnds(u,c);const y=pr(n,u,d,f,c);y&&this.id3Track.addCue(y)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===pi&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=n;if(r&&(o||c)){let l;i==="audio"?l=u=>u.type===et.audioId3&&c:i==="video"?l=u=>u.type===et.emsg&&o:l=u=>u.type===et.audioId3&&c||u.type===et.emsg&&o,Fr(r,t,s,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const o=Ur();if(s&&i&&!n){const{fragmentStart:y,fragmentEnd:E}=e;let v=this.assetCue;v?(v.startTime=y,v.endTime=E):o&&(v=this.assetCue=pr(o,y,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,u=Object.keys(l);let d=this.dateRangeCuesAppended;if(c&&t){var h;if((h=c.cues)!=null&&h.length){const y=Object.keys(d).filter(E=>!u.includes(E));for(let E=y.length;E--;){var g;const v=y[E],T=(g=d[v])==null?void 0:g.cues;delete d[v],T&&Object.keys(T).forEach(S=>{const x=T[S];if(x){x.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(x)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(u.length===0||!G(f==null?void 0:f.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let y=0;y<u.length;y++){const E=u[y],v=l[E],T=v.startTime,S=d[E],x=(S==null?void 0:S.cues)||{};let A=(S==null?void 0:S.durationKnown)||!1,P=pi;const{duration:L,endDate:p}=v;if(p&&L!==null)P=T+L,A=!0;else if(v.endOnNext&&!A){const I=u.reduce((k,N)=>{if(N!==v.id){const B=l[N];if(B.class===v.class&&B.startDate>v.startDate&&(!k||v.startDate<k.startDate))return B}return k},null);I&&(P=I.startTime,A=!0)}const D=Object.keys(v.attr);for(let I=0;I<D.length;I++){const k=D[I];if(!Vu(k))continue;const N=x[k];if(N)A&&!(S!=null&&S.durationKnown)?N.endTime=P:Math.abs(N.startTime-T)>.01&&(N.startTime=T,N.endTime=P);else if(o){let B=v.attr[k];Ku(k)&&(B=eo(B));const $=pr(o,T,P,{key:k,data:B},et.dateRange);$&&($.id=E,this.id3Track.addCue($),x[k]=$,n&&(k==="X-ASSET-LIST"||k==="X-ASSET-URL")&&$.addEventListener("enter",this.onEventCueEnter))}}d[E]={cues:x,dateRange:v,durationKnown:A}}}}}class Ag{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(d,Math.max(1,h));this.changeMediaPlaybackRate(t,g)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*i);const u=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;!e||(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.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;!e||(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.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===_.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class Lg extends an{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let o=!1,c=!1,l=!1;t.levels.forEach(u=>{const d=u.attrs;let{audioCodec:h,videoCodec:g}=u;h&&(u.audioCodec=h=Ri(h,s)||void 0),g&&(g=u.videoCodec=nu(g));const{width:f,height:y,unknownCodecs:E}=u,v=(E==null?void 0:E.length)||0;if(o||(o=!!(f&&y)),c||(c=!!g),l||(l=!!h),v||h&&!this.isAudioSupported(h)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":x,"PATHWAY-ID":A,RESOLUTION:P,"VIDEO-RANGE":L}=d,D=`${`${A||"."}-`}${u.bitrate}-${P}-${S}-${T}-${L}-${x}`;if(r[D])if(r[D].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const I=n[D]+=1;u.attrs["PATHWAY-ID"]=new Array(I+1).join(".");const k=this.createLevel(u);r[D]=k,i.push(k)}else r[D].addGroupId("audio",d.AUDIO),r[D].addGroupId("text",d.SUBTITLES);else{const I=this.createLevel(u);r[D]=I,n[D]=1,i.push(I)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new Hs(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=fo(i,[])}return t}isAudioSupported(e){return Vs(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Vs(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let o=[],c=[],l=e;const u=((n=t.stats)==null?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:T,videoRange:S,width:x,height:A})=>(!!T||!!(x&&A))&&mu(S))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",S=T;t.levels.length&&(S=`one or more CODECS in variant not supported: ${ge(t.levels.map(A=>A.attrs.CODECS).filter((A,P,L)=>L.indexOf(A)===P))}`,this.warn(S),T+=` (${S})`);const x=new Error(T);this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:x,reason:S})}}),u.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),za(o)),t.subtitles&&(c=t.subtitles,za(c));const d=l.slice(0);l.sort((T,S)=>{if(T.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&T.height!==S.height)return T.height-S.height;if(T.frameRate!==S.frameRate)return T.frameRate-S.frameRate;if(T.videoRange!==S.videoRange)return _i.indexOf(T.videoRange)-_i.indexOf(S.videoRange);if(T.videoCodec!==S.videoCodec){const x=$n(T.videoCodec),A=$n(S.videoCodec);if(x!==A)return A-x}if(T.uri===S.uri&&T.codecSet!==S.codecSet){const x=bi(T.codecSet),A=bi(S.codecSet);if(x!==A)return A-x}return T.averageBitrate!==S.averageBitrate?T.averageBitrate-S.averageBitrate:0});let h=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let T=0;T<d.length;T++)if(d[T].pathwayId===l[0].pathwayId){h=d[T];break}}this._levels=l;for(let T=0;T<l.length;T++)if(l[T]===h){var g;this._firstLevel=T;const S=h.bitrate,x=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${S}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const A=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);A>x&&x===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const f=r&&!i,y=this.hls.config,E=!!(y.audioStreamController&&y.audioTrackController),v={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:E&&!f&&o.some(T=>!!T.url)};u.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:u,reason:u.message}),d)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const c={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=n.details;if(!l||l.live){const u=this.switchParams(n.uri,i==null?void 0:i.details,l);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===ie.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===K.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;if(!n){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let c=n.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLo
vendor: 4,447 bytes, line 40
40ading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,o=n==null?void 0:n.age;this.log(`Loading level index ${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Oo(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function za(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Dl(){return self.SourceBuffer||self.WebKitSourceBuffer}function Cl(){if(!Kt())return!1;const e=Dl();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Ig(){if(!Cl())return!1;const a=Kt();return typeof(a==null?void 0:a.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(Ks(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(Ks(e,"audio"))))}function bg(){var a;const e=Dl();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const Rg=100;class _g extends Qr{constructor(e,t,s){super(e,t,s,"stream-controller",K.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!G(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(i,r,K.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}
vendor: 36,476 bytes, line 40
40startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(Rg),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=w.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=w.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case w.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e==null?void 0:e[t],i=s==null?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=w.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=w.IDLE;break}break}case w.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===w.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const n=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const y={};this.altAudio===2&&(y.type="video"),this.hls.trigger(m.BUFFER_EOS,y),this.state=w.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===w.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=w.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,d=this.getMaxBufferLength(n.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&be(g)&&this.fragmentTracker.getState(g)!==ke.OK){var f;const E=((f=this.backtrackFragment)!=null?f:g).sn-l.startSN,v=l.fragments[E-1];v&&g.cc===v.cc&&(g=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,h)){if(!g.gap){const E=this.audioOnly&&!this.altAudio?fe.AUDIO:fe.VIDEO,v=(E===fe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,E,K.MAIN)}g=this.getNextFragmentLoopLoading(g,l,o,K.MAIN,d)}!g||(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,n,h))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===ke.NOT_LOADED||i===ke.PARTIAL?be(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,K.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,u=Math.max(n.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case w.KEY_LOADING:case w.FRAG_LOADING:case w.FRAG_LOADING_WAITING_RETRY:case w.PARSING:case w.PARSED:this.state=w.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;He(s,"playing",this.onMediaPlaying),He(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(je(s,"playing",this.onMediaPlaying),je(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!bg(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==w.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=w.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,u=this.fragCurrent;u&&(this.state===w.FRAG_LOADING||this.state===w.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let d=0;if(o.live||(s=l.details)!=null&&s.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,d),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:n}),this.state===w.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=w.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,o=e.edge,c=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){const u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const d=J.bufferInfo(s,i,0);if(!((l=d.buffered)!=null&&l.length)){s.currentTime=i;return}if(d.start<=r){s.currentTime=i;return}const{nextStart:g}=J.bufferedInfo(d.buffered,r,0);g&&(s.currentTime=g)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=n[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,u=c.PTSKnown||!c.live,d=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new sl(this.hls,K.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,y=f!==-1,E=new jr(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,y),v=this.initPTS[s.cc];g.push(r,d,h,l,s,i,c.totalduration,u,E,v)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if(Di(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{!this.hls||this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Di(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===K.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===w.PARSED&&(this.state=w.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),be(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;!n||(!this._hasEnoughToStart&&J.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=w.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(K.MAIN,t);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===w.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===ie.LEVEL&&(this.state=w.IDLE);break;case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case _.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=w.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==fe.AUDIO||!this.altAudio){const s=(t===fe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,K.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=J.getBuffered(e),o=n.length?n.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*((r==null?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s==null?void 0:s.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=w.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===w.STOPPED||this.state===w.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:o,part:c,level:l}=n,{video:u,text:d,id3:h,initSegment:g}=i,{details:f}=l,y=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=w.PARSING,g){const E=g.tracks;if(E){const x=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(l,E,x,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:t,tracks:E})}const v=g.initPTS,T=g.timescale,S=this.initPTS[o.cc];if(G(v)&&(!S||S.baseTime!==v||S.timescale!==T)){const x=g.trackId;this.initPTS[o.cc]={baseTime:v,timescale:T,trackId:x},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:T,trackId:x})}}if(u&&f){y&&u.type==="audiovideo"&&this.logMuxedErr(o);const E=f.fragments[o.sn-1-f.startSN],v=o.sn===f.startSN,T=!E||o.cc>E.cc;if(i.independent!==!1){const{startPTS:S,endPTS:x,startDTS:A,endDTS:P}=u;if(c)c.elementaryStreams[u.type]={startPTS:S,endPTS:x,startDTS:A,endDTS:P};else if(u.firstKeyFrame&&u.independent&&r.id===1&&!T&&(this.couldBacktrack=!0),u.dropped&&u.independent){const L=this.getMainFwdBufferInfo(),p=(L?L.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!v&&p<D-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,x,o.start,P,!0)}else v&&S-(f.appliedTimelineOffset||0)>Ii&&(o.gap=!0);o.setElementaryStreamInfo(u.type,S,x,A,P),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,r,v||T)}else if(v||T)o.gap=!0;else{this.backtrack(o);return}}if(y){const{startPTS:E,endPTS:v,startDTS:T,endDTS:S}=y;c&&(c.elementaryStreams[fe.AUDIO]={startPTS:E,endPTS:v,startDTS:T,endDTS:S}),o.setElementaryStreamInfo(fe.AUDIO,E,v,T,S),this.bufferFragmentData(y,o,c,r)}if(f&&h!=null&&h.samples.length){const E={id:t,frag:o,details:f,samples:h.samples};s.trigger(m.FRAG_PARSING_METADATA,E)}if(f&&d){const E={id:t,frag:o,details:f,samples:d.samples};s.trigger(m.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${be(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==w.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:o}=t;if(r){const l=e.audioCodec;let u=Ei(r.codec,l);u==="mp4a"&&(u="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const h=r.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),l&&l!==u&&this.log(`Swapping manifest audio codec "${l}" for "${u}"`),r.levelCodec=u,r.id=K.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${u||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=K.MAIN;const l=n.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:d,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,K.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=w.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(J.isBuffered(e,s)?t=this.getAppendedFrag(s):J.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return G(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(G(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?ts(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const n=r+(t-i.start)*1e3;return new Date(n)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Dg extends lt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=_.KEY_LOAD_ERROR,s,i,r){return new kt({type:W.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!be(e)||!be(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(o=>{if(!this.emeController)return;n.setKeyFormat(o);const c=Ti(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=Bs(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const o=yr(r);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(u=>{const{keyInfo:d}=u;return r.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+Be(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const n=qc(t.initSegment.data);if(n.length){let o=n[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Be(o)}`),Vt.setKeyIdForUri(e.decryptdata.uri,o)):(o=Vt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Be(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!be(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,s))).catch(n=>{throw e.keyLoadPromise=null,"data"in n&&(n.data.frag=t),n})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,g,f,y)=>{const{frag:E,keyInfo:v}=f,T=yr(v.decryptdata);if(!E.decryptdata||v!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(E,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));v.decryptdata.key=E.decryptdata.key=new Uint8Array(h.data),E.keyLoader=null,v.loader=null,n({frag:E,keyInfo:v})},onError:(h,g,f,y)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),f,le({url:c.url,data:void 0},h)))},onTimeout:(h,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(h,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(c,u,d)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=yr(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function yr(a){if(a.keyFormat!==Ue.FAIRPLAY){const e=a.keyId;if(e)return Be(e)}return a.uri}function Xa(a){const{type:e}=a;switch(e){case ie.AUDIO_TRACK:return K.AUDIO;case ie.SUBTITLE_TRACK:return K.SUBTITLE;default:return K.MAIN}}function Er(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Cg{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ie.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:ie.LEVEL,url:n,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:ie.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:ie.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[ie.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[ie.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,u=i.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===ie.MANIFEST?r=s.manifestLoadPolicy.default:r=he({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),G((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===ie.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===ie.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===ie.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const u=l.partTarget,d=l.targetduration;if(u&&d){const h=Math.max(u*3,d*.8)*1e3;r=he({},r,{maxTimeToFirstByteMs:Math.min(h,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},c={onSuccess:(l,u,d,h)=>{const g=this.getInternalLoader(d);this.resetInternalLoader(d.type);const f=l.data;u.parsing.start=performance.now(),At.isMediaPlaylist(f)||d.type!==ie.MANIFEST?this.handleTrackOrLevelPlaylist(l,u,d,h||null,g):this.handleMasterPlaylist(l,u,d,h)},onError:(l,u,d,h)=>{this.handleNetworkError(u,d,!1,l,h)},onTimeout:(l,u,d)=>{this.handleNetworkError(u,d,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=Er(e,s),c=At.parseMasterPlaylist(n,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:u,sessionData:d,sessionKeys:h,startTimeOffset:g,variableList:f}=c;this.variableList=f,u.forEach(T=>{const{unknownCodecs:S}=T;if(S){const{preferManagedMediaSource:x}=this.hls.config;let{audioCodec:A,videoCodec:P}=T;for(let L=S.length;L--;){const p=S[L];Vs(p,"audio",x)?(T.audioCodec=A=A?`${A},${p}`:p,xs.audio[A.substring(0,4)]=2,S.splice(L,1)):Vs(p,"video",x)&&(T.videoCodec=P=P?`${P},${p}`:p,xs.video[P.substring(0,4)]=2,S.splice(L,1))}}});const{AUDIO:y=[],SUBTITLES:E,"CLOSED-CAPTIONS":v}=At.parseMasterPlaylistMedia(n,o,c);y.length&&!y.some(S=>!S.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ye({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:u,audioTracks:y,subtitles:E,captions:v,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:h,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:c,type:l}=s,u=Er(e,s),d=G(c)?c:G(o)?o:0,h=Xa(s),g=At.parseLevelPlaylist(e.data,u,d,h,0,this.variableList);if(l===ie.MANIFEST){const f={attrs:new ye({}),bitrate:0,details:g,name:"",url:u};g.requestScheduled=t.loading.start+Po(g,0),n.trigger(m.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.MANIFEST_PARSING_ERROR,fatal:t.type===ie.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===ie.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===ie.AUDIO_TRACK||e.type===ie.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let c=_.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case ie.MANIFEST:c=s?_.MANIFEST_LOAD_TIMEOUT:_.MANIFEST_LOAD_ERROR,l=!0;break;case ie.LEVEL:c=s?_.LEVEL_LOAD_TIMEOUT:_.LEVEL_LOAD_ERROR,l=!1;break;case ie.AUDIO_TRACK:c=s?_.AUDIO_TRACK_LOAD_TIMEOUT:_.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ie.SUBTITLE_TRACK:c=s?_.SUBTITLE_TRACK_LOAD_TIMEOUT:_.SUBTITLE_LOAD_ERROR,l=!1;break}u&&this.resetInternalLoader(e.type);const d={type:W.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:r};if(i){const h=(t==null?void 0:t.url)||e.url;d.response=le({url:h,data:void 0},i)}this.hls.trigger(m.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:c,level:l,levelOrTrack:u,id:d,groupId:h,deliveryDirectives:g}=i,f=Er(t,i),y=Xa(i);let E=typeof i.level=="number"&&y===K.MAIN?l:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:i,level:E,parent:y,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:_.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:T,reason:T.message,response:t,context:i,level:E,parent:y,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case ie.MANIFEST:case ie.LEVEL:if(E){if(!u)E=0;else if(u!==o.levels[E]){const T=o.levels.indexOf(u);T>-1&&(E=T)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:E||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:g,withoutMultiVariant:c===ie.MANIFEST});break;case ie.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:g});break;case ie.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:s,networkDetails:r,deliveryDirectives:g});break}}}class ft{static get version(){return Ys}static isMSESupported(){return Cl()}static isSupported(){return Ig()}static getMediaSource(){return Kt()}static get Events(){return m}static get MetadataSchema(){return et}static get ErrorTypes(){return W}static get ErrorDetails(){return _}static get DefaultConfig(){return ft.defaultConfig?ft.defaultConfig:fg}static set DefaultConfig(e){ft.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Zr,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=Mc(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=mg(ft.DefaultConfig,e,t);this.userConfig=e,s.progressive&&pg(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:o,fpsController:c}=s,l=new o(this),u=this.abrController=new i(this),d=new Cu(this),h=s.interstitialsController,g=h?this.interstitialsController=new h(this,ft):null,f=this.bufferController=new r(this,d),y=this.capLevelController=new n(this),E=new c(this),v=new Cg(this),T=s.contentSteeringController,S=T?new T(this):null,x=this.levelController=new Lg(this,S),A=new xg(this),P=new Dg(this.config,this.logger),L=this.streamController=new _g(this,d,P),p=this.gapController=new Tg(this,d);y.setStreamController(L),E.setStreamController(L);const D=[v,x,L];g&&D.splice(1,0,g),S&&D.splice(1,0,S),this.networkControllers=D;const I=[u,f,p,y,E,A,d];this.audioTrackController=this.createController(s.audioTrackController,D);const k=s.audioStreamController;k&&D.push(this.audioStreamController=new k(this,d,P)),this.subtitleTrackController=this.createController(s.subtitleTrackController,D);const N=s.subtitleStreamController;N&&D.push(this.subtititleStreamController=new N(this,d,P)),this.createController(s.timelineController,I),P.emeController=this.emeController=this.createController(s.emeController,I),this.cmcdController=this.createController(s.cmcdController,I),this.latencyController=this.createController(Ag,I),this.coreComponents=I,D.push(l);const B=l.onErrorOut;typeof B=="function"&&this.on(m.ERROR,B,l),this.on(m.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}
vendor: 6,307 bytes, line 40
40trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(m.ERROR,{type:W.OTHER_ERROR,details:_.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=Gr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[K.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[K.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[K.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Tf()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){gu(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;
40if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=po(t);return go(e,s,navigator.mediaCapabilities)}}ft.defaultConfig=void 0;const Pg={viewBox:"0 0 24 24",fill:"currentColor"},kg=["d"],vt=zs({__name:"MIcon",props:{path:{}},setup(a){const e=a;return(t,s)=>(ne(),de("svg",Pg,[q("path",{d:e.path},null,8,kg)]))}}),yi=11526/51,vr=400,Qa=zs({__name:"HandyEmulator",props:{position:{default:0}},setup(a){const e=a,t=Ae({});let s=null;const i=new Image;i.src="/handy.positions.vertical.webp",Ni(()=>{s=t.value.getContext("2d"),t.value.width=vr,t.value.height=yi,r(e.position)}),Zt(()=>e.position,()=>r(e.position));const r=n=>{if(!s)return;const o=Math.floor(n/100*51);s.drawImage(i,0,o*yi,vr,yi,0,0,vr,yi)};return(n,o)=>(ne(),de("canvas",{ref_key:"canvas",ref:t},null,512))}}),wg=zs({__name:"RangeSlider",props:{modelValue:{}},emits:["update:modelValue"],setup(a,{emit:e}){const t=a,s=e,i=Ae(!1),r=Ae();Ni(()=>{document.addEventListener("mousemove",n),document.addEventListener("mouseup",c)}),$r(()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",c)});const n=l=>{if(!i.value)return;const u=l.clientX,d=r.value.offsetWidth,{left:h}=r.value.getBoundingClientRect();let f=(u-h)/d;f>1&&(f=1),f<0&&(f=0),s("update:modelValue",f)},o=l=>{i.value=!0,n(l)},c=()=>{i.value=!1};return(l,u)=>(ne(),de("div",null,[q("div",{class:"bg-white/20 relative cursor-pointer select-none w-full h-full rounded-full",ref_key:"seekbar",ref:r,onMousedown:o,onMouseup:c},[q("div",{class:"bg-white h-full rounded-l-full",style:ms(`width: ${t.modelValue*100}%`)},null,4),q("div",{class:"h-3 w-3 absolute -top-1 rounded-full bg-white",style:ms(`left: calc(${t.modelValue*100}% - 6px)`)},null,4)],544)]))}}
40),Og={class:"bg-white/50 rounded-full relative z-0 lg:!h-1",style:{height:"2px"}},Mg=["viewBox"],Fg=["id"],Ng=["points"],Bg=["clip-path"],Za=zs({__name:"Seekbar",props:{value:{},max:{},actions:{}},emits:["seek"],setup(a,{emit:e}){const t=a,s=e,i=Math.random().toString(36).substr(2,9),r=Ae(),n=Ae({enabled:!1,progress:0,overallProgress:0});Ni(()=>{window.addEventListener("mousemove",o),window.addEventListener("mouseup",c)}),$r(()=>{window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",c)});const o=g=>{const f=g.touches?g.touches[0].clientX:g.clientX,y=r.value.offsetWidth,{left:E}=r.value.getBoundingClientRect();let T=(f-E)/y;T>1&&(T=1),T<0&&(T=0),n.value.overallProgress=T,n.value.enabled&&(n.value.progress=T)},c=()=>{!n.value.enabled||(s("seek",n.value.progress*t.max),n.value.enabled=!1)},l=g=>{n.value.enabled=!0,o(g)},u=ps(()=>n.value.enabled?n.value.progress*100:t.value/t.max*100),d=ps(()=>{if(!t.actions||!t.actions.length)return"";let g=Math.max(9/3600*t.max,.75);const f=[];let y=0,E="",v=0;for(let T=0;T<t.max;T+=g){const S=[];for(let A=v;A<t.actions.length;A++){if(t.actions[A][0]/1e3>=T+g){v=A;break}S.push(t.actions[A])}const x=h(S);x>y&&(y=x),f.push([T,x])}if(!f.length)return"";f[0][1]=0,f[f.length-1][1]=0;for(let T=0;T<f.length;T++){let S=f[T][1]/y*100;S=Math.round(Math.abs(100-S)),E+=`${f[T][0]},${S||0} `}return E}),h=g=>{let f=0;if(g.length===0)return f;for(let y=0;y<g.length-1;y++){let E=g[y],v=g[y+1];if(E[0]!==v[0]){if(v[0]<E[0]){let T=v;v=E,E=T}f+=1e3*Math.abs(v[1]-E[1])/Math.abs(v[0]-E[0])}}return f/g.length};return(g,f)=>(ne(),de("div",{class:"w-full cursor-pointer py-2 touch-none select-none group",ref_key:"seekbar",ref:r,onMousedown:l,onTouchstart:l,onTouchmove:o,onTouchcancel:f[0]||(f[0]=y=>n.value.enabled=!1),onTouchend:c},[q("div",Og,[q("div",{class:"h-full bg-white rounded-l-full relative z-10 pointer-events-none",style:ms(`width: ${u.value}%`)},null,4),q("div",{class:dt(["absolute bg-zinc-300/20 rounded-full flex items-center justify-center top-1/2 transform -translate-y-1/2 z-20",{"!bg-zinc-300/50":n.value.enabled}]),style:ms([{height:"22px",width:"22px"},`left: calc(${u.value}% - 11px)`])},[...f[1]||(f[1]=[q("div",{class:"bg-white rounded-full z-20 pointer-events-none",style:{height:"8px",width:"8px"}},null,-1)])],6),q("div",{class:dt(["absolute bg-zinc-900 shadow text-white text-sm font-medium rounded-full py-1 px-2 -top-16 lg:-top-10 hidden group-hover:block",{"!block":n.value.enabled}]),style:ms(`left: calc(${n.value.overallProgress*100}% - 26.5px)`)},qe(oe(Tr)(t.max*n.value.overallProgress)),7),(ne(),de("svg",{viewBox:`0 0 ${t.max} 100`,preserveAspectRatio:"none",class:"absolute left-0 -z-10 w-full h-6 lg:!-top-6",style:{to
40p:"-24px"}},[q("defs",null,[q("clipPath",{id:`hotspots-${oe(i)}`,clipPathUnits:"userSpaceOnUse"},[q("polygon",{points:d.value},null,8,Ng)],8,Fg)]),q("g",{"clip-path":`url(#hotspots-${oe(i)})`},[f[2]||(f[2]=q("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:"rgba(33,29,27,0.75)"},null,-1)),q("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:"#635b58",style:ms(`transform: translate3d(-${100-u.value}%, 0px, 0px);`)},null,4)],8,Bg)],8,Mg))])],544))}}),Ug={class:"flex flex-col"},$g={key:0,class:"absolute top-2 right-2 bg-red-600 text-white p-4 w-auto pr-8 rounded-md z-100 text-right"},Gg={key:2,class:"font-medium text-center text-base lg:text-xl flex items-center flex-col"},Vg={class:"mt-3 mx-auto flex gap-3"},Kg={key:1,class:"absolute right-4 top-4 rounded-lg bg-zinc-900/75 p-2 z-40 lg:block lg:w-1/5 overflow-hidden"},Hg={class:"leading-normal flex flex-col gap-2 w-full h-full"},Yg={class:"bg-white rounded-lg w-full aspect-video overflow-hidden pointer-events-none"},Wg={key:0},qg={key:0,class:"text-start"},jg={class:"font-bold text-green-400"},zg={href:"https://lp.thehandy.com/handy2-offer/?promo=FAPTAP15&ref=faptap&utm_source=faptap&utm_medium=widget&utm_campaign=in-player-widget&utm_content=the-handy",target:"_blank","data-ph-capture-attribute-invideo-handy-ad":"1",class:"block w-full mb-2"},Xg={key:0,class:"absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-white"},Qg=["href"],Zg={class:"flex justify-between"},Jg={class:"flex items-center gap-x-2 justify-start"},em={class:"whitespace-nowrap",style:{"flex-basis":"96px","flex-grow":"0","flex-shrink":"0"}},tm={class:"font-bold"},sm={class:"flex gap-x-2 items-center group"},im={key:0,class:"flex justify-between items-center gap-x-2"},rm={class:"bg-zinc-900 text-xs font-medium py-0.5 px-1.5 rounded-full shadow"},nm={key:0},am={key:0,class:"grid grid-cols-2 gap-3 p-4 text-white rounded-lg max-w-md mx-auto"},om=["onClick"],lm={class:"text-xs text-gray-300"},cm={key:1},um=["onClick"],dm={class:"flex-1"},hm={class:"text-sm text-gray-300 md:text-base"},fm=["loop"],gm={class:"min-height-div text-white text-lg font-bold flex items-center justify-center relative col-6"},mm={key:0,class:"rounded-lg bg-zinc-900/75 p-2 z-40 flex lg:hidden overflow-hidden"},pm={class:"leading-normal flex gap-2 w-full h-full"},ym={class:"bg-white rounded-lg flex-grow max-w-full aspect-video overflow-hidden pointer-events-none"},Em={key:0,class:"flex flex-col flex-shrink max-w-xs"},vm={class:"font-bold text-green-400"},Tm={href:"https://lp.thehandy.com/handy2-offer/?promo=FAPTAP15&ref=faptap&utm_source=faptap&utm_medium=widget&utm_campaign=in-player-widget&utm_content=the-handy",target:"_blank","data-ph-capture-attribute-invideo-handy-ad":"1",class:"block w-full mb-2"},Sm={name:"Player"},_m=zs({...Sm,props:{video:{},isOverlay:{},playlist:{},shuffleMode:{type:Boolean},repeatMode:{type:Boolean},loop:{type:Boolean}},setup(a){const e=ic(),t=rc();let s=null;const i=ps(()=>{if(!c.playlist||c.playlist.length===0)return null;const b=c.playlist.findIndex(C=>String(C.id)===String(c.video.id));if(b===-1)return null;if(c.shuffleMode){const C=c.playlist.filter((j,me)=>me!==b);return C.length?C[Math.floor(Math.random()*C.length)]:null}return b===c.playlist.length-1?c.repeatMode?c.playlist[0]:null:c.playlist[b+1]});function r(b){if(b){let C={...t.query};t.query.playlist&&(C.playlist=t.query.playlist),e.push({path:`/v/${b.id}`,query:C})}}Yl(()=>{p.el&&(p.el.pause(),p.el.src="",p.el.load())});const n=ac();let o;(b=>{b[b.READY=0]="READY",b[b.PREPARING=1]="PREPARING",b[b.ERROR=2]="ERROR",b[b.PROMO=3]="PROMO"})(o||(o={}));const c=a,l=Ae(""),u=Ae(""),d=Wl(),{handy:h,ui:g,autoblow:f,vacuglide:y,bluetoothFleshyThrust:E,fleshyX3:v,osr:T,loob:S}=ql(d),x=Ae(),{isMobile:A}=jl(),P=/Android/i.test(navigator.userAgent);let L=Ae(null);const p=zl(D());function D(){return{hls:new ft,sources:[],actions:[],el:{},state:{settings:!1,state:1,ui:!0,currentTime:0,lastCurrentTime:0,duration:0,playing:!1,fullscreen:!1,loading:!0,source:void 0,volume:1},intervals:{status:-1,progress:-1},timeouts:{hidePlayer:-1,loadingDebounce:-1}}}const I=Ae(!0),k=b=>{p.sources.length!==0&&(b?p.el.play().catch(()=>{p.el.muted=!0,p.el.play()}):p.el.pause())};function N(){nc("advpopup","true"),I.value=!1}const B=Ae(!1),Y=Ae(""),$=Ae(0);function O(){$.value===0&&($.value=0,p.state.loading=!0,B.value=!0)}const V=b=>
40b.url.startsWith("http")?b.url:`/api/${b.url}`,U=(b,C)=>!b||!C?!1:b.format===C.format&&String(b.quality)===String(C.quality)&&V(b)===V(C),H=()=>{!B.value||!p.sources.length||!p.el.paused||p.el.ended||(mt(),p.state.loading=!1,p.state.state!==3&&(p.state.state=0,p.state.message=void 0),k(!0))},X=()=>{const b=Hi(p.sources,L.value);if(!!b){if(U(p.state.source,b)){H(),p.state.lastCurrentTime=0;return}_s(b,!1,"init"),p.state.lastCurrentTime=0}};async function M(b){return F(b)?ei.videos.getBunnySources(c.video.id):ei.videos.getSources(c.video.id)}function F(b){return b||!Dn(c.video.stream_url)}function Z(){gt(),p.state.message=Cn,p.state.state=1,p.state.loading=!1,l.value=""}function ae(){return p.state.state===1&&p.state.message===Cn}function ee(){!oc(c.video)||(re(),u.value=lc,setTimeout(()=>{u.value=""},1e4))}function re(){u.value=""}const pe=Ae(!1);let ve=null,_e=null,Ve=null,Le=!1;const Gi=250,Ls=3e3,Is=15e3,Xs=3e4,se=Ae(0),Te=Ae(!1),Me=Ae(!1),st=Ae(!1),De=Ae(!1),it=Ae(!1),bt=Ae(!1);let Ce=0;function Rt(){ve&&(clearTimeout(ve),ve=null),_e&&(clearInterval(_e),_e=null),l.value=""}function bs(){Ve&&(clearTimeout(Ve),Ve=null)}function Yt(){bs(),it.value=!1,Ve=setTimeout(()=>{it.value=!0},Ls)}function gt(){bs(),st.value=!1,it.value=!1}function Ot(){De.value=!1,Rt()}function _t(){if(pe.value||Te.value||!c.video.stream_url_selfhosted||!c.video.stream_url||De.value)return;Rt(),De.value=!0;let b=Xs/1e3;const C=se.value;_e=setInterval(()=>{if(C!==se.value||!De.value||Te.value){Ot();return}b-=1,Xs/1e3-b>=Is/1e3&&b>0&&!hn()&&(l.value=`Stream is slow. Switching server in ${b}s...`),b<=0&&(clearInterval(_e),_e=null)},1e3),ve=setTimeout(async()=>{C!==se.value||!De.value||Te.value||pe.value||await kl()},Xs)}function mt(){p.timeouts.loadingDebounce!==-1&&(clearTimeout(p.timeouts.loadingDebounce),p.timeouts.loadingDebounce=-1)}const Ke=()=>{if(!p.el||!("paused"in p.el)||!("readyState"in p.el)||p.el.ended)return!1;const b=p.el.readyState>=HTMLMediaElement.HAVE_FUTURE_DATA,C=p.el.currentTime>0,j=Le&&!p.el.paused;return b&&(C||p.state.playing||j||!p.el.paused)},hn=()=>p.el&&rt(p.el);function Rs(){return Ke()?(mt(),Ot(),p.state.loading=!1,l.value="",p.state.state!==2&&p.state.state!==3&&(p.state.state=0),!0):!1}const Vi=async b=>{var Ms;const{targetIsBunny:C,origin:j,resumePlayback:me=!1}=b,z=F(C),Ye=++se.value,Re=!z&&Boolean(c.video.stream_url_selfhosted),rs=B.value&&(me||p.state.playing||!p.el.paused);j==="manual"&&(Te.value=!0),Ce=Math.max(((Ms=p.el)==null?void 0:Ms.currentTime)||0,p.state.currentTime||0,p.state.lastCurrentTime||0),Rt(),mt(),De.value=!1,j==="init"&&(pe.value=!1),p.state.lastCurrentTime=Ce,p.state.loading=!0,p.state.state=1,p.state.playing=!1,Le=rs,l.value="",st.value=!0,Yt();let ue=[],Mt=z;try{ue=await M(z)}catch(we){if(z&&ti(c.video)){Z();return}console.error("[Player] Failed to fetch sources:",we)}if((!ue||ue.length===0)&&Re){const we=!z;!z&&!hn()&&(l.value="FT Server is taking too long to respond. Switching to EXT Server...");try{ue=await M(we),Mt=we,pe.value=!0}catch(ct){if(we&&ti(c.video)){Z();return}console.error("[Player] Fallback server fetch failed:",ct)}}if(Ye!==se.value){gt();return}if(!ue||ue.length===0){if(Mt&&ti(c.video)){Z();return}gt(),p.state.message="Source not found. Please try another video.",p.state.state=2,p.state.loading=!1;return}p.sources=ue,bt.value=Mt,n.isBunny!==Mt&&(Me.value=!0,n.setBunny(Mt));const Os=Hi(p.sources,L.value);if(!Os){gt(),p.state.message="Source not found on selected server.",p.state.state=2,p.state.loading=!1;return}gt(),_s(Os,!0,j)},Pl=b=>{if(b===0){Ot();return}};Zt(()=>p.state.state,b=>{console.log(`[Player] State changed: ${o[b]}`),Pl(b)});const kl=async()=>{console.warn("[Player] Buffer timeout - switching servers"),pe.value=!0,await Vi({targetIsBunny:!n.isBunny,origin:"auto",resumePlayback:!0})};Ni(async()=>{var j,me;$.value=0,Xl("advpopup")==="true"&&(I.value=!1),p.el=document.querySelector("#player");const C=!Dn(c.video.stream_url);if(n.isBunny!==C&&(Me.value=!0,n.setBunny(C)),await Vi({targetIsBunny:C,origin:"init"}),!p.sources||!p.sources.length){if(ti(c.video)){Z();return}Ql.capture("Video File Removed",{videoId:c.video.id}),p.state.message="Source not found. Please try another video.",p.state.state=2;return}if(ei.videos.viewVideo(c.video.id).then(),!((j=c.video.script)!=null&&j.url))ee();
40else try{p.actions=await ei.videos.getScript(c.video.script.url)}catch(z){console.error("[Player] Failed to load script actions:",z)}document.addEventListener("keydown",fn),p.state.volume=p.el.volume,p.state.duration=c.video.duration,p.el.addEventListener("loadedmetadata",()=>{p.state.duration=p.el.duration,Ce>0?(Dt(Ce),Ce=0):p.state.lastCurrentTime>0&&Dt(p.state.lastCurrentTime)}),p.el.addEventListener("canplay",()=>{Ke()?Rs():!p.el.paused&&!p.el.ended&&(p.state.loading=!0,_t()),Le&&B.value&&(Le=!1,Wt(!1),h.value.play(Math.floor(p.state.currentTime*1e3)),f.value.play(Math.floor(p.state.currentTime*1e3)),y.value.play(Math.floor(p.state.currentTime*1e3))),p.state.playing&&(h.value.play(Math.floor(p.state.currentTime*1e3)),f.value.play(Math.floor(p.state.currentTime*1e3)),y.value.play(Math.floor(p.state.currentTime*1e3))),Ce=0}),p.el.addEventListener("waiting",()=>{p.state.loading=!p.el.paused&&!p.el.ended,!p.el.paused&&!p.el.ended&&_t(),Ds()}),p.el.addEventListener("playing",()=>{Rs(),p.state.loading=!1}),p.el.addEventListener("timeupdate",()=>{!(p&&p.el)||(p.state.currentTime=p.el.currentTime,Ke()&&Rs(),p.state.state===1&&!p.el.paused&&!p.el.ended&&!Ke()&&(p.state.loading=!0,_t()))}),p.el.addEventListener("volumechange",()=>{p.state.volume=p.el.volume}),p.el.addEventListener("pause",()=>{p.state.playing&&!rt(p.el)&&Ds(),p.state.playing=!1}),p.el.addEventListener("play",()=>{is(p.el.currentTime*1e3),f.value.iscsvsent&&rt(p.el)&&f.value.play(Math.floor(p.state.currentTime*1e3)),y.value.iscsvsent&&rt(p.el)&&y.value.play(Math.floor(p.state.currentTime*1e3)),E.value.connected&&(console.log("[Player] Video play - resetting Fleshy Thrust positions"),E.value.resetPosition()),h.value.play(Math.floor(p.state.currentTime*1e3)),p.state.playing=!0,p.state.loading=!1,Ce=0}),p.el.addEventListener("ended",()=>{is(0),p.state.playing=!1,c.repeatMode&&!c.playlist?(Dt(0),console.log("PLAYER: Video ended with repeatMode, calling restartDevicesAt(0)"),En(0),Wt(!1)):i.value?r(i.value):(console.log("PLAYER: Video ended, calling stopDevices()"),Ds(),p.el.pause(),p.el.currentTime=0)}),document.addEventListener("fullscreenchange",()=>{p.state.fullscreen=document.fullscreenElement!==null}),document.addEventListener("webkitfullscreenchange",()=>{p.state.fullscreen=document.fullscreenElement!==null}),p.el.addEventListener("webkitendfullscreen",()=>{p.el.setAttribute("playsinline",""),p.state.fullscreen=!1}),p.el.addEventListener("seeking",()=>{is(p.el.currentTime*1e3),E.value.connected&&(console.log("[Player] Video seeked - resetting Fleshy Thrust positions"),E.value.resetPosition())}),p.intervals.status=setInterval(wl,Gi),L.value=Fl(),(me=c.video.script)!=null&&me.url&&(await mn(),await pn(),await yn()),O(),X(),s=requestAnimationFrame(qt)}),$r(()=>{console.log("[Player] Unmounting"),p.hls.stopLoad(),document.removeEventListener("keydown",fn),Ds(),clearInterval(p.intervals.status),clearInterval(p.intervals.progress),Ot(),gt(),p.hls.destroy();const b=D();Object.assign(p,b);const C=document.querySelectorAll("video");console.log("[Player] Pausing videos on deactivation"),C.forEach(j=>{j.paused||j.pause()}),s&&cancelAnimationFrame(s)}),Zl(()=>{console.log("[Player] Activated"),p.hls.stopLoad(),Ds(),clearInterval(p.intervals.status),clearInterval(p.intervals.progress)});const fn=b=>{var C,j;if(!(((C=document.activeElement)==null?void 0:C.tagName.toLowerCase())==="input"||((j=document.activeElement)==null?void 0:j.tagName.toLowerCase())==="textarea"||document.activeElement.isContentEditable||!p.el)&&!(b.ctrlKey||b.shiftKey))switch(b.preventDefault(),b.key){case" ":p.state.playing&&(p.state.ui=!0),Wt(!1),Yi();break;case"ArrowRight":Dt(p.state.currentTime+10);break;case"ArrowLeft":Dt(p.state.currentTime-10);break;case"f":Ki();break}},wl=()=>{if(p.state.state===1&&!Ke()&&(De.value||Le)){p.state.loading=!0;return}const b=p.el.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA,C=p.el.readyState>=HTMLMediaElement.HAVE_FUTURE_DATA,me=!(!p.el.paused&&!p.el.ended&&p.el.currentTime>0&&b)&&!p.el.paused&&!p.el.ended&&!C;if(Ke()){Rs();return}me?p.timeouts.loadingDebounce===-1&&(p.timeouts.loadingDebounce=setTimeout(()=>{p.state.loading=!0},300)):(mt(),p.state.loading=!1)},Ki=()=>{const b=x.value;if(p.state.fullscreen)document.cancelFullScreen?document.cancelFullScreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{b.requestFullscreen?b.requestFullscreen():b.webkitRequestFullscreen?b.webkitRequestFullscreen():b.mozRequestFullScreen?b.mozRequestFullScreen():b.msRequestFullscreen?b.msRequestFullscreen():b.webkitEnterFullscreen&&b.webkitEnterFullscreen();const C=p.el;"webkitEnterFullscreen"in C&&(C.removeAttribute("playsinline"),C.webkitEnterFullscreen(),p.state.fullscreen=!0)}},rt=b=>b.currentTime>0&&!b.paused&&!b.ended&&b.readyState>=b.HAVE_FUTURE_DATA,Ol=ps(()=>ae()?!1:st.value?it.value:!p.state.loading||p.state.playing?!1:!p.el||!("paused"in p.el)?!0:Ke()||Le&&B.value&&p.el.readyState>=HTMLMediaElement.HAVE_FUTURE_DATA?!1:!rt(p.el)),Ml=ps(()=>ae()?!1:st.value?it.value:p.state.state!==1||p.state.playing?!1:!p.el||!("paused"in p.el)?!0:Ke()||Le&&B.value&&p.el.readyState>=HTMLMediaElement.HAVE_FUTURE_DATA?!1:!rt(p.el)),Wt=async(b=!0)=>
40{if(f.value.connected&&!f.value.iscsvsent){p.state.state=2,p.state.message="Failed to prepare video.";return}if(y.value.connected&&!y.value.iscsvsent){p.state.state=2,p.state.message="Failed to prepare video for VacuGlide.";return}p.sources.length!==0&&(rt(p.el)?(k(!1),b&&(p.state.ui=!0)):(k(!0),b&&(p.state.ui=!1)))},Dt=b=>{p.el.currentTime=b,p.state.currentTime=b,is(b*1e3)},_s=(b,C,j="external")=>{var Re;if(U(p.state.source,b)){C&&localStorage.setItem("quality",b.quality),Ke()?Rs():p.el.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&p.state.state!==2&&p.state.state!==3&&(mt(),p.state.state=0,p.state.loading=!1);return}const me=p.state.playing||!p.el.paused&&!p.el.ended&&p.el.currentTime>0,z=B.value&&(me||p.el.currentTime===0);j==="manual"&&(Te.value=!0),Ce===0&&(Ce=Math.max(((Re=p.el)==null?void 0:Re.currentTime)||0,p.state.currentTime||0,p.state.lastCurrentTime||0)),p.state.lastCurrentTime=Ce,p.state.source=b,p.state.state=1,p.state.loading=!0,Ot(),mt(),is(Ce*1e3),p.state.playing=!1,Le=z,p.el.pause(),p.hls.stopLoad(),p.hls.detachMedia();const Ye=V(b);b.format==="mp4"?(p.el.src=Ye,p.el.load(),(Le||p.state.loading)&&_t()):b.format==="hls"&&(ft.isSupported()?(p.hls.loadSource(Ye),p.hls.attachMedia(p.el),(Le||p.state.loading)&&_t(),p.hls.once(ft.Events.MANIFEST_PARSED,()=>{Ce>0&&(Dt(Ce),Ce=0),Le&&B.value&&(Le=!1,Wt(!1))}),p.hls.once(ft.Events.ERROR,(rs,ue)=>{ue.fatal&&(console.error("[Player] Fatal HLS error:",ue),p.state.message="Playback error. Try switching servers.",p.state.state=2,p.state.loading=!1)})):(p.el.src=Ye,p.el.load(),(Le||p.state.loading)&&_t())),C&&localStorage.setItem("quality",b.quality)},Hi=(b,C,j)=>{const me=b.map(Re=>parseInt(Re.quality));let z;if(j)z=C===null||isNaN(parseInt(C))?720:parseInt(C);else{const Re=parseInt(localStorage.getItem("quality")||"")||null,rs=C===null||isNaN(parseInt(C))?720:parseInt(C);z=Re!==null?Re:rs}let Ye=me.findIndex(Re=>Re<=z);return Ye===-1&&(Ye=me.findIndex(Re=>Re<=720)),Ye>-1?b[Ye]:b[0]};function Fl(){if("connection"in navigator){let b=navigator.connection||navigator.mozConnection||navigator.webkitConnection,C=b.downlink;return b.addEventListener("change",()=>{console.log(`[Player] Network changed: ${b.effectiveType}, speed: ${C}Mbps`);const j=gn(b.downlink);j!==null&&rt(p.el)&&_s(Hi(p.sources,j,!0),!0)}),gn(C)}else return console.log("[Player] Network Information API not supported"),null}function gn(b){return b<1?"144":b>=1&&b<2?"360":b>=2&&b<4?"480":b>=4&&b<8?"720":"1080"}const Yi=()=>{clearTimeout(p.timeouts.hidePlayer),p.timeouts.hidePlayer=setTimeout(()=>{p.state.playing&&(p.state.ui=!1)},2500)},Nl=b=>{p.el.volume=b,p.el.muted=!(b>0)};Zt(()=>p.state.volume,b=>Nl(b));const Bl=ps(()=>p.state.duration>0?p.state.duration:c.video.duration/1e3),mn=async()=>{var b;if(!!((b=c.video.script)!=null&&b.url))try{p.state.message="Preparing...",p.state.state=1;let C=!1;if(rt(p.el)&&(k(!1),C=!0),await h.value.prepare(qi(c.video.script.url)),p.state.state=0,p.state.message=void 0,C)try{k(!0)}catch(j){console.error("[Player] Handy: auto-play after prep failed:",j)}}catch(C){console.error("[Player] Handy: failed to prepare script:",C),p.state.state=2,p.state.message="Failed to prepare video"}},pn=async()=>{var b;if(!!((b=c.video.script)!=null&&b.url))try{p.state.message="Preparing...",p.state.state=1;let C=!1;if(rt(p.el)&&(k(!1),C=!0),await f.value.prepare(qi(c.video.script.url)),p.state.state=0,p.state.message=void 0,C)try{k(!0)}catch(j){console.error("[Player] Autoblow: auto-play after prep failed:",j)}}catch(C){console.error("[Player] Autoblow: failed to prepare script:",C),p.state.state=2,p.state.message="Failed to prepare video"}},yn=async()=>{var b;if(!!((b=c.video.script)!=null&&b.url))try{p.state.message="Preparing...",p.state.state=1;let C=!1;if(rt(p.el)&&(k(!1),C=!0),await y.value.prepare(qi(c.video.script.url)),p.state.state=0,p.state.message=void 0,C)try{k(!0)}catch(j){console.error("[Player] VacuGlide: auto-play after prep failed:",j)}}catch(C){console.error("[Player] VacuGlide: failed to prepare script:",C),p.state.state=2,p.state.message="Failed to prepare video for VacuGlide"}};Zt(()=>h.value.connected,async b=>{!b||await mn()}),Zt(()=>f.value.connected,async b=>{!b||await pn()}),Zt(()=>y.value.connected,async b=>{!b||await yn()});const Ds=()=>
40{clearInterval(ks),d.devices.forEach(b=>{switch(b.connector){case $e.Autoblow:d.autoblow.stop();break;case $e.VacuGlide:d.vacuglide.stop();break;case $e.Handy:d.handy.stop();break;case $e.Intiface:b.instance.stop();break;case $e.Bluetooth:b.instance.stop();break;case $e.BluetoothFleshyThrust:d.bluetoothFleshyThrust.resetPosition();break;case $e.FleshyX3:d.fleshyX3.stop();break}})},En=b=>{console.log("PLAYER: restartDevicesAt called with timeMs:",b),h.value.connected&&(console.log("PLAYER: Restarting Handy"),h.value.play(b)),f.value.iscsvsent&&(console.log("PLAYER: Restarting Autoblow"),f.value.play(b)),y.value.iscsvsent&&(console.log("PLAYER: Restarting VacuGlide"),y.value.play(b)),E.value.connected&&(console.log("PLAYER: Resetting Bluetooth Fleshy Thrust position"),E.value.resetPosition())},qt=()=>{var Mt,Os,Ms;if(!s)return;if(!B.value){requestAnimationFrame(qt);return}const b=p.el.currentTime*1e3;if(!p.el||!rt(p.el)){requestAnimationFrame(qt);return}Ps>0&&b<500&&Ps>5e3&&(console.log("PLAYER: Loop detected - lastProgressTime:",Ps,"current time:",b,"resetting cursor"),Ie=0,Cs=-1,En(b)),Ps=b;const C=p.actions;if(!C.length){requestAnimationFrame(qt);return}if(Ie=vn(C,b,Ie),Ie>=C.length){const we=$l(C);we>=0&&(ws.value=Qs(Math.round(C[we][1]))),requestAnimationFrame(qt);return}const j=C[Ie],me=Wi(C,Ie),z=me>=0?C[me]:void 0;if(z&&j[0]>z[0]){const we=z[1]+(j[1]-z[1])*(b-z[0])/(j[0]-z[0]);ws.value=Math.round(we)}else ws.value=Qs(Math.round(j[1]));const Ye=Ie,Re=[];for(;Ie<C.length&&((Mt=C[Ie])==null?void 0:Mt[0])<=b;){if(!ss(C[Ie])){Ie++;continue}Ie>Cs&&Re.push(Ie),Ie++}if(Ie<C.length&&Ie>Cs&&ss(C[Ie])&&Re.push(Ie),!Re.length){requestAnimationFrame(qt);return}const rs=Re.map(we=>{const ct=C[we],ns=ct[0],as=Qs(parseInt(ct[1].toFixed(0))),Zs=ns-b;return{Index:we,"Target Time (ms)":Number(ns.toFixed(0)),Position:as,"Offset (ms)":Number(Zs.toFixed(0)),Type:ns>b?"Upcoming (Ahead)":"Past (Catchup)"}});console.group(`[Player CatchUp] Player Time: ${Number(b.toFixed(0))}ms | Emitted: ${Re.length} | Cursor: ${Ye} -> ${Ie}`),console.table(rs),console.groupEnd();const ue=(Ms=(Os=nt().user)==null?void 0:Os.id)!=null?Ms:"";Re.forEach(we=>{const ct=C[we],ns=Wi(C,we),as=ns>=0?C[ns]:ct,Zs=Ul(C,we+1),Gl=Zs>=0?C[Zs][0]:ct[0],Vl=ct[0]>b,Kl=ct[0]-b,Hl=Gl-ct[0],jt=Math.max(1,Number((Vl?Kl:Hl).toFixed(0)));let Se=Qs(parseInt(ct[1].toFixed(0)));d.devices.forEach(Fe=>{switch(Fe.connector){case $e.OSR:ue!==""&&nt().isGymModeEnable&&yc.movementTotal(Se,ue),d.osr.move(Se,jt);break;case $e.LOOB:ue!==""&&nt().isGymModeEnable&&pc.movementTotal(Se,ue),d.loob.move(Se,jt);break;case $e.Handy:ue!==""&&nt().isGymModeEnable&&mc.movementTotal(Se,ue);break;case $e.Autoblow:ue!==""&&nt().isGymModeEnable&&gc.movementTotal(Se,ue);break;case $e.VacuGlide:ue!==""&&nt().isGymModeEnable&&fc.movementTotal(Se,ue);break;case $e.BluetoothFleshyThrust:E.value.connected&&(ue!==""&&nt().isGymModeEnable&&hc.movementTotal(Se,ue),E.value.move(Se,jt));break;case $e.FleshyX3:v.value.connected&&(ue!==""&&nt().isGymModeEnable&&dc.movementTotal(Se,ue),v.value.move(Se,jt));break;default:try{if(Fe.instance.linearAttributes.length>0){ue&&nt().isGymModeEnable&&(Fe.connector===$e.Intiface&&cc.movementTotal(Se,ue),Fe.connector===$e.Bluetooth&&uc.movementTotal(Se,ue));const ze=Fs(Fe.connector,Se,d.intiface,d.bluetooth),pt=ze/100;console.log(`[Player] Buttplug linear: pos=${Se}->${ze} (${pt}) in=${jt}ms`),Fe.instance.linear(pt,jt)}if(Fe.instance.vibrateAttributes.length>0){ks&&clearInterval(ks);const ze=125,pt=Math.max(1,Math.floor(jt/ze));let Ft=0;ks=setInterval(async()=>{Ft++;const Js=Ft/pt;if(Js>=1){clearInterval(ks);const xn=Fs(Fe.connector,100-Se,d.intiface,d.bluetooth),An=Number((xn/100).toFixed(1));console.log(`[Player] Buttplug vibrate final: pos=${100-Se}->${xn} (${An})`),Fe.instance.vibrate(Math.abs(An));return}let os=Se+(as[1]-Se)*Js;os=Math.max(0,Math.min(100,os));const Tn=100-os,Sn=Fs(Fe.connector,Tn,d.intiface,d.bluetooth);os=Number((Sn/100).toFixed(1)),console.log(`[Player] Buttplug vibrate step: pos=${Tn}->${Sn} (${os})`),Fe.instance.vibrate(Math.abs(os))},ze)}if(Fe.instance.rotateAttributes.length>0){const ze=Math.abs(Se-as[1]),pt=Fs(Fe.connector,ze,d.intiface,d.bluetooth),Ft=Number((pt/100).toFixed(2)),Js=as[1]>Se;console.log(`[Player] Buttplug rotate: posDelta=${ze}->${pt} value=${Ft}`),Fe.instance.rotate(Math.abs(Ft),Js)}if(Fe.instance.oscillateAttributes.length>0){const ze=Math.abs(Se-as[1]),pt=Fs(Fe.connector,ze,d.intiface,d.bluetooth),Ft=Number((pt/100).toFixed(2));console.log(`[Player] Buttplug oscillate: posDelta=${ze}->${pt} value=${Ft}`),Fe.instance.oscillate(Math.abs(Ft))}}catch(ze){console.error("[Player] Buttplug device error:",ze)}}}),Cs=we}),s=requestAnimationFrame(qt)};Zt(()=>n.isBunny,async()=>{var j;if(Me.value){Me.value=!1;return}Ce=Math.max(((j=p.el)==null?void 0:j.currentTime)||0,p.state.currentTime||0,p.state.lastCurrentTime||0),is(Ce*1e3),Rt(),mt(),gt(),Ot();const b=n.manualOverride;n.manualOverride=!1;const C=b?"manual":"external";b&&(pe.value=!0),await Vi({targetIsBunny:n.isBunny,origin:C,resumePlayback:p.state.playing})});const ss=b=>Array.isArray(b)&&Number.isFinite(b[0])&&Number.isFinite(b[1]),Qs=b=>Math.max(0,Math.min(100,b)),Wi=(b,C)=>{for(let j=C-1;j>=0;j--)if(ss(b[j]))return j;return-1},Ul=(b,C)=>{for(let j=C;j<b.length;j++)if(ss(b[j]))return j;return-1},$l=b=>{for(let C=b.length-1;C>=0;C--)if(ss(b[C]))return C;return-1},vn=(b,C,j=0)=>{let me=Math.max(0,Math.min(j,b.length));for(;me<b.length;){const z=b[me];if(!ss(z)){me++;continue}if(z[0]>=C)break;me++}return me},is=(b=0)=>{Ie=vn(p.actions,Math.max(0,b),0),Cs=Wi(p.actions,Ie)};let Cs=-1,Ie=0,Ps=0;console.log("PLAYER: lastProgressTime initialized to",Ps);let ks=-1;const ws=Ae(0);return(b,C)=>{var j,me;return ne(),de("div",Ug,[q("div",{class:"relative aspect-video overflow-hidden",ref_key:"container",ref:x},[l.value||u.value?(ne(),de("div",$g,qe(l.value||u.value),1)):Xe("",!0),Ln(q("div",{onClick:C[1]||(C[1]=()=>{p.state.state===3&&(oe(g).open=!0)}),class:dt(["h-full w-full flex items-center justify-center absolute z-10 bg-black/90 text-white flex-col",{"cursor-pointer":p.state.state===3}])},[Ml.value?(ne(),Nt(Pn,{key:0,class:"h-16 w-16 text-white",loading:!0})):p.state.state===2?(ne(),Nt(vt,{key:1,path:oe(Ec),class:"h-16 w-16"},null,8,["path"])):Xe("",!0),p.state.state===3?(ne(),de("div",Gg,[C[18]||(C[18]=q("p",{class:"text-2xl font-medium"}
40,"Interactive Content",-1)),C[19]||(C[19]=q("span",{class:"text-zinc-300 mt-6"},"Please Buy or Connect your Handy to continue watching this video",-1)),q("div",Vg,[Ge(ls,{theme:"green",class:"mx-auto"},{default:zt(()=>[...C[16]||(C[16]=[at("Buy Or Connect",-1)])]),_:1}),Ge(ls,{onClick:C[0]||(C[0]=ji(()=>{},["stop"])),href:a.video.stream_url,target:"_blank",theme:"light"},{default:zt(()=>[...C[17]||(C[17]=[at("Continue Video",-1)])]),_:1},8,["href"])])])):(ne(),de("span",{key:3,class:dt(["font-medium text-center text-xl absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 mt-12",{"text-base mt-16":!p.state.fullscreen}])},qe(p.state.message),3))],2),[[In,p.state.state!=0]]),!oe(d).devices.length&&!oe(A)&&!oe(nt)().isAuthorized&&I.value&&B.value?(ne(),de("div",Kg,[q("div",Hg,[q("div",Yg,[Ge(Qa,{position:ws.value,class:"w-full h-full"},null,8,["position"])]),c.isOverlay?Xe("",!0):(ne(),de("div",Wg,[oe(nt)().isProduction?(ne(),de("div",qg,[...C[20]||(C[20]=[q("p",{class:"font-medium text-white"},"This Video is Interactive",-1),q("p",{class:"text-sm text-zinc-300"},[at("Feel what you see with "),q("b",{class:"font-medium text-white"},"The Handy"),at(" - the interactive, automatic stroker that syncs up with every "),q("span",{class:"font-medium text-white"}
40,"FapTap"),at(" video")],-1)])])):Xe("",!0),q("p",jg,qe(oe(bn)),1),q("a",zg,[Ge(ls,{class:"w-full",theme:"green"},{default:zt(()=>[...C[21]||(C[21]=[at("Buy Now",-1)])]),_:1})]),Ge(ls,{class:"w-full",theme:"red",onClick:C[2]||(C[2]=ji(z=>{N(),I.value=!1},["stop"]))},{default:zt(()=>[...C[22]||(C[22]=[at("Close",-1)])]),_:1})]))])])):Xe("",!0),Ln(q("div",null,[q("div",{onMouseenter:C[12]||(C[12]=z=>(p.state.ui=!0,Yi())),onMousemove:C[13]||(C[13]=z=>(p.state.ui=!0,Yi())),class:dt([{"cursor-none":!p.state.ui},"flex flex-col h-full text-zinc-300 transition-colors absolute w-full top-0 left-0 z-30"])},[Ol.value?(ne(),de("div",Xg,[Ge(Pn,{loading:"",class:"h-16 w-16"})])):B.value?(ne(),de("div",{key:1,class:dt(["flex items-center gap-x-2 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2",{invisible:!p.state.ui&&!p.state.loading}])},[q("button",{onClick:C[3]||(C[3]=z=>Dt(p.state.currentTime-10)),class:"p-4"},[Ge(vt,{path:oe(Lc),name:"rewind-10",class:"h-6 w-6"},null,8,["path"])]),q("button",{onClick:C[4]||(C[4]=z=>Wt())},[p.state.playing?(ne(),Nt(vt,{key:0,path:oe(kn),class:"h-16 w-16"},null,8,["path"])):(ne(),Nt(vt,{key:1,path:oe(wn),class:"h-16 w-16"},null,8,["path"]))]),q("button",{onClick:C[5]||(C[5]=z=>Dt(p.state.currentTime+10)),class:"p-4"},[Ge(vt,{path:oe(Tc),class:"h-6 w-6"},null,8,["path"])])],2)):Xe("",!0),B.value?(ne(),de("div",{key:2,class:"flex-grow flex",onDblclick:Ki,onClick:C[6]||(C[6]=z=>Wt(!1))},null,32)):(ne(),de("a",{key:3,class:"flex-grow flex",href:Y.value,target:"_blank",rel:"noopener noreferrer nofollow ugc"},null,8,Qg)),q("div",{class:dt(["px-3 py-2 text-sm transition-transform bg-gradient-to-t from-black/80 to-transparent",p.state.ui?"":["translate-y-20"]])},[B.value?(ne(),Nt(Za,{key:0,class:"w-full",max:p.state.duration,value:p.state.currentTime,actions:p.actions,onSeek:C[7]||(C[7]=z=>Dt(z))},null,8,["max","value","actions"])):(ne(),Nt(Za,{key:1,disabled:"",class:"w-full flex-1 mx-4 ml-1 cursor-not-allowed",actions:[[]],max:p.state.duration,value:p.state.currentTime},null,8,["max","value"])),q("div",Zg,[q("div",Jg,[q("button",{onClick:C[8]||(C[8]=z=>Wt(!1)),class:"hover:text-white"},[Ge(vt,{path:p.state.playing?oe(kn):oe(wn),class:"h-7 w-7"},null,8,["path"])]),q("div",em,[q("span",tm,qe(oe(Tr)(p.state.currentTime)),1),C[23]||(C[23]=at(" / ",-1)),q("span",null,qe(oe(Tr)(Bl.value)),1)]),q("div",sm,[q("button",{class:dt(["hover:!text-white",{"opacity-50 disabled":!p.state.playing}]),onClick:C[9]||(C[9]=z=>{p.el.muted=!p.el.muted})},[Ge(vt,{path:p.el.muted?oe(bc):oe(Ic),class:"w-6 h-6"},null,8,["path"])],2),!oe(A)||oe(P)?(ne(),Nt(wg,{key:0,class:"h-1 w-20 mr-1.5",modelValue:p.state.volume,"onUpdate:modelValue":C[10]||(C[10]=z=>p.state.volume=z)},null,8,["modelValue"])):Xe("",!0)])]),B.value?(ne(),de("div",im,[p.state.source?(ne(),de("button",{key:0,ref:"qualityChooser",onClick:C[11]||(C[11]=z=>p.state.settings=!0),class:"hover:!text-white flex items-center"},[q("span",rm,qe((j=p.state.source)==null?void 0:j.quality)+"p ("+qe((me=p.state.source)==null?void 0:me.format)+") ",1),Ge(vt,{path:oe(Ac),class:"w-6 h-6"},null,8,["path"])],512)):Xe("",!0),q("button",{class:"hover:!text-white",onClick:Ki},[Ge(vt,{path:p.state.fullscreen?oe(xc):oe(Sc),class:"h-6 w-6"},null,8,["path"])])])):Xe("",!0)])],2),$.value>=0&&!B.value?(ne(),de("div",{key:4,class:dt(["bg-zinc-800 hover:bg-blue-600 active:bg-blue-500 rounded-none overflow-hidden disabled:opacity-75 cursor-pointer disabled:cursor-not-allowed flex items-center absolute bottom-16 right-0 z-20 text-white gap-1 px-4 md:px-8 py-1 md:py-2 text-sm md:text-lg whitespace-nowrap",{"opacity-75":$.value>0}]),onClick:O},[q("span",null,[C[24]||(C[24]=at("Skip ad ",-1)),$.value>0?(ne(),de("i",nm," in "+qe($.value)+" sec ",1)):Xe("",!0)]),Ge(vt,{path:oe(vc),class:"h-6 w-6"},null,8,["path"])],2)):Xe("",!0)],34)],512),[[In,p.state.state===0]]),(ne(),Nt(Jl(oe(A)?ec:tc),{modelValue:p.state.settings,"onUpdate:modelValue":C[14]||(C[14]=z=>p.state.settings=z),target:b.$refs.qualityChooser,teleport:!1,placement:"top-end",offset:8,class:"w-40"},{default:zt(()=>[oe(A)?(ne(),de("div",am,[(ne(!0),de(Rn,null,_n(p.sources,z=>(ne(),de("div",{class:dt(["p-3 hover:bg-blue-500 rounded cursor-pointer text-center",p.state.source&&p.state.source.quality===z.quality&&p.state.source.format===z.format?"bg-blue-500":"bg-gray-700"]),onClick:Ye=>(_s(z,!0,"manual"),p.state.settings=!1)},[at(qe(z.quality)+" ",1),C[25]||(C[25]=q("br",null,null,-1)),q("span",lm,"("+qe(z.format)+")",1)],10,om))),256))])):(ne(),de("div",cm,[(ne(!0),de(Rn,null,_n(p.sources,z=>(ne(),de("div",{class:dt(["flex py-1.5 md:py-1.5 px-3 items-center gap-3 hover:bg-blue-500 cursor-pointer text-lg md:text-base text-center",p.state.source&&p.state.source.quality===z.quality&&p.state.source.format===z.format?"bg-blue-500":"bg-gray-700"]),onClick:Ye=>(_s(z,!0,"manual"),p.state.settings=!1)},[q("div",dm,qe(z.quality)+"p",1),q("div",hm,"("+qe(z.format)+")",1)],10,um))),256))]))]),_:1},8,["modelValue","target"])),q("video",{id:"player",loop:c.loop,playsinline:"",class:"absolute w-full h-full bg-black"},null,8,fm)],512),q("div",gm,[!oe(d).devices.length&&oe(A)&&!oe(nt)().isAuthorized&&I.value?(ne(),de("div",mm,[q("div",pm,[q("div",ym,[Ge(Qa,{position:ws.value,class:"w-full h-full object-contain"},null,8,["position"])]),c.isOverlay?Xe("",!0):(ne(),de("div",Em,[C[28]||(C[28]=sc('<div class="text-start"><p class="font-medium text-white">This Video is Interactive</p><p class="text-sm text-zinc-300">Feel what you see with <b class="font-medium text-white">The Handy</b> - the interactive, automatic stroker that syncs up with every <span class="font-medium text-white">FapTap</span> video</p></div>',1)),q("p",vm,qe(oe(bn)),1),q("a",Tm,[Ge(ls,{class:"w-full text-sm",theme:"green"},{default:zt(()=>[...C[26]||(C[26]=[at("Buy Now",-1)])]),_:1})]),Ge(ls,{class:"w-full text-sm",theme:"red",onClick:C[15]||(C[15]=ji(z=>{N(),I.value=!1},["stop"]))},{default:zt(()=>[...C[27]||(C[27]=[at("Close",-1)])]),_:1})]))])])):Xe("",!0)])])}}});
40export{_m as _};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.