import './async-Djx13DAD.js';
import { c as bind_props, d as attr_class, a as attr, g as attr_style, j as stringify } from './index-B7gr0Dsc.js';
import './2-CeYbpaU1.js';
import { w as w$2, y as y$2 } from './utils.svelte-D8Xdzglu.js';
import './MarkdownCode.svelte_svelte_type_style_lang-DJRtJayx.js';
import { k as k$1 } from './BlockLabel-DYKzuObf.js';
import { u } from './DownloadLink-BLkRTIUs.js';
import { w as w$1 } from './IconButton-7VBZdgpA.js';
import { p } from './Empty-uaeWNu3s.js';
import { y as y$1 } from './ShareButton-B1Vd_e6T.js';
import { l } from './Download-rAXPPveZ.js';
import { t } from './Music-CFRjVwjy.js';
import { y } from './IconButtonWrapper-DlgTGGi-.js';
import { Z } from './MinimalAudioPlayer-YeOh_PMv.js';
import { p as p$1, u as u$1, c } from './VolumeLevels-ChNcuVO2.js';
import { n } from './Play-BVmRHWoH.js';
import { r } from './Undo-DlTKhhuO.js';
import { e as escape_html } from './escaping-CBnpiEl5.js';
import './context-BZS6UlnY.js';
import './uneval-DjLoL4oF.js';
import './clone-BLo8hHdj.js';
import './index5-BoOEKc6P.js';
import './dev-fallback-Bc5Ork7Y.js';
import './prism-python-BaDPvmdn.js';
import './index-server-lqjMX237.js';

function Dn(r){r.push('<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="currentColor" stroke-width="1.5" viewBox="0 0 24 24" color="currentColor"><path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" d="M21.044 5.704a.6.6 0 0 1 .956.483v11.626a.6.6 0 0 1-.956.483l-7.889-5.813a.6.6 0 0 1 0-.966l7.89-5.813ZM10.044 5.704a.6.6 0 0 1 .956.483v11.626a.6.6 0 0 1-.956.483l-7.888-5.813a.6.6 0 0 1 0-.966l7.888-5.813Z"></path></svg>');}function Cn(r){r.push('<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="feather feather-closed-caption"><rect x="2" y="6" width="20" height="12" rx="2" ry="2"></rect><text x="12" y="15" font-family="sans-serif" font-size="8" font-weight="bold" fill="currentColor" stroke="none" text-anchor="middle">CC</text></svg>');}function _n(r){r.push('<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="currentColor" stroke-width="1.5" viewBox="0 0 24 24" color="currentColor"><path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" d="M2.956 5.704A.6.6 0 0 0 2 6.187v11.626a.6.6 0 0 0 .956.483l7.889-5.813a.6.6 0 0 0 0-.966l-7.89-5.813ZM13.956 5.704a.6.6 0 0 0-.956.483v11.626a.6.6 0 0 0 .956.483l7.889-5.813a.6.6 0 0 0 0-.966l-7.89-5.813Z"></path></svg>');}const ps=(r,t)=>(t||(t=5),r/100*t||5);function On(r,t){r.component(e=>{let{currentVolume:s$1=void 0,show_volume_slider:i=void 0,waveform:n}=t;e.push(`<input id="volume" class="volume-slider svelte-c0ird4" type="range" min="0" max="1" step="0.01"${attr("value",s$1)}/>`),bind_props(t,{currentVolume:s$1,show_volume_slider:i});});}function Mn(r$1,t){r$1.component(e=>{let {waveform:s$1,audio_duration:i,i18n:n$1,playing:o,show_redo:a=false,interactive:l=false,handle_trim_audio:c$1,mode:h=void 0,container:u,handle_reset_value:d,waveform_options:f={},trim_region_settings:g={},show_volume_slider:m=void 0,editable:p=true,subtitles_toggle:y=void 0,show_subtitles:A=false,trimDuration:T=void 0}=t,R=[.5,1,1.5,2],E=R[1],v=1;let P=true,L;function _(D){D.push(`<div class="controls svelte-72dh9g" data-testid="waveform-controls"><div class="control-wrapper svelte-72dh9g"><button class="action icon volume svelte-72dh9g" aria-label="Adjust volume"${attr_style("",{color:m?"var(--color-accent)":"var(--neutral-400)"})}>`),p$1(D,{currentVolume:v}),D.push("<!----></button> "),m?(D.push("<!--[-->"),On(D,{waveform:s$1,get currentVolume(){return v},set currentVolume(q){v=q,P=false;},get show_volume_slider(){return m},set show_volume_slider(q){m=q,P=false;}})):D.push("<!--[!-->"),D.push(`<!--]--> <button${attr_class("playback icon svelte-72dh9g",void 0,{hidden:m})}${attr("aria-label",`Adjust playback speed to ${R[(R.indexOf(E)+1)%R.length]}x`)}><span>${escape_html(E)}x</span></button></div> <div class="play-pause-wrapper svelte-72dh9g"><button class="rewind icon svelte-72dh9g"${attr("aria-label",`Skip backwards by ${ps(i,f.skip_length)} seconds`)}>`),Dn(D),D.push(`<!----></button> <button class="play-pause-button icon svelte-72dh9g"${attr("aria-label",n$1(o?"audio.pause":"audio.play"))}>`),o?(D.push("<!--[-->"),u$1(D)):(D.push("<!--[!-->"),n(D)),D.push(`<!--]--></button> <button class="skip icon svelte-72dh9g"${attr("aria-label",`Skip forward by ${stringify(ps(i,f.skip_length))} seconds`)}>`),_n(D),D.push('<!----></button></div> <div class="settings-wrapper svelte-72dh9g">'),A?(D.push("<!--[-->"),D.push(`<button class="action icon cc-button svelte-72dh9g" data-testid="subtitles-toggle"${attr_style(`color: ${stringify(y?"var(--color-accent)":"var(--neutral-400)")}`)}>`),Cn(D),D.push("<!----></button>")):D.push("<!--[!-->"),D.push("<!--]--> "),p&&l?(D.push("<!--[-->"),a&&!h?(D.push("<!--[-->"),D.push('<button class="action icon svelte-72dh9g" aria-label="Reset audio">'),r(D),D.push("<!----></button>")):D.push("<!--[!-->"),D.push("<!--]--> "),h?(D.push("<!--[!-->"),D.push('<button class="text-button svelte-72dh9g">Trim</button> <button class="text-button svelte-72dh9g">Cancel</button>')):(D.push("<!--[-->"),D.push('<button class="action icon svelte-72dh9g" aria-label="Trim audio to selection">'),c(D),D.push("<!----></button>")),D.push("<!--]-->")):D.push("<!--[!-->"),D.push("<!--]--></div></div>");}do P=true,L=e.copy(),_(L);while(!P);e.subsume(L),bind_props(t,{mode:h,show_volume_slider:m,subtitles_toggle:y,trimDuration:T});});}function Nn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Un={exports:{}};(function(r,t){(function(e){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var u=a.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=a.normalizePath(u.path),a.buildURLFromParts(u)}var d=a.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=a.normalizePath(d.path),a.buildURLFromParts(d)):c;var f=a.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2];}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(m.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)m.path=f.path,d.params||(m.params=f.params,d.query||(m.query=f.query));else {var p=f.path,y=p.substring(0,p.lastIndexOf("/")+1)+d.path;m.path=a.normalizePath(y);}return m.path===null&&(m.path=h.alwaysNormalize?a.normalizePath(d.path):d.path),a.buildURLFromParts(m)},parseURL:function(l){var c=s.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(o,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};r.exports=a;})();})(Un);function ys(r,t){var e=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),e.push.apply(e,s);}return e}function ut(r){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?ys(Object(e),true).forEach(function(s){Gn(r,s,e[s]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(e)):ys(Object(e)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(e,s));});}return r}function Bn(r,t){if(typeof r!="object"||!r)return r;var e=r[Symbol.toPrimitive];if(e!==void 0){var s=e.call(r,t);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return (t==="string"?String:Number)(r)}function $n(r){var t=Bn(r,"string");return typeof t=="symbol"?t:String(t)}function Gn(r,t,e){return t=$n(t),t in r?Object.defineProperty(r,t,{value:e,enumerable:true,configurable:true,writable:true}):r[t]=e,r}function ct(){return ct=Object.assign?Object.assign.bind():function(r){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[s]=e[s]);}return r},ct.apply(this,arguments)}const $=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Kn=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=Vn},Vn=Number.MAX_SAFE_INTEGER||9007199254740991;let x=(function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r})({}),H=(function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r})({}),w=(function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.UNKNOWN="unknown",r})({});const Ot=function(){},Hn={trace:Ot,debug:Ot,log:Ot,warn:Ot,info:Ot,error:Ot};let Wn=Hn;const b=Wn,Yn=/^(\d+)x(\d+)$/,Ts=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Qt{constructor(t){typeof t=="string"&&(t=Qt.parseAttrList(t)),ct(this,t);}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(e.length&1?"0":"")+e;const s=new Uint8Array(e.length/2);for(let i=0;i<e.length/2;i++)s[i]=parseInt(e.slice(i*2,i*2+2),16);return s}else return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}bool(t){return this[t]==="YES"}decimalResolution(t){const e=Yn.exec(this[t]);if(e!==null)return {width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const s={};for(Ts.lastIndex=0;(e=Ts.exec(t))!==null;){let n=e[2];n.indexOf('"')===0&&n.lastIndexOf('"')===n.length-1&&(n=n.slice(1,-1));const o=e[1].trim();s[o]=n;}return s}}class zn{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const s=e.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==s[i]){b.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=ct(new Qt({}),s,t);}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const s=new Date(this.attr["END-DATE"]);$(s.getTime())&&(this._endDate=s);}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return t!==null?new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if($(t))return t}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 isValid(){return !!this.id&&!this._badValueForSameId&&$(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class qn{constructor(){this.aborted=false,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 lt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};function is(r){return Uint8Array.from(atob(r),t=>t.charCodeAt(0))}function jn(r){const t=He(r).subarray(0,16),e=new Uint8Array(16);return e.set(t,16-t.length),e}function Xn(r){const t=function(s,i,n){const o=s[i];s[i]=s[n],s[n]=o;};t(r,0,3),t(r,1,2),t(r,4,5),t(r,6,7);}function Qn(r){const t=r.split(":");let e=null;if(t[0]==="data"&&t.length===2){const s=t[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const n=i[0]==="base64",o=i[1];n?(s.splice(-1,1),e=is(o)):e=jn(o);}}return e}function He(r){return Uint8Array.from(unescape(encodeURIComponent(r)),t=>t.charCodeAt(0))}const Kt=typeof self<"u"?self:void 0;var J={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ht={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ss(r){switch(r){case ht.FAIRPLAY:return J.FAIRPLAY;case ht.PLAYREADY:return J.PLAYREADY;case ht.WIDEVINE:return J.WIDEVINE;case ht.CLEARKEY:return J.CLEARKEY}}var ui={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Zn(r){if(r===ui.WIDEVINE)return J.WIDEVINE}function Es(r){switch(r){case J.FAIRPLAY:return ht.FAIRPLAY;case J.PLAYREADY:return ht.PLAYREADY;case J.WIDEVINE:return ht.WIDEVINE;case J.CLEARKEY:return ht.CLEARKEY}}function Ie(r){const{drmSystems:t,widevineLicenseUrl:e}=r,s=t?[J.FAIRPLAY,J.WIDEVINE,J.PLAYREADY,J.CLEARKEY].filter(i=>!!t[i]):[];return !s[J.WIDEVINE]&&e&&s.push(J.WIDEVINE),s}const di=(function(r){return Kt!=null&&(r=Kt.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Jn(r,t,e,s){let i;switch(r){case J.FAIRPLAY:i=["cenc","sinf"];break;case J.WIDEVINE:case J.PLAYREADY:i=["cenc"];break;case J.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return tr(i,t,e,s)}function tr(r,t,e,s){return [{initDataTypes:r,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map(n=>({contentType:`audio/mp4; codecs="${n}"`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:e.map(n=>({contentType:`video/mp4; codecs="${n}"`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Ft(r,t,e){return Uint8Array.prototype.slice?r.slice(t,e):new Uint8Array(Array.prototype.slice.call(r,t,e))}const ns=(r,t)=>t+10<=r.length&&r[t]===73&&r[t+1]===68&&r[t+2]===51&&r[t+3]<255&&r[t+4]<255&&r[t+6]<128&&r[t+7]<128&&r[t+8]<128&&r[t+9]<128,fi=(r,t)=>t+10<=r.length&&r[t]===51&&r[t+1]===68&&r[t+2]===73&&r[t+3]<255&&r[t+4]<255&&r[t+6]<128&&r[t+7]<128&&r[t+8]<128&&r[t+9]<128,jt=(r,t)=>{const e=t;let s=0;for(;ns(r,t);){s+=10;const i=Le(r,t+6);s+=i,fi(r,t+10)&&(s+=10),t+=s;}if(s>0)return r.subarray(e,e+s)},Le=(r,t)=>{let e=0;return e=(r[t]&127)<<21,e|=(r[t+1]&127)<<14,e|=(r[t+2]&127)<<7,e|=r[t+3]&127,e},er=(r,t)=>ns(r,t)&&Le(r,t+6)+10<=r.length-t,rs=r=>{const t=nr(r);for(let e=0;e<t.length;e++){const s=t[e];if(sr(s))return cr(s)}},sr=r=>r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp",ir=r=>{const t=String.fromCharCode(r[0],r[1],r[2],r[3]),e=Le(r,4),s=10;return {type:t,size:e,data:r.subarray(s,s+e)}},nr=r=>{let t=0;const e=[];for(;ns(r,t);){const s=Le(r,t+6);t+=10;const i=t+s;for(;t+8<i;){const n=ir(r.subarray(t)),o=rr(n);o&&e.push(o),t+=n.size+10;}fi(r,t)&&(t+=10);}return e},rr=r=>r.type==="PRIV"?or(r):r.type[0]==="W"?lr(r):ar(r),or=r=>{if(r.size<2)return;const t=At(r.data,true),e=new Uint8Array(r.data.subarray(t.length+1));return {key:r.type,info:t,data:e.buffer}},ar=r=>{if(r.size<2)return;if(r.type==="TXXX"){let e=1;const s=At(r.data.subarray(e),true);e+=s.length+1;const i=At(r.data.subarray(e));return {key:r.type,info:s,data:i}}const t=At(r.data.subarray(1));return {key:r.type,data:t}},lr=r=>{if(r.type==="WXXX"){if(r.size<2)return;let e=1;const s=At(r.data.subarray(e),true);e+=s.length+1;const i=At(r.data.subarray(e));return {key:r.type,info:s,data:i}}const t=At(r.data);return {key:r.type,data:t}},cr=r=>{if(r.data.byteLength===8){const t=new Uint8Array(r.data),e=t[3]&1;let s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,e&&(s+=4772185884e-2),Math.round(s)}},At=(r,t=false)=>{const e=hr();if(e){const c=e.decode(r);if(t){const h=c.indexOf("\0");return h!==-1?c.substring(0,h):c}return c.replace(/\0/g,"")}const s=r.length;let i,n,o,a="",l=0;for(;l<s;){if(i=r[l++],i===0&&t)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:n=r[l++],a+=String.fromCharCode((i&31)<<6|n&63);break;case 14:n=r[l++],o=r[l++],a+=String.fromCharCode((i&15)<<12|(n&63)<<6|(o&63)<<0);break}}return a};let we;function hr(){if(!navigator.userAgent.includes("PlayStation 4"))return !we&&typeof self.TextDecoder<"u"&&(we=new self.TextDecoder("utf-8")),we}const St={hexDump:function(r){let t="";for(let e=0;e<r.length;e++){let s=r[e].toString(16);s.length<2&&(s="0"+s),t+=s;}return t}},pe=Math.pow(2,32)-1,ur=[].push,gi={video:1,audio:2,id3:3,text:4};function st(r){return String.fromCharCode.apply(null,r)}function mi(r,t){const e=r[t]<<8|r[t+1];return e<0?65536+e:e}function M(r,t){const e=pi(r,t);return e<0?4294967296+e:e}function vs(r,t){let e=M(r,t);return e*=Math.pow(2,32),e+=M(r,t+4),e}function pi(r,t){return r[t]<<24|r[t+1]<<16|r[t+2]<<8|r[t+3]}function De(r,t,e){r[t]=e>>24,r[t+1]=e>>16&255,r[t+2]=e>>8&255,r[t+3]=e&255;}function dr(r){const t=r.byteLength;for(let e=0;e<t;){const s=M(r,e);if(s>8&&r[e+4]===109&&r[e+5]===111&&r[e+6]===111&&r[e+7]===102)return  true;e=s>1?e+s:t;}return  false}function K(r,t){const e=[];if(!t.length)return e;const s=r.byteLength;for(let i=0;i<s;){const n=M(r,i),o=st(r.subarray(i+4,i+8)),a=n>1?i+n:s;if(o===t[0])if(t.length===1)e.push(r.subarray(i+8,a));else {const l=K(r.subarray(i+8,a),t.slice(1));l.length&&ur.apply(e,l);}i=a;}return e}function fr(r){const t=[],e=r[0];let s=8;const i=M(r,s);s+=4;let n=0,o=0;e===0?(n=M(r,s),o=M(r,s+4),s+=8):(n=vs(r,s),o=vs(r,s+8),s+=16),s+=2;let a=r.length+o;const l=mi(r,s);s+=2;for(let c=0;c<l;c++){let h=s;const u=M(r,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return b.warn("SIDX has hierarchical references (not supported)"),null;const g=M(r,h);h+=4,t.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:a,end:a+d-1}}),a+=d,h+=4,s=h;}return {earliestPresentationTime:n,timescale:i,version:e,referencesCount:l,references:t}}function xi(r){const t=[],e=K(r,["moov","trak"]);for(let i=0;i<e.length;i++){const n=e[i],o=K(n,["tkhd"])[0];if(o){let a=o[0];const l=M(o,a===0?12:20),c=K(n,["mdia","mdhd"])[0];if(c){a=c[0];const h=M(c,a===0?12:20),u=K(n,["mdia","hdlr"])[0];if(u){const d=st(u.subarray(8,12)),f={soun:lt.AUDIO,vide:lt.VIDEO}[d];if(f){const g=K(n,["mdia","minf","stbl","stsd"])[0],m=gr(g);t[l]={timescale:h,type:f},t[f]=ut({timescale:h,id:l},m);}}}}}return K(r,["moov","mvex","trex"]).forEach(i=>{const n=M(i,4),o=t[n];o&&(o.default={duration:M(i,12),flags:M(i,20)});}),t}function gr(r){const t=r.subarray(8),e=t.subarray(86),s=st(t.subarray(4,8));let i=s;const n=s==="enca"||s==="encv";if(n){const a=K(t,[s])[0].subarray(s==="enca"?28:78);K(a,["sinf"]).forEach(c=>{const h=K(c,["schm"])[0];if(h){const u=st(h.subarray(4,8));if(u==="cbcs"||u==="cenc"){const d=K(c,["frma"])[0];d&&(i=st(d));}}});}switch(i){case "avc1":case "avc2":case "avc3":case "avc4":{const o=K(e,["avcC"])[0];i+="."+Jt(o[1])+Jt(o[2])+Jt(o[3]);break}case "mp4a":{const o=K(t,[s])[0],a=K(o.subarray(28),["esds"])[0];if(a&&a.length>12){let l=4;if(a[l++]!==3)break;l=Ce(a,l),l+=2;const c=a[l++];if(c&128&&(l+=2),c&64&&(l+=a[l++]),a[l++]!==4)break;l=Ce(a,l);const h=a[l++];if(h===64)i+="."+Jt(h);else break;if(l+=12,a[l++]!==5)break;l=Ce(a,l);const u=a[l++];let d=(u&248)>>3;d===31&&(d+=1+((u&7)<<3)+((a[l]&224)>>5)),i+="."+d;}break}case "hvc1":case "hev1":{const o=K(e,["hvcC"])[0],a=o[1],l=["","A","B","C"][a>>6],c=a&31,h=M(o,2),u=(a&32)>>5?"H":"L",d=o[12],f=o.subarray(6,12);i+="."+l+c,i+="."+h.toString(16).toUpperCase(),i+="."+u+d;let g="";for(let m=f.length;m--;){const p=f[m];(p||g)&&(g="."+p.toString(16).toUpperCase()+g);}i+=g;break}case "dvh1":case "dvhe":{const o=K(e,["dvcC"])[0],a=o[2]>>1&127,l=o[2]<<5&32|o[3]>>3&31;i+="."+Tt(a)+"."+Tt(l);break}case "vp09":{const o=K(e,["vpcC"])[0],a=o[4],l=o[5],c=o[6]>>4&15;i+="."+Tt(a)+"."+Tt(l)+"."+Tt(c);break}case "av01":{const o=K(e,["av1C"])[0],a=o[1]>>>5,l=o[1]&31,c=o[2]>>>7?"H":"M",h=(o[2]&64)>>6,u=(o[2]&32)>>5,d=a===2&&h?u?12:10:h?10:8,f=(o[2]&16)>>4,g=(o[2]&8)>>3,m=(o[2]&4)>>2,p=o[2]&3;i+="."+a+"."+Tt(l)+c+"."+Tt(d)+"."+f+"."+g+m+p+"."+Tt(1)+"."+Tt(1)+"."+Tt(1)+"."+0;break}}return {codec:i,encrypted:n}}function Ce(r,t){const e=t+5;for(;r[t++]&128&&t<e;);return t}function Jt(r){return ("0"+r.toString(16).toUpperCase()).slice(-2)}function Tt(r){return (r<10?"0":"")+r}function mr(r,t){if(!r||!t)return r;const e=t.keyId;return e&&t.isCommonEncryption&&K(r,["moov","trak"]).forEach(i=>{const o=K(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let a=K(o,["enca"]);const l=a.length>0;l||(a=K(o,["encv"])),a.forEach(c=>{const h=l?c.subarray(28):c.subarray(78);K(h,["sinf"]).forEach(d=>{const f=yi(d);if(f){const g=f.subarray(8,24);g.some(m=>m!==0)||(b.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${St.hexDump(g)} -> ${St.hexDump(e)}`),f.set(e,8));}});});}),r}function yi(r){const t=K(r,["schm"])[0];if(t){const e=st(t.subarray(4,8));if(e==="cbcs"||e==="cenc")return K(r,["schi","tenc"])[0]}return b.error("[eme] missing 'schm' box"),null}function pr(r,t){return K(t,["moof","traf"]).reduce((e,s)=>{const i=K(s,["tfdt"])[0],n=i[0],o=K(s,["tfhd"]).reduce((a,l)=>{const c=M(l,4),h=r[c];if(h){let u=M(i,4);if(n===1){if(u===pe)return b.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),a;u*=pe+1,u+=M(i,8);}const d=h.timescale||9e4,f=u/d;if($(f)&&(a===null||f<a))return f}return a},null);return o!==null&&$(o)&&(e===null||o<e)?o:e},null)}function xr(r,t){let e=0,s=0,i=0;const n=K(r,["moof","traf"]);for(let o=0;o<n.length;o++){const a=n[o],l=K(a,["tfhd"])[0],c=M(l,4),h=t[c];if(!h)continue;const u=h.default,d=M(l,0)|u?.flags;let f=u?.duration;d&8&&(d&2?f=M(l,12):f=M(l,8));const g=h.timescale||9e4,m=K(a,["trun"]);for(let p=0;p<m.length;p++){if(e=yr(m[p]),!e&&f){const y=M(m[p],4);e=f*y;}h.type===lt.VIDEO?s+=e/g:h.type===lt.AUDIO&&(i+=e/g);}}if(s===0&&i===0){let o=1/0,a=0,l=0;const c=K(r,["sidx"]);for(let h=0;h<c.length;h++){const u=fr(c[h]);if(u!=null&&u.references){o=Math.min(o,u.earliestPresentationTime/u.timescale);const d=u.references.reduce((f,g)=>f+g.info.duration||0,0);a=Math.max(a,d+u.earliestPresentationTime/u.timescale),l=a-o;}}if(l&&$(l))return l}return s||i}function yr(r){const t=M(r,0);let e=8;t&1&&(e+=4),t&4&&(e+=4);let s=0;const i=M(r,4);for(let n=0;n<i;n++){if(t&256){const o=M(r,e);s+=o,e+=4;}t&512&&(e+=4),t&1024&&(e+=4),t&2048&&(e+=4);}return s}function Tr(r,t,e){K(t,["moof","traf"]).forEach(s=>{K(s,["tfhd"]).forEach(i=>{const n=M(i,4),o=r[n];if(!o)return;const a=o.timescale||9e4;K(s,["tfdt"]).forEach(l=>{const c=l[0],h=e*a;if(h){let u=M(l,4);if(c===0)u-=h,u=Math.max(u,0),De(l,4,u);else {u*=Math.pow(2,32),u+=M(l,8),u-=h,u=Math.max(u,0);const d=Math.floor(u/(pe+1)),f=Math.floor(u%(pe+1));De(l,4,d),De(l,8,f);}}});});});}function Sr(r){const t={valid:null,remainder:null},e=K(r,["moof"]);if(e.length<2)return t.remainder=r,t;const s=e[e.length-1];return t.valid=Ft(r,0,s.byteOffset-8),t.remainder=Ft(r,s.byteOffset-8),t}function gt(r,t){const e=new Uint8Array(r.length+t.length);return e.set(r),e.set(t,r.length),e}function As(r,t){const e=[],s=t.samples,i=t.timescale,n=t.id;let o=false;return K(s,["moof"]).map(l=>{const c=l.byteOffset-8;K(l,["traf"]).map(u=>{const d=K(u,["tfdt"]).map(f=>{const g=f[0];let m=M(f,4);return g===1&&(m*=Math.pow(2,32),m+=M(f,8)),m/i})[0];return d!==void 0&&(r=d),K(u,["tfhd"]).map(f=>{const g=M(f,4),m=M(f,0)&16777215,p=(m&1)!==0,y=(m&2)!==0,A=(m&8)!==0;let T=0;const R=(m&16)!==0;let E=0;const I=(m&32)!==0;let v=8;g===n&&(p&&(v+=8),y&&(v+=4),A&&(T=M(f,v),v+=4),R&&(E=M(f,v),v+=4),I&&(v+=4),t.type==="video"&&(o=Er(t.codec)),K(u,["trun"]).map(C=>{const P=C[0],L=M(C,0)&16777215,_=(L&1)!==0;let D=0;const q=(L&4)!==0,X=(L&256)!==0;let V=0;const B=(L&512)!==0;let j=0;const Q=(L&1024)!==0,O=(L&2048)!==0;let F=0;const Y=M(C,4);let G=8;_&&(D=M(C,G),G+=4),q&&(G+=4);let z=D+c;for(let tt=0;tt<Y;tt++){if(X?(V=M(C,G),G+=4):V=T,B?(j=M(C,G),G+=4):j=E,Q&&(G+=4),O&&(P===0?F=M(C,G):F=pi(C,G),G+=4),t.type===lt.VIDEO){let U=0;for(;U<j;){const N=M(s,z);if(z+=4,vr(o,s[z])){const Z=s.subarray(z,z+N);Ti(Z,o?2:1,r+F/i,e);}z+=N,U+=N+4;}}r+=V/i;}}));})});}),e}function Er(r){if(!r)return  false;const t=r.indexOf("."),e=t<0?r:r.substring(0,t);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function vr(r,t){if(r){const e=t>>1&63;return e===39||e===40}else return (t&31)===6}function Ti(r,t,e,s){const i=Si(r);let n=0;n+=t;let o=0,a=0,l=0;for(;n<i.length;){o=0;do{if(n>=i.length)break;l=i[n++],o+=l;}while(l===255);a=0;do{if(n>=i.length)break;l=i[n++],a+=l;}while(l===255);const c=i.length-n;let h=n;if(a<c)n+=a;else if(a>c){b.error(`Malformed SEI payload. ${a} is too small, only ${c} bytes left to parse.`);break}if(o===4){if(i[h++]===181){const d=mi(i,h);if(h+=2,d===49){const f=M(i,h);if(h+=4,f===1195456820){const g=i[h++];if(g===3){const m=i[h++],p=31&m,y=64&m,A=y?2+p*3:0,T=new Uint8Array(A);if(y){T[0]=m;for(let R=1;R<A;R++)T[R]=i[h++];}s.push({type:g,payloadType:o,pts:e,bytes:T});}}}}}else if(o===5&&a>16){const u=[];for(let g=0;g<16;g++){const m=i[h++].toString(16);u.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&u.push("-");}const d=a-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[h++];s.push({payloadType:o,pts:e,uuid:u.join(""),userData:At(f),userDataBytes:f});}}}function Si(r){const t=r.byteLength,e=[];let s=1;for(;s<t-2;)r[s]===0&&r[s+1]===0&&r[s+2]===3?(e.push(s+2),s+=2):s++;if(e.length===0)return r;const i=t-e.length,n=new Uint8Array(i);let o=0;for(s=0;s<i;o++,s++)o===e[0]&&(o++,e.shift()),n[s]=r[o];return n}function Ar(r){const t=r[0];let e="",s="",i=0,n=0,o=0,a=0,l=0,c=0;if(t===0){for(;st(r.subarray(c,c+1))!=="\0";)e+=st(r.subarray(c,c+1)),c+=1;for(e+=st(r.subarray(c,c+1)),c+=1;st(r.subarray(c,c+1))!=="\0";)s+=st(r.subarray(c,c+1)),c+=1;s+=st(r.subarray(c,c+1)),c+=1,i=M(r,12),n=M(r,16),a=M(r,20),l=M(r,24),c=28;}else if(t===1){c+=4,i=M(r,c),c+=4;const u=M(r,c);c+=4;const d=M(r,c);for(c+=4,o=2**32*u+d,Kn(o)||(o=Number.MAX_SAFE_INTEGER,b.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=M(r,c),c+=4,l=M(r,c),c+=4;st(r.subarray(c,c+1))!=="\0";)e+=st(r.subarray(c,c+1)),c+=1;for(e+=st(r.subarray(c,c+1)),c+=1;st(r.subarray(c,c+1))!=="\0";)s+=st(r.subarray(c,c+1)),c+=1;s+=st(r.subarray(c,c+1)),c+=1;}const h=r.subarray(c,r.byteLength);return {schemeIdUri:e,value:s,timeScale:i,presentationTime:o,presentationTimeDelta:n,eventDuration:a,id:l,payload:h}}function br(r,...t){const e=t.length;let s=8,i=e;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(r,4),i=0,s=8;i<e;i++)n.set(t[i],s),s+=t[i].byteLength;return n}function Rr(r,t,e){if(r.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let n;s>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,false)):n=new Uint8Array;const o=new Uint8Array(4);return e&&e.byteLength>0&&new DataView(o.buffer).setUint32(0,e.byteLength,false),br([112,115,115,104],new Uint8Array([s,0,0,0]),r,n,i,o,e||new Uint8Array)}function Lr(r){if(!(r instanceof ArrayBuffer)||r.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},e=new DataView(r),s=e.getUint32(0);if(r.byteLength!==s&&s>44||e.getUint32(4)!==1886614376||(t.version=e.getUint32(8)>>>24,t.version>1))return null;t.systemId=St.hexDump(new Uint8Array(r,12,16));const n=e.getUint32(28);if(t.version===0){if(s-32<n)return null;t.data=new Uint8Array(r,32,n);}else if(t.version===1){t.kids=[];for(let o=0;o<n;o++)t.kids.push(new Uint8Array(r,32+o*16,16));}return t}let te={};class xe{static clearKeyUriToKeyIdMap(){te={};}constructor(t,e,s,i=[1],n=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=i,this.iv=n,this.encrypted=t?t!=="NONE":false,this.isCommonEncryption=this.encrypted&&t!=="AES-128";}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return  true;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ht.FAIRPLAY:case ht.WIDEVINE:case ht.PLAYREADY:case ht.CLEARKEY:return ["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return  false}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof t!="number"&&(this.method==="AES-128"&&!this.iv&&b.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const s=Ir(t);return new xe(this.method,this.uri,"identity",this.keyFormatVersions,s)}const e=Qn(this.uri);if(e)switch(this.keyFormat){case ht.WIDEVINE:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case ht.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Rr(s,null,e);const i=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),n=String.fromCharCode.apply(null,Array.from(i)),o=n.substring(n.indexOf("<"),n.length),c=new DOMParser().parseFromString(o,"text/xml").getElementsByTagName("KID")[0];if(c){const h=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(h){const u=is(h).subarray(0,16);Xn(u),this.keyId=u;}}break}default:{let s=e.subarray(0,16);if(s.length!==16){const i=new Uint8Array(16);i.set(s,16-s.length),s=i;}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s=te[this.uri];if(!s){const i=Object.keys(te).length%Number.MAX_SAFE_INTEGER;s=new Uint8Array(16),new DataView(s.buffer,12,4).setUint32(0,i),te[this.uri]=s;}this.keyId=s;}return this}}function Ir(r){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=r>>8*(15-e)&255;return t}function ye(r=true){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function wr(r){return typeof self<"u"&&r===self.ManagedMediaSource}const bs={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,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}};function Dr(r,t,e=true){var s;const i=ye(e);return (s=i?.isTypeSupported(We(r,t)))!=null?s:false}function We(r,t){return `${t}/mp4;codecs="${r}"`}function Rs(r){return r.split(",").reduce((t,e)=>{const s=bs.video[e];return s?(s*2+t)/(t?3:2):(bs.audio[e]+t)/(t?2:1)},0)}const _e={};function Cr(r,t=true){if(_e[r])return _e[r];const e={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[r];for(let s=0;s<e.length;s++)if(Dr(e[s],"audio",t))return _e[r]=e[s],e[s];return r}const _r=/flac|opus/i;function Ye(r,t=true){return r.replace(_r,e=>Cr(e.toLowerCase(),t))}function Ls(r,t){return r&&r!=="mp4a"?r:t&&t.split(",")[0]}var wt={AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},W={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function kr(r,t){let e;try{e=new Event("addtrack");}catch{e=document.createEvent("Event"),e.initEvent("addtrack",false,false);}e.track=r,t.dispatchEvent(e);}function Ei(r,t){const e=r.mode;if(e==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(t.id))try{if(r.addCue(t),!r.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(s){b.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,r.addCue(i);}catch(i){b.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`);}}e==="disabled"&&(r.mode=e);}function qt(r){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let e=r.cues.length;e--;)r.removeCue(r.cues[e]);t==="disabled"&&(r.mode=t);}function Is(r,t,e,s){const i=r.mode;if(i==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=Fr(r.cues,t,e);for(let o=0;o<n.length;o++)r.removeCue(n[o]);}i==="disabled"&&(r.mode=i);}function Pr(r,t){if(t<r[0].startTime)return 0;const e=r.length-1;if(t>r[e].endTime)return  -1;let s=0,i=e;for(;s<=i;){const n=Math.floor((i+s)/2);if(t<r[n].startTime)i=n-1;else if(t>r[n].startTime&&s<e)s=n+1;else return n}return r[s].startTime-t<t-r[i].startTime?s:i}function Fr(r,t,e){const s=[],i=Pr(r,t);if(i>-1)for(let n=i,o=r.length;n<o;n++){const a=r[n];if(a.startTime>=t&&a.endTime<=e)s.push(a);else if(a.startTime>e)return s}return s}function ce(r){const t=[];for(let e=0;e<r.length;e++){const s=r[e];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&t.push(r[e]);}return t}var Xt={audioId3:"org.id3",emsg:"https://aomedia.org/emsg/ID3"};function Or(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}(()=>{const r=Or();try{r&&new r(0,Number.POSITIVE_INFINITY,"");}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();const ws=["NONE","TYPE-0","TYPE-1",null],Mr=["SDR","PQ","HLG"];var he={No:"",Yes:"YES",v2:"v2"};function Ds(r){const{canSkipUntil:t,canSkipDateRanges:e,age:s}=r,i=s<t/2;return t&&i?e?he.v2:he.Yes:he.No}class Cs{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s;}addDirectives(t){const e=new self.URL(t);return this.msn!==void 0&&e.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Te{constructor(t){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.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=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.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(t){return _s(this._audioGroups,t)}hasSubtitleGroup(t){return _s(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e){if(t==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(e)===-1&&s.push(e);}else if(t==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(e)===-1&&s.push(e);}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return (t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return (t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function _s(r,t){return !t||!r?false:r.indexOf(t)!==-1}function ke(r,t){const e=t.startPTS;if($(e)){let s=0,i;t.sn>r.sn?(s=e-r.start,i=r):(s=r.start-e,i=t),i.duration!==s&&(i.duration=s);}else t.sn>r.sn?r.cc===t.cc&&r.minEndPTS?t.start=r.start+(r.minEndPTS-r.start):t.start=r.start+r.duration:t.start=Math.max(r.start-t.duration,0);}function vi(r,t,e,s,i,n){s-e<=0&&(b.warn("Fragment should have a positive duration",t),s=e+t.duration,n=i+t.duration);let a=e,l=s;const c=t.startPTS,h=t.endPTS;if($(c)){const p=Math.abs(c-e);$(t.deltaPTS)?t.deltaPTS=Math.max(p,t.deltaPTS):t.deltaPTS=p,a=Math.max(e,c),e=Math.min(e,c),i=Math.min(i,t.startDTS),l=Math.min(s,h),s=Math.max(s,h),n=Math.max(n,t.endDTS);}const u=e-t.start;t.start!==0&&(t.start=e),t.duration=s-t.start,t.startPTS=e,t.maxStartPTS=a,t.startDTS=i,t.endPTS=s,t.minEndPTS=l,t.endDTS=n;const d=t.sn;if(!r||d<r.startSN||d>r.endSN)return 0;let f;const g=d-r.startSN,m=r.fragments;for(m[g]=t,f=g;f>0;f--)ke(m[f],m[f-1]);for(f=g;f<m.length-1;f++)ke(m[f],m[f+1]);return r.fragmentHint&&ke(m[m.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=true,u}function Nr(r,t){let e=null;const s=r.fragments;for(let l=s.length-1;l>=0;l--){const c=s[l].initSegment;if(c){e=c;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let i=0,n;if($r(r,t,(l,c)=>{l.relurl&&(i=l.cc-c.cc),$(l.startPTS)&&$(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(n=c),t.PTSKnown=t.alignedSliding=true),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,l.initSegment&&(c.initSegment=l.initSegment,e=l.initSegment);}),e&&(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach(c=>{var h;c&&(!c.initSegment||c.initSegment.relurl===((h=e)==null?void 0:h.relurl))&&(c.initSegment=e);}),t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some(l=>!l),t.deltaUpdateFailed){b.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=t.skippedSegments;l--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc;}else t.canSkipDateRanges&&(t.dateRanges=Ur(r.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const o=t.fragments;if(i){b.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<o.length;l++)o[l].cc+=i;}t.skippedSegments&&(t.startCC=t.fragments[0].cc),Br(r.partList,t.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats;}),n?vi(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Ai(r,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=r.driftStartTime,t.driftStart=r.driftStart;const a=t.advancedDateTime;if(t.advanced&&a){const l=t.edge;t.driftStart||(t.driftStartTime=a,t.driftStart=l),t.driftEndTime=a,t.driftEnd=l;}else t.driftEndTime=r.driftEndTime,t.driftEnd=r.driftEnd,t.advancedDateTime=r.advancedDateTime;}function Ur(r,t,e){const s=ct({},r);return e&&e.forEach(i=>{delete s[i];}),Object.keys(t).forEach(i=>{const n=new zn(t[i].attr,s[i]);n.isValid?s[i]=n:b.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[i].attr)}"`);}),s}function Br(r,t,e){if(r&&t){let s=0;for(let i=0,n=r.length;i<=n;i++){const o=r[i],a=t[i+s];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?e(o,a):s--;}}}function $r(r,t,e){const s=t.skippedSegments,i=Math.max(r.startSN,t.startSN)-t.startSN,n=(r.fragmentHint?1:0)+(s?t.endSN:Math.min(r.endSN,t.endSN))-t.startSN,o=t.startSN-r.startSN,a=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let c=i;c<=n;c++){const h=l[o+c];let u=a[c];s&&!u&&c<s&&(u=t.fragments[c]=h),h&&u&&e(h,u);}}function Ai(r,t){const e=t.startSN+t.skippedSegments-r.startSN,s=r.fragments;e<0||e>=s.length||ze(t,s[e].start);}function ze(r,t){if(t){const e=r.fragments;for(let s=r.skippedSegments;s<e.length;s++)e[s].start+=t;r.fragmentHint&&(r.fragmentHint.start+=t);}}function Gr(r,t=1/0){let e=1e3*r.targetduration;if(r.updated){const s=r.fragments;if(s.length&&e*4>t){const n=s[s.length-1].duration*1e3;n<e&&(e=n);}}else e/=2;return Math.round(e)}function Kr(r,t,e){if(!(r!=null&&r.details))return null;const s=r.details;let i=s.fragments[t-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===t)?i:t<s.startSN&&e&&e.sn===t?e:null}function ks(r,t,e){var s;return r!=null&&r.details?bi((s=r.details)==null?void 0:s.partList,t,e):null}function bi(r,t,e){if(r)for(let s=r.length;s--;){const i=r[s];if(i.index===e&&i.fragment.sn===t)return i}return null}function Vr(r){r.forEach((t,e)=>{const{details:s}=t;s!=null&&s.fragments&&s.fragments.forEach(i=>{i.level=e;});});}function Se(r){switch(r.details){case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_TIMEOUT:case w.LEVEL_LOAD_TIMEOUT:case w.MANIFEST_LOAD_TIMEOUT:return  true}return  false}function Ps(r,t){const e=Se(t);return r.default[`${e?"timeout":"error"}Retry`]}function os(r,t){const e=r.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*r.retryDelayMs,r.maxRetryDelayMs)}function Fs(r){return ut(ut({},r),{errorRetry:null,timeoutRetry:null})}function Ee(r,t,e,s){if(!r)return  false;const i=s?.code,n=t<r.maxNumRetry&&(Hr(i)||!!e);return r.shouldRetry?r.shouldRetry(r,t,e,s,n):n}function Hr(r){return r===0&&navigator.onLine===false||!!r&&(r<400||r>499)}const Ri={search:function(r,t){let e=0,s=r.length-1,i=null,n=null;for(;e<=s;){i=(e+s)/2|0,n=r[i];const o=t(n);if(o>0)e=i+1;else if(o<0)s=i-1;else return n}return null}};function Wr(r,t,e){if(t===null||!Array.isArray(r)||!r.length||!$(t))return null;const s=r[0].programDateTime;if(t<(s||0))return null;const i=r[r.length-1].endProgramDateTime;if(t>=(i||0))return null;e=e||0;for(let n=0;n<r.length;++n){const o=r[n];if(zr(t,e,o))return o}return null}function ve(r,t,e=0,s=0,i=.005){let n=null;if(r){n=t[r.sn-t[0].sn+1]||null;const a=r.endDTS-e;a>0&&a<15e-7&&(e+=15e-7);}else e===0&&t[0].start===0&&(n=t[0]);if(n&&((!r||r.level===n.level)&&qe(e,s,n)===0||Yr(n,r,Math.min(i,s))))return n;const o=Ri.search(t,qe.bind(null,e,s));return o&&(o!==r||!n)?o:n}function Yr(r,t,e){if(t&&t.start===0&&t.level<r.level&&(t.endPTS||0)>0){const s=t.tagList.reduce((i,n)=>(n[0]==="INF"&&(i+=parseFloat(n[1])),i),e);return r.start<=s}return  false}function qe(r=0,t=0,e){if(e.start<=r&&e.start+e.duration>r)return 0;const s=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-s<=r?1:e.start-s>r&&e.start?-1:0}function zr(r,t,e){const s=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return (e.endProgramDateTime||0)-s>r}function qr(r,t){return Ri.search(r,e=>e.cc<t?1:e.cc>t?-1:0)}var rt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},mt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class jr{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=b.log.bind(b,"[info]:"),this.warn=b.warn.bind(b,"[warning]:"),this.error=b.error.bind(b,"[error]:"),this.registerListeners();}registerListeners(){const t=this.hls;t.on(x.ERROR,this.onError,this),t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.LEVEL_UPDATED,this.onLevelUpdated,this);}unregisterListeners(){const t=this.hls;t&&(t.off(x.ERROR,this.onError,this),t.off(x.ERROR,this.onErrorOut,this),t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.LEVEL_UPDATED,this.onLevelUpdated,this));}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={};}startLoad(t){}stopLoad(){this.playlistError=0;}getVariantLevelIndex(t){return t?.type===W.MAIN?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={};}onLevelUpdated(){this.playlistError=0;}onError(t,e){var s,i;if(e.fatal)return;const n=this.hls,o=e.context;switch(e.details){case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case w.FRAG_PARSING_ERROR:if((s=e.frag)!=null&&s.gap){e.errorAction={action:rt.DoNothing,flags:mt.None};return}case w.FRAG_GAP:case w.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=rt.SendAlternateToPenaltyBox;return}case w.LEVEL_EMPTY_ERROR:case w.LEVEL_PARSING_ERROR:{var a,l;const c=e.parent===W.MAIN?e.level:n.loadLevel;e.details===w.LEVEL_EMPTY_ERROR&&((a=e.context)!=null&&(l=a.levelDetails)!=null&&l.live)?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,c):(e.levelRetry=false,e.errorAction=this.getLevelSwitchAction(e,c));}return;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:typeof o?.level=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,o.level));return;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.SUBTITLE_LOAD_ERROR:case w.SUBTITLE_TRACK_LOAD_TIMEOUT:if(o){const c=n.levels[n.loadLevel];if(c&&(o.type===wt.AUDIO_TRACK&&c.hasAudioGroup(o.groupId)||o.type===wt.SUBTITLE_TRACK&&c.hasSubtitleGroup(o.groupId))){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=rt.SendAlternateToPenaltyBox,e.errorAction.flags=mt.MoveAllAlternatesMatchingHost;return}}return;case w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=n.levels[n.loadLevel],h=c?.attrs["HDCP-LEVEL"];h?e.errorAction={action:rt.SendAlternateToPenaltyBox,flags:mt.MoveAllAlternatesMatchingHDCP,hdcpLevel:h}:this.keySystemError(e);}return;case w.BUFFER_ADD_CODEC_ERROR:case w.REMUX_ALLOC_ERROR:case w.BUFFER_APPEND_ERROR:e.errorAction=this.getLevelSwitchAction(e,(i=e.level)!=null?i:n.loadLevel);return;case w.INTERNAL_EXCEPTION:case w.BUFFER_APPENDING_ERROR:case w.BUFFER_FULL_ERROR:case w.LEVEL_SWITCH_ERROR:case w.BUFFER_STALLED_ERROR:case w.BUFFER_SEEK_OVER_HOLE:case w.BUFFER_NUDGE_ON_STALL:e.errorAction={action:rt.DoNothing,flags:mt.None};return}e.type===H.KEY_SYSTEM_ERROR&&this.keySystemError(e);}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=false,t.errorAction=this.getLevelSwitchAction(t,e);}getPlaylistRetryOrSwitchAction(t,e){const s=this.hls,i=Ps(s.config.playlistLoadPolicy,t),n=this.playlistError++;if(Ee(i,n,Se(t),t.response))return {action:rt.RetryRequest,flags:mt.None,retryConfig:i,retryCount:n};const a=this.getLevelSwitchAction(t,e);return i&&(a.retryConfig=i,a.retryCount=n),a}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:n,keyLoadPolicy:o}=e.config,a=Ps(t.details.startsWith("key")?o:n,t),l=e.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(t.details!==w.FRAG_GAP&&i.fragmentError++,Ee(a,l,Se(t),t.response)))return {action:rt.RetryRequest,flags:mt.None,retryConfig:a,retryCount:l};const c=this.getLevelSwitchAction(t,s);return a&&(c.retryConfig=a,c.retryCount=l),c}getLevelSwitchAction(t,e){const s=this.hls;e==null&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var n,o;const c=t.details;i.loadError++,c===w.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;s.autoLevelEnabled||(s.loadLevel=-1);const m=(n=t.frag)==null?void 0:n.type,y=(m===W.AUDIO&&c===w.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(c===w.BUFFER_ADD_CODEC_ERROR||c===w.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:I})=>i.audioCodec!==I),T=t.sourceBufferName==="video"&&(c===w.BUFFER_ADD_CODEC_ERROR||c===w.BUFFER_APPEND_ERROR)&&u.some(({codecSet:I,audioCodec:v})=>i.codecSet!==I&&i.audioCodec===v),{type:R,groupId:E}=(o=t.context)!=null?o:{};for(let I=u.length;I--;){const v=(I+d)%u.length;if(v!==d&&v>=f&&v<=g&&u[v].loadError===0){var a,l;const C=u[v];if(c===w.FRAG_GAP&&m===W.MAIN&&t.frag){const P=u[v].details;if(P){const L=ve(t.frag,P.fragments,t.frag.start);if(L!=null&&L.gap)continue}}else {if(R===wt.AUDIO_TRACK&&C.hasAudioGroup(E)||R===wt.SUBTITLE_TRACK&&C.hasSubtitleGroup(E))continue;if(m===W.AUDIO&&(a=i.audioGroups)!=null&&a.some(P=>C.hasAudioGroup(P))||m===W.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(P=>C.hasSubtitleGroup(P))||y&&i.audioCodec===C.audioCodec||!y&&i.audioCodec!==C.audioCodec||T&&i.codecSet===C.codecSet)continue}h=v;break}}if(h>-1&&s.loadLevel!==h)return t.levelRetry=true,this.playlistError=0,{action:rt.SendAlternateToPenaltyBox,flags:mt.None,nextAutoLevel:h}}return {action:rt.SendAlternateToPenaltyBox,flags:mt.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var s;switch((s=e.errorAction)==null?void 0:s.action){case rt.DoNothing:break;case rt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==w.FRAG_GAP?e.fatal=true:/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:i,hdcpLevel:n,nextAutoLevel:o}=s;switch(i){case mt.None:this.switchLevel(t,o);break;case mt.MoveAllAlternatesMatchingHDCP:n&&(e.maxHdcpLevel=ws[ws.indexOf(n)-1],s.resolved=true),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}s.resolved||this.switchLevel(t,o);}switchLevel(t,e){e!==void 0&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=true,this.hls.nextLoadLevel=this.hls.nextAutoLevel);}}class Li{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=false,this.log=void 0,this.warn=void 0,this.log=b.log.bind(b,`${e}:`),this.warn=b.warn.bind(b,`${e}:`),this.hls=t;}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null;}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1);}startLoad(){this.canLoad=true,this.requestScheduled=-1,this.loadPlaylist();}stopLoad(){this.canLoad=false,this.clearTimer();}switchParams(t,e,s){const i=e?.renditionReports;if(i){let n=-1;for(let o=0;o<i.length;o++){const a=i[o];let l;try{l=new self.URL(a.URI,e.url).href;}catch(c){b.warn(`Could not construct new URL for Rendition Report: ${c}`),l=a.URI||"";}if(l===t){n=o;break}else l===t.substring(0,l.length)&&(n=o);}if(n!==-1){const o=i[n],a=parseInt(o["LAST-MSN"])||e?.lastPartSn;let l=parseInt(o["LAST-PART"])||e?.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(e.age-e.partTarget,e.targetduration);l>=0&&h>e.partTarget&&(l+=1);}const c=s&&Ds(s);return new Cs(a,l>=0?l:void 0,c)}}}loadPlaylist(t){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now());}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,s){const{details:i,stats:n}=e,o=self.performance.now(),a=n.loading.first?Math.max(0,o-n.loading.first):0;if(i.advancedDateTime=Date.now()-a,i.live||s!=null&&s.live){if(i.reloaded(s),s&&this.log(`live playlist ${t} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),s&&i.fragments.length>0&&Nr(s,i),!this.canLoad||!i.live)return;let l,c,h;if(i.canBlockReload&&i.endSN&&i.advanced){const p=this.hls.config.lowLatencyMode,y=i.lastPartSn,A=i.endSN,T=i.lastPartIndex,R=T!==-1,E=y===A,I=p?0:T;R?(c=E?A+1:y,h=E?I:T+1):c=A+1;const v=i.age,C=v+i.ageHeader;let P=Math.min(C-i.partTarget,i.targetduration*1.5);if(P>0){if(s&&P>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${P} with playlist age: ${i.age}`),P=0;else {const L=Math.floor(P/i.targetduration);if(c+=L,h!==void 0){const _=Math.round(P%i.targetduration/i.partTarget);h+=_;}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${v.toFixed(2)}s goal: ${P} skip sn ${L} to part ${h}`);}i.tuneInGoal=P;}if(l=this.getDeliveryDirectives(i,e.deliveryDirectives,c,h),p||!E){this.loadPlaylist(l);return}}else (i.canBlockReload||i.canSkipUntil)&&(l=this.getDeliveryDirectives(i,e.deliveryDirectives,c,h));const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=(i.edge-d)*1e3,g=Gr(i,f);i.updated&&o>this.requestScheduled+g&&(this.requestScheduled=n.loading.start),c!==void 0&&i.canBlockReload?this.requestScheduled=n.loading.first+g-(i.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+g<o?this.requestScheduled=o:this.requestScheduled-o<=0&&(this.requestScheduled+=g);let m=this.requestScheduled-o;m=Math.max(0,m),this.log(`reload live playlist ${t} in ${Math.round(m)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),m);}else this.clearTimer();}getDeliveryDirectives(t,e,s,i){let n=Ds(t);return e!=null&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,n=he.No),new Cs(s,i,n)}checkRetry(t){const e=t.details,s=Se(t),i=t.errorAction,{action:n,retryCount:o=0,retryConfig:a}=i||{},l=!!i&&!!a&&(n===rt.RetryRequest||!i.resolved&&n===rt.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,o>=a.maxNumRetry)return  false;if(s&&(c=t.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else {const h=os(a,o);this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${e}" in ${h}ms`);}t.levelRetry=true,i.resolved=true;}return l}}class Mt{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s;}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t;}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class Xr{constructor(t,e,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 Mt(t),this.fast_=new Mt(e),this.defaultTTFB_=i,this.ttfb_=new Mt(t);}update(t,e){const{slow_:s,fast_:i,ttfb_:n}=this;s.halfLife!==t&&(this.slow_=new Mt(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new Mt(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new Mt(t,n.getEstimate(),n.getTotalWeight()));}sample(t,e){t=Math.max(t,this.minDelayMs_);const s=8*e,i=t/1e3,n=s/i;this.fast_.sample(i,n),this.slow_.sample(i,n);}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,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_}destroy(){}}const Ii={supported:true,configurations:[],decodingInfoResults:[{supported:true,powerEfficient:true,smooth:true}]},Os={};function Qr(r,t,e,s,i,n){const o=r.audioCodec?r.audioGroups:null,a=n?.audioCodec,l=n?.channels,c=l?parseInt(l):a?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((u,d)=>{if(d){const f=t.groups[d];if(!f)throw new Error(`Audio track group ${d} not found`);Object.keys(f.channels).forEach(g=>{u[g]=(u[g]||0)+f.channels[g];});}return u},{2:0});}catch{return  true}return r.videoCodec!==void 0&&(r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(s,30)||r.videoRange!=="SDR"&&r.videoRange!==e||r.bitrate>Math.max(i,8e6))||!!h&&$(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function Zr(r,t,e){const s=r.videoCodec,i=r.audioCodec;if(!s||!i||!e)return Promise.resolve(Ii);const n={width:r.width,height:r.height,bitrate:Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)),framerate:r.frameRate||30},o=r.videoRange;o!=="SDR"&&(n.transferFunction=o.toLowerCase());const a=s.split(",").map(l=>({type:"media-source",video:ut(ut({},n),{},{contentType:We(l,"video")})}));return i&&r.audioGroups&&r.audioGroups.forEach(l=>{var c;l&&((c=t.groups[l])==null||c.tracks.forEach(h=>{if(h.groupId===l){const u=h.channels||"",d=parseFloat(u);$(d)&&d>2&&a.push.apply(a,i.split(",").map(f=>({type:"media-source",audio:{contentType:We(f,"audio"),channels:""+d}})));}}));}),Promise.all(a.map(l=>{const c=Jr(l);return Os[c]||(Os[c]=e.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:a,decodingInfoResults:l})).catch(l=>({supported:false,configurations:a,decodingInfoResults:[],error:l}))}function Jr(r){const{audio:t,video:e}=r,s=e||t;if(s){const i=s.contentType.split('"')[1];if(e)return `r${e.height}x${e.width}f${Math.ceil(e.framerate)}${e.transferFunction||"sd"}_${i}_${Math.ceil(e.bitrate/1e5)}`;if(t)return `c${t.channels}${t.spatialRendering?"s":"n"}_${i}`}return ""}function to(){if(typeof matchMedia=="function"){const r=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(r.media!==t.media)return r.matches===true}return  false}function eo(r,t){let e=false,s=[];return r&&(e=r!=="SDR",s=[r]),t&&(s=t.allowedVideoRanges||Mr.slice(0),e=t.preferHDR!==void 0?t.preferHDR:to(),e?s=s.filter(i=>i!=="SDR"):s=["SDR"]),{preferHDR:e,allowedVideoRanges:s}}function so(r,t,e,s,i){const n=Object.keys(r),o=s?.channels,a=s?.audioCodec,l=o&&parseInt(o)===2;let c=true,h=false,u=1/0,d=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:y}=eo(t,i);for(let E=n.length;E--;){const I=r[n[E]];c=I.channels[2]>0,u=Math.min(u,I.minHeight),d=Math.min(d,I.minFramerate),f=Math.min(f,I.minBitrate);const v=y.filter(C=>I.videoRanges[C]>0);v.length>0&&(h=true,m=v);}u=$(u)?u:0,d=$(d)?d:0;const A=Math.max(1080,u),T=Math.max(30,d);return f=$(f)?f:e,e=Math.max(f,e),h||(t=void 0,m=[]),{codecSet:n.reduce((E,I)=>{const v=r[I];if(I===E)return E;if(v.minBitrate>e)return Rt(I,`min bitrate of ${v.minBitrate} > current estimate of ${e}`),E;if(!v.hasDefaultAudio)return Rt(I,"no renditions with default or auto-select sound found"),E;if(a&&I.indexOf(a.substring(0,4))%5!==0)return Rt(I,`audio codec preference "${a}" not found`),E;if(o&&!l){if(!v.channels[o])return Rt(I,`no renditions with ${o} channel sound found (channels options: ${Object.keys(v.channels)})`),E}else if((!a||l)&&c&&v.channels[2]===0)return Rt(I,"no renditions with stereo sound found"),E;return v.minHeight>A?(Rt(I,`min resolution of ${v.minHeight} > maximum of ${A}`),E):v.minFramerate>T?(Rt(I,`min framerate of ${v.minFramerate} > maximum of ${T}`),E):m.some(C=>v.videoRanges[C]>0)?v.maxScore<g?(Rt(I,`max score of ${v.maxScore} < selected max of ${g}`),E):E&&(Rs(I)>=Rs(E)||v.fragmentError>r[E].fragmentError)?E:(g=v.maxScore,I):(Rt(I,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),E)},void 0),videoRanges:m,preferHDR:p,minFramerate:d,minBitrate:f}}function Rt(r,t){b.log(`[abr] start candidates with "${r}" ignored because ${t}`);}function io(r){return r.reduce((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:false,hasAutoSelect:false}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=true),s.hasAutoSelect&&(t.hasAutoSelectAudio=true),t},{hasDefaultAudio:false,hasAutoSelectAudio:false,groups:{}})}function no(r,t,e,s){return r.slice(e,s+1).reduce((i,n)=>{if(!n.codecSet)return i;const o=n.audioGroups;let a=i[n.codecSet];a||(i[n.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,n.bitrate);const l=Math.min(n.height,n.width);return a.minHeight=Math.min(a.minHeight,l),a.minFramerate=Math.min(a.minFramerate,n.frameRate),a.maxScore=Math.max(a.maxScore,n.score),a.fragmentError+=n.fragmentError,a.videoRanges[n.videoRange]=(a.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;const h=t.groups[c];h&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{a.channels[u]=(a.channels[u]||0)+h.channels[u];}));}),i},{})}function vt(r,t,e){if("attrs"in r){const s=t.indexOf(r);if(s!==-1)return s}for(let s=0;s<t.length;s++){const i=t[s];if($t(r,i,e))return s}return  -1}function $t(r,t,e){const{groupId:s,name:i,lang:n,assocLang:o,characteristics:a,default:l}=r,c=r.forced;return (s===void 0||t.groupId===s)&&(i===void 0||t.name===i)&&(n===void 0||t.lang===n)&&(n===void 0||t.assocLang===o)&&(l===void 0||t.default===l)&&(c===void 0||t.forced===c)&&(a===void 0||ro(a,t.characteristics))&&(e===void 0||e(r,t))}function ro(r,t=""){const e=r.split(","),s=t.split(",");return e.length===s.length&&!e.some(i=>s.indexOf(i)===-1)}function Nt(r,t){const{audioCodec:e,channels:s}=r;return (e===void 0||(t.audioCodec||"").substring(0,4)===e.substring(0,4))&&(s===void 0||s===(t.channels||"2"))}function oo(r,t,e,s,i){const n=t[s],a=t.reduce((d,f,g)=>{const m=f.uri;return (d[m]||(d[m]=[])).push(g),d},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const l=n.videoRange,c=n.frameRate,h=n.codecSet.substring(0,4),u=Ms(t,s,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return  false;const f=d.audioGroups,g=e.filter(m=>!f||f.indexOf(m.groupId)!==-1);return vt(r,g,i)>-1});return u>-1?u:Ms(t,s,d=>{const f=d.audioGroups,g=e.filter(m=>!f||f.indexOf(m.groupId)!==-1);return vt(r,g,i)>-1})}function Ms(r,t,e){for(let s=t;s;s--)if(e(r[s]))return s;for(let s=t+1;s<r.length;s++)if(e(r[s]))return s;return  -1}class ao{constructor(t){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.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:e,partCurrent:s,hls:i}=this,{autoLevelEnabled:n,media:o}=i;if(!e||!o)return;const a=performance.now(),l=s?s.stats:e.stats,c=s?s.duration:e.duration,h=a-l.loading.start,u=i.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||e.level<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!n||o.paused||!o.playbackRate||!o.readyState)return;const d=i.mainForwardBufferInfo;if(d===null)return;const f=this.bwEstimator.getEstimateTTFB(),g=Math.abs(o.playbackRate);if(h<=Math.max(f,1e3*(c/(g*2))))return;const m=d.len/g,p=l.loading.first?l.loading.first-l.loading.start:-1,y=l.loaded&&p>-1,A=this.getBwEstimate(),T=i.levels,R=T[e.level],E=l.total||Math.max(l.loaded,Math.round(c*R.averageBitrate/8));let I=y?h-p:h;I<1&&y&&(I=Math.min(h,l.loaded*8/A));const v=y?l.loaded*1e3/I:0,C=v?(E-l.loaded)/v:E*8/A+f/1e3;if(C<=m)return;const P=v?v*8:A;let L=Number.POSITIVE_INFINITY,_;for(_=e.level-1;_>u;_--){const q=T[_].maxBitrate;if(L=this.getTimeToLoadFrag(f/1e3,P,c*q,!T[_].details),L<m)break}if(L>=C||L>c*10)return;i.nextLoadLevel=i.nextAutoLevel=_,y?this.bwEstimator.sample(h-Math.min(f,p),l.loaded):this.bwEstimator.sampleTTFB(h);const D=T[_].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>D&&this.resetEstimator(D),this.clearTimer(),b.warn(`[abr] Fragment ${e.sn}${s?" part "+s.index:""} of level ${e.level} is loading too slowly;
      Time to underbuffer: ${m.toFixed(3)} s
      Estimated load time for current fragment: ${C.toFixed(3)} s
      Estimated load time for down switch fragment: ${L.toFixed(3)} s
      TTFB estimate: ${p|0} ms
      Current BW estimate: ${$(A)?A|0:"Unknown"} bps
      New BW estimate: ${this.getBwEstimate()|0} bps
      Switching to level ${_} @ ${D|0} bps`),i.trigger(x.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:s,stats:l});},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners();}resetEstimator(t){t&&(b.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator();}initEstimator(){const t=this.hls.config;return new Xr(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.FRAG_LOADING,this.onFragLoading,this),t.on(x.FRAG_LOADED,this.onFragLoaded,this),t.on(x.FRAG_BUFFERED,this.onFragBuffered,this),t.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(x.LEVEL_LOADED,this.onLevelLoaded,this),t.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(x.ERROR,this.onError,this);}unregisterListeners(){const{hls:t}=this;t&&(t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.FRAG_LOADING,this.onFragLoading,this),t.off(x.FRAG_LOADED,this.onFragLoaded,this),t.off(x.FRAG_BUFFERED,this.onFragBuffered,this),t.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(x.LEVEL_LOADED,this.onLevelLoaded,this),t.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(x.ERROR,this.onError,this));}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null;}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,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(t,e){const s=e.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=e.part)!=null?i:null;}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100);}}onLevelSwitching(t,e){this.clearTimer();}onError(t,e){if(!e.fatal)switch(e.details){case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case w.FRAG_LOAD_TIMEOUT:{const s=e.frag,{fragCurrent:i,partCurrent:n}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const o=performance.now(),a=n?n.stats:s.stats,l=o-a.loading.start,c=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),a.loaded);}else this.bwEstimator.sampleTTFB(l);}break}}}getTimeToLoadFrag(t,e,s,i){const n=t+s/e,o=i?this.lastLevelLoadSec:0;return n+o}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,n=i.end-i.start;$(n)&&(this.lastLevelLoadSec=n/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD);}onFragLoaded(t,{frag:e,part:s}){const i=s?s.stats:e.stats;if(e.type===W.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const n=s?s.duration:e.duration,o=this.hls.levels[e.level],a=(o.loaded?o.loaded.bytes:0)+i.loaded,l=(o.loaded?o.loaded.duration:0)+n;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l);}if(e.bitrateTest){const n={stats:i,frag:e,part:s,id:e.type};this.onFragBuffered(x.FRAG_BUFFERED,n),e.bitrateTest=false;}else this.lastLoadedFragLevel=e.level;}}onFragBuffered(t,e){const{frag:s,part:i}=e,n=i!=null&&i.stats.loaded?i.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;const o=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,n.loaded),n.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0;}ignoreFragment(t){return t.type!==W.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1);}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,n=this.findBestLevel(s,e,t,0,i,1,1);if(n>-1)return n;const o=this.hls.firstLevel,a=Math.min(Math.max(o,e),t);return b.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(t!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const n=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const o=this.hls.levels;if(o.length>Math.max(t,n)&&o[t].loadError<=o[n].loadError)return t}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:i,config:n,minAutoLevel:o}=s,a=e?e.duration:t?t.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(c){const p=this.findBestLevel(l,o,i,c,0,h,u);if(p>=0)return p}let d=a?Math.min(a,n.maxStarvationDelay):n.maxStarvationDelay;if(!c){const p=this.bitrateTestDelay;p&&(d=(a?Math.min(a,n.maxLoadingDelay):n.maxLoadingDelay)-p,b.info(`[abr] bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1);}const f=this.findBestLevel(l,o,i,c,d,h,u);if(b.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`),f>-1)return f;const g=s.levels[o],m=s.levels[s.loadLevel];return g?.bitrate<m?.bitrate?o:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&e.playbackRate!==0?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return (i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,i,n,o,a){var l;const c=i+n,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:y}=this.hls;if(g.length===1)return 0;const A=g[u],T=!!(A!=null&&(l=A.details)!=null&&l.live),R=p===-1||h===-1;let E,I="SDR",v=A?.frameRate||0;const{audioPreference:C,videoPreference:P}=y,L=this.audioTracksByGroup||(this.audioTracksByGroup=io(m));if(R){if(this.firstSelection!==-1)return this.firstSelection;const V=this.codecTiers||(this.codecTiers=no(g,L,e,s)),B=so(V,I,t,C,P),{codecSet:j,videoRanges:Q,minFramerate:O,minBitrate:F,preferHDR:Y}=B;E=j,I=Y?Q[Q.length-1]:Q[0],v=O,t=Math.max(t,F),b.log(`[abr] picked start tier ${JSON.stringify(B)}`);}else E=A?.codecSet,I=A?.videoRange;const _=f?f.duration:d?d.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,q=[];for(let V=s;V>=e;V--){var X;const B=g[V],j=V>u;if(!B)continue;if(y.useMediaCapabilities&&!B.supportedResult&&!B.supportedPromise){const tt=navigator.mediaCapabilities;typeof tt?.decodingInfo=="function"&&Qr(B,L,I,v,t,C)?(B.supportedPromise=Zr(B,L,tt),B.supportedPromise.then(U=>{if(!this.hls)return;B.supportedResult=U;const N=this.hls.levels,Z=N.indexOf(B);U.error?b.warn(`[abr] MediaCapabilities decodingInfo error: "${U.error}" for level ${Z} ${JSON.stringify(U)}`):U.supported||(b.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${Z} ${JSON.stringify(U)}`),Z>-1&&N.length>1&&(b.log(`[abr] Removing unsupported level ${Z}`),this.hls.removeLevel(Z)));})):B.supportedResult=Ii;}if(E&&B.codecSet!==E||I&&B.videoRange!==I||j&&v>B.frameRate||!j&&v>0&&v<B.frameRate||B.supportedResult&&!((X=B.supportedResult.decodingInfoResults)!=null&&X[0].smooth)){q.push(V);continue}const Q=B.details,O=(f?Q?.partTarget:Q?.averagetargetduration)||_;let F;j?F=a*t:F=o*t;const Y=_&&i>=_*2&&n===0?g[V].averageBitrate:g[V].maxBitrate,G=this.getTimeToLoadFrag(D,F,Y*O,Q===void 0);if(F>=Y&&(V===h||B.loadError===0&&B.fragmentError===0)&&(G<=D||!$(G)||T&&!this.bitrateTestDelay||G<c)){const tt=this.forcedAutoLevel;return V!==p&&(tt===-1||tt!==p)&&(q.length&&b.trace(`[abr] Skipped level(s) ${q.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[q[0]].codecs}" ${g[q[0]].videoRange}; not compatible with "${A.codecs}" ${I}`),b.info(`[abr] switch candidate:${u}->${V} adjustedbw(${Math.round(F)})-bitrate=${Math.round(F-Y)} ttfb:${D.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${G.toFixed(1)} firstSelection:${R} codecSet:${E} videoRange:${I} hls.loadLevel:${p}`)),R&&(this.firstSelection=V),V}}return  -1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls,i=Math.min(Math.max(t,s),e);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i);}}class lo{constructor(){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(t){return this._tickInterval?false:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),true)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,true):false}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,true):false}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(){}}var xt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};const co={length:0,start:()=>0,end:()=>0};class nt{static isBuffered(t,e){try{if(t){const s=nt.getBuffered(t);for(let i=0;i<s.length;i++)if(e>=s.start(i)&&e<=s.end(i))return !0}}catch{}return  false}static bufferInfo(t,e,s){try{if(t){const i=nt.getBuffered(t),n=[];let o;for(o=0;o<i.length;o++)n.push({start:i.start(o),end:i.end(o)});return this.bufferedInfo(n,e,s)}}catch{}return {len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.sort(function(c,h){const u=c.start-h.start;return u||h.end-c.end});let i=[];if(s)for(let c=0;c<t.length;c++){const h=i.length;if(h){const u=i[h-1].end;t[c].start-u<s?t[c].end>u&&(i[h-1].end=t[c].end):i.push(t[c]);}else i.push(t[c]);}else i=t;let n=0,o,a=e,l=e;for(let c=0;c<i.length;c++){const h=i[c].start,u=i[c].end;if(e+s>=h&&e<u)a=h,l=u,n=l-e;else if(e+s<h){o=h;break}}return {len:n,start:a||0,end:l||0,nextStart:o}}static getBuffered(t){try{return t.buffered}catch(e){return b.log("failed to get media.buffered",e),co}}}class wi{constructor(t,e,s,i=0,n=-1,o=false){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=ee(),this.buffering={audio:ee(),video:ee(),audiovideo:ee()},this.level=t,this.sn=e,this.id=s,this.size=i,this.part=n,this.partial=o;}}function ee(){return {start:0,executeStart:0,executeEnd:0,end:0}}function ue(r,t){for(let s=0,i=r.length;s<i;s++){var e;if(((e=r[s])==null?void 0:e.cc)===t)return r[s]}return null}function ho(r,t,e){return !!(t&&(e.endCC>e.startCC||r&&r.cc<e.startCC))}function uo(r,t){const e=r.fragments,s=t.fragments;if(!s.length||!e.length){b.log("No fragments to align");return}const i=ue(e,s[0].cc);if(!i||i&&!i.startPTS){b.log("No frag in previous level to align on");return}return i}function Ns(r,t){if(r){const e=r.start+t;r.start=r.startPTS=e,r.endPTS=e+r.duration;}}function Di(r,t){const e=t.fragments;for(let s=0,i=e.length;s<i;s++)Ns(e[s],r);t.fragmentHint&&Ns(t.fragmentHint,r),t.alignedSliding=true;}function fo(r,t,e){t&&(go(r,e,t),!e.alignedSliding&&t&&Ae(e,t),!e.alignedSliding&&t&&!e.skippedSegments&&Ai(t,e));}function go(r,t,e){if(ho(r,e,t)){const s=uo(e,t);s&&$(s.start)&&(b.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),Di(s.start,t));}}function Ae(r,t){if(!r.hasProgramDateTime||!t.hasProgramDateTime)return;const e=r.fragments,s=t.fragments;if(!e.length||!s.length)return;let i,n;const o=Math.min(t.endCC,r.endCC);t.startCC<o&&r.startCC<o&&(i=ue(s,o),n=ue(e,o)),(!i||!n)&&(i=s[Math.floor(s.length/2)],n=ue(e,i.cc)||e[Math.floor(e.length/2)]);const a=i.programDateTime,l=n.programDateTime;if(!a||!l)return;const c=(l-a)/1e3-(n.start-i.start);Di(c,r);}const Us=Math.pow(2,17);class mo{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t;}destroy(){this.loader&&(this.loader.destroy(),this.loader=null);}abort(){this.loader&&this.loader.abort();}load(t,e){const s=t.url;if(!s)return Promise.reject(new Ct({type:H.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:false,frag:t,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,n=i.fLoader,o=i.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(f=>f[0]==="GAP")){l($s(t));return}else t.gap=false;const c=this.loader=t.loader=n?new n(i):new o(i),h=Bs(t),u=Fs(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:Us};t.stats=c.stats,c.load(h,d,{onSuccess:(f,g,m,p)=>{this.resetLoader(t,c);let y=f.data;m.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(y.slice(0,16)),y=y.slice(16)),a({frag:t,part:null,payload:y,networkDetails:p});},onError:(f,g,m,p)=>{this.resetLoader(t,c),l(new Ct({type:H.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:false,frag:t,response:ut({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:p}));},onAbort:(f,g,m)=>{this.resetLoader(t,c),l(new Ct({type:H.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:false,frag:t,error:new Error("Aborted"),networkDetails:m,stats:f}));},onTimeout:(f,g,m)=>{this.resetLoader(t,c),l(new Ct({type:H.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:false,frag:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:f}));},onProgress:(f,g,m,p)=>{e&&e({frag:t,part:null,payload:m,networkDetails:p});}});})}loadPart(t,e,s){this.abort();const i=this.config,n=i.fLoader,o=i.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){l($s(t,e));return}const c=this.loader=t.loader=n?new n(i):new o(i),h=Bs(t,e),u=Fs(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Us};e.stats=c.stats,c.load(h,d,{onSuccess:(f,g,m,p)=>{this.resetLoader(t,c),this.updateStatsFromPart(t,e);const y={frag:t,part:e,payload:f.data,networkDetails:p};s(y),a(y);},onError:(f,g,m,p)=>{this.resetLoader(t,c),l(new Ct({type:H.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:false,frag:t,part:e,response:ut({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:p}));},onAbort:(f,g,m)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,c),l(new Ct({type:H.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:false,frag:t,part:e,error:new Error("Aborted"),networkDetails:m,stats:f}));},onTimeout:(f,g,m)=>{this.resetLoader(t,c),l(new Ct({type:H.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:false,frag:t,part:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:f}));}});})}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,n=i.total;if(s.loaded+=i.loaded,n){const l=Math.round(t.duration/e.duration),c=Math.min(Math.round(s.loaded/n),l),u=(l-c)*Math.round(s.loaded/c);s.total=s.loaded+u;}else s.total=Math.max(s.loaded,s.total);const o=s.loading,a=i.loading;o.start?o.first+=a.first-a.start:(o.start=a.start,o.first=a.first),o.end=a.end;}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy();}}function Bs(r,t=null){const e=t||r,s={frag:r,part:t,responseType:"arraybuffer",url:e.url,headers:{},rangeStart:0,rangeEnd:0},i=e.byteRangeStartOffset,n=e.byteRangeEndOffset;if($(i)&&$(n)){var o;let a=i,l=n;if(r.sn==="initSegment"&&((o=r.decryptdata)==null?void 0:o.method)==="AES-128"){const c=n-i;c%16&&(l=n+(16-c%16)),i!==0&&(s.resetIV=true,a=i-16);}s.rangeStart=a,s.rangeEnd=l;}return s}function $s(r,t){const e=new Error(`GAP ${r.gap?"tag":"attribute"} found`),s={type:H.MEDIA_ERROR,details:w.FRAG_GAP,fatal:false,frag:r,error:e,networkDetails:null};return t&&(s.part=t),(t||r).stats.aborted=true,new Ct(s)}class Ct extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t;}}class po{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e;}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class xo{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e;}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},false,["encrypt","decrypt"])}}function yo(r){const t=r.byteLength,e=t&&new DataView(r.buffer).getUint8(t-1);return e?Ft(r,0,t-e):r}class To{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_(t){const e=new DataView(t),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=e.getUint32(i*4);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],n=s[1],o=s[2],a=s[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],f=new Uint32Array(256);let g=0,m=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let y=m^m<<1^m<<2^m<<3^m<<4;y=y>>>8^y&255^99,t[g]=y,e[y]=g;const A=f[g],T=f[A],R=f[T];let E=f[y]*257^y*16843008;i[g]=E<<24|E>>>8,n[g]=E<<16|E>>>16,o[g]=E<<8|E>>>24,a[g]=E,E=R*16843009^T*65537^A*257^g*16843008,c[y]=E<<24|E>>>8,h[y]=E<<16|E>>>16,u[y]=E<<8|E>>>24,d[y]=E,g?(g=A^f[f[f[R^A]]],m^=f[f[m]]):g=m=1;}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=true,i=0;for(;i<e.length&&s;)s=e[i]===this.key[i],i++;if(s)return;this.key=e;const n=this.keySize=e.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const o=this.ksRows=(n+6+1)*4;let a,l;const c=this.keySchedule=new Uint32Array(o),h=this.invKeySchedule=new Uint32Array(o),u=this.sBox,d=this.rcon,f=this.invSubMix,g=f[0],m=f[1],p=f[2],y=f[3];let A,T;for(a=0;a<o;a++){if(a<n){A=c[a]=e[a];continue}T=A,a%n===0?(T=T<<8|T>>>24,T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255],T^=d[a/n|0]<<24):n>6&&a%n===4&&(T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255]),c[a]=A=(c[a-n]^T)>>>0;}for(l=0;l<o;l++)a=o-l,l&3?T=c[a]:T=c[a-4],l<4||a<=4?h[l]=T:h[l]=g[u[T>>>24]]^m[u[T>>>16&255]]^p[u[T>>>8&255]]^y[u[T&255]],h[l]=h[l]>>>0;}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,s){const i=this.keySize+6,n=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],c=a[1],h=a[2],u=a[3],d=this.uint8ArrayToUint32Array_(s);let f=d[0],g=d[1],m=d[2],p=d[3];const y=new Int32Array(t),A=new Int32Array(y.length);let T,R,E,I,v,C,P,L,_,D,q,X,V,B;const j=this.networkToHostOrderSwap;for(;e<y.length;){for(_=j(y[e]),D=j(y[e+1]),q=j(y[e+2]),X=j(y[e+3]),v=_^n[0],C=X^n[1],P=q^n[2],L=D^n[3],V=4,B=1;B<i;B++)T=l[v>>>24]^c[C>>16&255]^h[P>>8&255]^u[L&255]^n[V],R=l[C>>>24]^c[P>>16&255]^h[L>>8&255]^u[v&255]^n[V+1],E=l[P>>>24]^c[L>>16&255]^h[v>>8&255]^u[C&255]^n[V+2],I=l[L>>>24]^c[v>>16&255]^h[C>>8&255]^u[P&255]^n[V+3],v=T,C=R,P=E,L=I,V=V+4;T=o[v>>>24]<<24^o[C>>16&255]<<16^o[P>>8&255]<<8^o[L&255]^n[V],R=o[C>>>24]<<24^o[P>>16&255]<<16^o[L>>8&255]<<8^o[v&255]^n[V+1],E=o[P>>>24]<<24^o[L>>16&255]<<16^o[v>>8&255]<<8^o[C&255]^n[V+2],I=o[L>>>24]<<24^o[v>>16&255]<<16^o[C>>8&255]<<8^o[P&255]^n[V+3],A[e]=j(T^f),A[e+1]=j(I^g),A[e+2]=j(E^m),A[e+3]=j(R^p),f=_,g=D,m=q,p=X,e=e+4;}return A.buffer}}const So=16;class as{constructor(t,{removePKCS7Padding:e=true}={}){if(this.logEnabled=true,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.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=e,e)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:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?yo(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null);}decrypt(t,e,s){return this.useSoftware?new Promise((i,n)=>{this.softwareDecrypt(new Uint8Array(t),e,s);const o=this.flush();o?i(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"));}):this.webCryptoDecrypt(new Uint8Array(t),e,s)}softwareDecrypt(t,e,s){const{currentIV:i,currentResult:n,remainderData:o}=this;this.logOnce("JS AES decrypt"),o&&(t=gt(o,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;i&&(s=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new To),l.expandKey(e);const c=n;return this.currentResult=l.decrypt(a.buffer,0,s),this.currentIV=Ft(a,-16).buffer,c||null}webCryptoDecrypt(t,e,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s));this.key=e,this.fastAesKey=new xo(this.subtle,e);}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new po(this.subtle,new Uint8Array(s)).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(b.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,e,s)))}onWebCryptoError(t,e,s){this.useSoftware=true,this.logEnabled=true,this.softwareDecrypt(t,e,s);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%So;return s!==t.length&&(e=Ft(t,0,s),this.remainderData=Ft(t,s)),e}logOnce(t){this.logEnabled&&(b.log(`[decrypter]: ${t}`),this.logEnabled=false);}}const Eo={toString:function(r){let t="";const e=r.length;for(let s=0;s<e;s++)t+=`[${r.start(s).toFixed(3)}-${r.end(s).toFixed(3)}]`;return t}},k={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 Ci extends lo{constructor(t,e,s,i,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=k.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=false,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=false,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=false,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=i,this.log=b.log.bind(b,`${i}:`),this.warn=b.warn.bind(b,`${i}:`),this.hls=t,this.fragmentLoader=new mo(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new as(t.config),t.on(x.MANIFEST_LOADED,this.onManifestLoaded,this);}doTick(){this.onTickEnd();}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=k.STOPPED;}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return  false;const s=e.partList;if(s!=null&&s.length){const n=s[s.length-1];return nt.isBuffered(this.media,n.start+n.duration/2)}const i=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(i)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var t;return (t=this.levelLastLoaded)==null?void 0:t.details}}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const i=this.config;this.levels&&i.autoStartLoad&&this.state===k.STOPPED&&this.startLoad(i.startPosition);}onMediaDetaching(){const t=this.media;t!=null&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=false,this.fragmentTracker.removeAllFragments(),this.stopLoad();}onMediaSeeking(){const{config:t,fragCurrent:e,media:s,mediaBuffer:i,state:n}=this,o=s?s.currentTime:0,a=nt.bufferInfo(i||s,o,t.maxBufferHole);if(this.log(`media seeking to ${$(o)?o.toFixed(3):o}, state: ${n}`),this.state===k.ENDED)this.resetLoadingState();else if(e){const l=t.maxFragLookUpTolerance,c=e.start-l,h=e.start+e.duration+l;if(!a.len||h<a.start||c>a.end){const u=o>h;(o<c||u)&&(u&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null);}}s&&(this.fragmentTracker.removeFragmentsInRange(o,1/0,this.playlistType,true),this.lastCurrentTime=o),!this.loadedmetadata&&!a.len&&(this.nextLoadPosition=this.startPosition=o),this.tickImmediate();}onMediaEnded(){this.startPosition=this.lastCurrentTime=0;}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[];}onHandlerDestroying(){this.hls.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null;}onHandlerDestroyed(){this.state=k.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(t,e,s){this._loadFragForPlayback(t,e,s);}_loadFragForPlayback(t,e,s){const i=n=>{if(this.fragContextChanged(t)){this.warn(`Fragment ${t.sn}${n.part?" p: "+n.part.index:""} of level ${t.level} was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(n);};this._doFragLoad(t,e,s,i).then(n=>{if(!n)return;const o=this.state;if(this.fragContextChanged(t)){(o===k.FRAG_LOADING||!this.fragCurrent&&o===k.PARSING)&&(this.fragmentTracker.removeFragment(t),this.state=k.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(x.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n);}).catch(n=>{this.state===k.STOPPED||this.state===k.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(t));});}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===xt.APPENDING){const n=t.type,o=this.getFwdBufferInfo(this.mediaBuffer,n),a=Math.max(t.duration,o?o.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?t.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,t.duration))&&s.removeFragment(t);}else ((e=this.mediaBuffer)==null?void 0:e.buffered.length)===0?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===xt.PARTIAL&&s.removeFragment(t));}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type});}t.fragments[0]||(t.deltaUpdateFailed=true);}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(x.BUFFER_FLUSHING,i);}_loadInitSegment(t,e){this._doFragLoad(t,e).then(s=>{if(!s||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{payload:n}=s,o=t.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&o.method==="AES-128"){const a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer).catch(l=>{throw i.trigger(x.ERROR,{type:H.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:false,error:l,reason:l.message,frag:t}),l}).then(l=>{const c=self.performance.now();return i.trigger(x.FRAG_DECRYPTED,{frag:t,payload:l,stats:{tstart:a,tdecrypt:c}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===k.STOPPED||this.state===k.ERROR||(this.warn(s),this.resetFragmentLoading(t));});}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state=k.IDLE,t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick();}fragContextChanged(t){const{fragCurrent:e}=this;return !t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var s,i,n,o;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===W.MAIN?"level":"track"} ${t.level} (frag:[${((s=t.startPTS)!=null?s:NaN).toFixed(3)}-${((i=t.endPTS)!=null?i:NaN).toFixed(3)}] > buffer:${a?Eo.toString(nt.getBuffered(a)):"(detached)"})`),t.sn!=="initSegment"){var l;if(t.type!==W.SUBTITLE){const h=t.elementaryStreams;if(!Object.keys(h).some(u=>!!h[u])){this.state=k.IDLE;return}}const c=(l=this.levels)==null?void 0:l[t.level];c!=null&&c.fragmentError&&(this.log(`Resetting level fragment error count of ${c.fragmentError} on frag buffered`),c.fragmentError=0);}this.state=k.IDLE,a&&(!this.loadedmetadata&&t.type==W.MAIN&&a.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((o=this.fragPrevious)==null?void 0:o.sn)&&(this.loadedmetadata=true,this.seekToStartPos()),this.tick());}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:i,partsLoaded:n}=t,o=!n||n.length===0||n.some(l=>!l),a=new wi(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!o);e.flush(a);}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,i){var n;const o=e?.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let a=null;if(t.encrypted&&!((n=t.decryptdata)!=null&&n.key)?(this.log(`Loading key for ${t.sn} of [${o.startSN}-${o.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${t.level}`),this.state=k.KEY_LOADING,this.fragCurrent=t,a=this.keyLoader.load(t).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(x.KEY_LOADED,h),this.state===k.KEY_LOADING&&(this.state=k.IDLE),h}),this.hls.trigger(x.KEY_LOADING,{frag:t}),this.fragCurrent===null&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!t.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(t,o.encryptedFragments),s=Math.max(t.start,s||0),this.config.lowLatencyMode&&t.sn!=="initSegment"){const h=o.partList;if(h&&i){s>t.end&&o.fragmentHint&&(t=o.fragmentHint);const u=this.getNextPart(h,t,s);if(u>-1){const d=h[u];this.log(`Loading part sn: ${t.sn} p: ${d.index} cc: ${t.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${u}-${h.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=k.FRAG_LOADING;let f;return a?f=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(t,d,e,i)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(t,d,e,i).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(x.FRAG_LOADING,{frag:t,part:d,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!t.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${o?"of ["+o.startSN+"-"+o.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),$(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=k.FRAG_LOADING;const l=this.config.progressive;let c;return l&&a?c=a.then(h=>!h||this.fragContextChanged(h?.frag)?null:this.fragmentLoader.load(t,i)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(t,l?i:void 0),a]).then(([h])=>(!l&&h&&i&&i(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(x.FRAG_LOADING,{frag:t,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(t,e,s,i){return new Promise((n,o)=>{var a;const l=[],c=(a=s.details)==null?void 0:a.partList,h=u=>{this.fragmentLoader.loadPart(t,u,i).then(d=>{l[u.index]=d;const f=d.part;this.hls.trigger(x.FRAG_LOADED,d);const g=ks(s,t.sn,u.index+1)||bi(c,t.sn,u.index+1);if(g)h(g);else return n({frag:t,part:f,partsLoaded:l})}).catch(o);};h(e);})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===w.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(x.ERROR,e);}else this.hls.trigger(x.ERROR,{type:H.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,err:t,error:t,fatal:true});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==k.PARSING){!this.fragCurrent&&this.state!==k.STOPPED&&this.state!==k.ERROR&&(this.state=k.IDLE);return}const{frag:s,part:i,level:n}=e,o=self.performance.now();s.stats.parsing.end=o,i&&(i.stats.parsing.end=o),this.updateLevelTiming(s,i,n,t.partial);}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:n,part:o}=t;if(!(e!=null&&e[i]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${i}. The current chunk will not be buffered.`),null;const a=e[i],l=o>-1?ks(a,n,o):null,c=l?l.fragment:Kr(a,n,s);return c?(s&&s!==c&&(c.stats=s.stats),{frag:c,part:l,level:a}):null}bufferFragmentData(t,e,s,i,n){var o;if(!t||this.state!==k.PARSING)return;const{data1:a,data2:l}=t;let c=a;if(a&&l&&(c=gt(a,l)),!((o=c)!=null&&o.length))return;const h={type:t.type,frag:e,part:s,chunkMeta:i,parent:e.type,data:c};if(this.hls.trigger(x.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s){if(n)return;this.flushBufferGap(e);}}flushBufferGap(t){const e=this.media;if(!e)return;if(!nt.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const s=e.currentTime,i=nt.bufferInfo(e,s,0),n=t.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),a=Math.max(Math.min(t.start-o,i.end-o),s+o);t.start-a>o&&this.flushMainBuffer(a,t.start);}getFwdBufferInfo(t,e){const s=this.getLoadPosition();return $(s)?this.getFwdBufferInfoAtPos(t,s,e):null}getFwdBufferInfoAtPos(t,e,s){const{config:{maxBufferHole:i}}=this,n=nt.bufferInfo(t,e,i);if(n.len===0&&n.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(e,s);if(o&&n.nextStart<o.end)return nt.bufferInfo(t,e,Math.max(n.nextStart,i))}return n}getMaxBufferLength(t){const{config:e}=this;let s;return t?s=Math.max(8*e.maxBufferSize/t,e.maxBufferLength):s=e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e),n=Math.max(t-e*3,s.maxMaxBufferLength/2,i);return n>=i?(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),true):false}getAppendedFrag(t,e=W.MAIN){const s=this.fragmentTracker.getAppendedFrag(t,W.MAIN);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:n}=this,o=s[0].start;let a;if(e.live){const l=n.initialLiveManifestSize;if(i<l)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${l})`),null;(!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<o)&&(a=this.getInitialLiveFragment(e,s),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:t);}else t<=o&&(a=s[0]);if(!a){const l=n.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,l,e);}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return (s===xt.OK||s===xt.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,i,n){const o=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(a===null)return a;if(t=a,o&&t&&!t.gap&&s.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i);if(l!==null&&s.len+l.len>=n)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!(t!=null&&t.initSegment.data)&&!this.bitrateTest?t.initSegment:t}getNextPart(t,e,s){let i=-1,n=false,o=true;for(let a=0,l=t.length;a<l;a++){const c=t[a];if(o=o&&!c.independent,i>-1&&s<c.start)break;const h=c.loaded;h?i=-1:(n||c.independent||o)&&c.fragment===e&&(i=a),n=h;}return i}loadedEndOfParts(t,e){const s=t[t.length-1];return s&&e>s.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Wr(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const n=s.sn+1;if(n>=t.startSN&&n<=t.endSN){const o=e[n-t.startSN];s.cc===o.cc&&(i=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`));}i||(i=qr(e,s.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`));}}else {const n=this.hls.liveSyncPosition;n!==null&&(i=this.getFragmentAtPosition(n,this.bitrateTest?t.fragmentEnd:t.edge,t));}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:n}=this,{fragments:o,endSN:a}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:c}=i,h=s.partList,u=!!(i.lowLatencyMode&&h!=null&&h.length&&l);u&&l&&!this.bitrateTest&&(o=o.concat(l),a=l.sn);let d;if(t<e){const f=t>e-c?0:c;d=ve(n,o,t,f);}else d=o[o.length-1];if(d){const f=d.sn-s.startSN,g=this.fragmentTracker.getState(d);if((g===xt.OK||g===xt.PARTIAL&&d.gap)&&(n=d),n&&d.sn===n.sn&&(!u||h[0].fragment.sn>d.sn)&&n&&d.level===n.level){const p=o[f+1];d.sn<a&&this.fragmentTracker.getState(p)!==xt.OK?d=p:d=null;}}return d}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,n=s.currentTime,o=t.fragments[0].start,a=t.edge,l=n>=o-e.maxFragLookUpTolerance&&n<=a;if(i!==null&&s.duration>i&&(n<i||!l)){const c=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!l&&s.readyState<4||n<a-c)&&(this.loadedmetadata||(this.nextLoadPosition=i),s.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),s.currentTime=i));}}alignPlaylists(t,e,s){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const n=t.fragments[0].start,o=!e,a=t.alignedSliding&&$(n);if(o||!a&&!n){const{fragPrevious:l}=this;fo(l,s,t);const c=t.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${i}`),c}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,e){let s=this.startPosition;if(s<e&&(s=-1),s===-1||this.lastCurrentTime===-1){const i=this.startTimeOffset!==null,n=i?this.startTimeOffset:t.startTimeOffset;n!==null&&$(n)?(s=e+n,n<0&&(s+=t.totalduration),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Start time offset ${n} found in ${i?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):t.live?s=this.hls.liveSyncPosition||e:this.startPosition=s=0,this.lastCurrentTime=s;}this.nextLoadPosition=s;}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&t.sn!=="initSegment"&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t));}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==k.FRAG_LOADING_WAITING_RETRY)&&(this.state=k.IDLE);}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const h=this.getCurrentContext(e.chunkMeta);h&&(e.frag=h.frag);}const s=e.frag;if(!s||s.type!==t||!this.levels)return;if(this.fragContextChanged(s)){var i;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const n=e.details===w.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,true);const o=e.errorAction,{action:a,retryCount:l=0,retryConfig:c}=o||{};if(o&&a===rt.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const h=os(c,l);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${h}ms`),o.resolved=true,this.retryDate=self.performance.now()+h,this.state=k.FRAG_LOADING_WAITING_RETRY;}else if(c&&o)if(this.resetFragmentErrors(t),l<c.maxNumRetry)!n&&a!==rt.RemoveAlternatePermanently&&(o.resolved=true);else {b.warn(`${e.details} reached or exceeded max retry (${l})`);return}else o?.action===rt.SendAlternateToPenaltyBox?this.state=k.WAITING_LEVEL:this.state=k.ERROR;this.tickImmediate();}reduceLengthAndFlushBuffer(t){if(this.state===k.PARSING||this.state===k.PARSED){const e=t.frag,s=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,e?.duration||10);const o=!n;return o&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),o}return  false}resetFragmentErrors(t){t===W.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=false),this.state!==k.STOPPED&&(this.state=k.IDLE);}afterBufferFlushed(t,e,s){if(!t)return;const i=nt.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,s),this.state===k.ENDED&&this.resetLoadingState();}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=k.IDLE;}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=false;const e=t?t.details:null;e!=null&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition;}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState();}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,false,true);}updateLevelTiming(t,e,s,i){var n;const o=s.details;if(!o){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((l,c)=>{const h=t.elementaryStreams[c];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${t.sn} ${c} duration reliably (${u})`),l||false;const d=i?0:vi(o,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(x.LEVEL_PTS_UPDATED,{details:o,level:s,drift:d,type:c,frag:t,start:h.startPTS,end:h.endPTS}),true}return l},false)&&((n=this.transmuxer)==null?void 0:n.error)===null){const l=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(s.fragmentError===0&&(s.fragmentError++,t.gap=true,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,true)),this.warn(l.message),this.hls.trigger(x.ERROR,{type:H.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:false,error:l,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer();}this.state=k.PARSED,this.hls.trigger(x.FRAG_PARSED,{frag:t,part:e});}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null);}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState());}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`));}get state(){return this._state}}class vo{constructor(){this.chunks=[],this.dataLength=0;}push(t){this.chunks.push(t),this.dataLength+=t.length;}flush(){const{chunks:t,dataLength:e}=this;let s;if(t.length)t.length===1?s=t[0]:s=Ao(t,e);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0;}}function Ao(r,t){const e=new Uint8Array(t);let s=0;for(let i=0;i<r.length;i++){const n=r[i];e.set(n,s),s+=n.length;}return e}function bo(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Ro(){const r=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(r);return {worker:new self.Worker(t),objectURL:t}}function Lo(r){const t=new self.URL(r,self.location.href).href;return {worker:new self.Worker(t),scriptURL:t}}function Et(r="",t=9e4){return {type:r,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class ls{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(t,e,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0};}resetTimeStamp(t){this.initPTS=t,this.resetContiguity();}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0;}canParse(t,e){return  false}appendFrame(t,e,s){}demux(t,e){this.cachedData&&(t=gt(this.cachedData,t),this.cachedData=null);let s=jt(t,0),i=s?s.length:0,n;const o=this._audioTrack,a=this._id3Track,l=s?rs(s):void 0,c=t.length;for((this.basePTS===null||this.frameIndex===0&&$(l))&&(this.basePTS=Io(l,e,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Xt.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(t,i)){const h=this.appendFrame(o,t,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,n=i):i=c;}else er(t,i)?(s=jt(t,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Xt.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,n=i):i++;if(i===c&&n!==c){const h=Ft(t,n);this.cachedData?this.cachedData=gt(this.cachedData,h):this.cachedData=h;}}return {audioTrack:o,videoTrack:Et(),id3Track:a,textTrack:Et()}}demuxSampleAes(t,e,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Et(),id3Track:this._id3Track,textTrack:Et()}}destroy(){}}const Io=(r,t,e)=>{if($(r))return r*90;const s=e?e.baseTime*9e4/e.timescale:0;return t*9e4+s};function wo(r,t,e,s){let i,n,o,a;const l=navigator.userAgent.toLowerCase(),c=s,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((t[e+2]&192)>>>6)+1;const u=(t[e+2]&60)>>>2;if(u>h.length-1){const d=new Error(`invalid ADTS sampling index:${u}`);r.emit(x.ERROR,x.ERROR,{type:H.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:true,error:d,reason:d.message});return}return o=(t[e+2]&1)<<2,o|=(t[e+3]&192)>>>6,b.log(`manifest codec:${s}, ADTS type:${i}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(i=5,a=new Array(4),n=u-3):(i=2,a=new Array(2),n=u):l.indexOf("android")!==-1?(i=2,a=new Array(2),n=u):(i=5,a=new Array(4),s&&(s.indexOf("mp4a.40.29")!==-1||s.indexOf("mp4a.40.5")!==-1)||!s&&u>=6?n=u-3:((s&&s.indexOf("mp4a.40.2")!==-1&&(u>=6&&o===1||/vivaldi/i.test(l))||!s&&o===1)&&(i=2,a=new Array(2)),n=u)),a[0]=i<<3,a[0]|=(u&14)>>1,a[1]|=(u&1)<<7,a[1]|=o<<3,i===5&&(a[1]|=(n&14)>>1,a[2]=(n&1)<<7,a[2]|=8,a[3]=0),{config:a,samplerate:h[u],channelCount:o,codec:"mp4a.40."+i,manifestCodec:c}}function _i(r,t){return r[t]===255&&(r[t+1]&246)===240}function ki(r,t){return r[t+1]&1?7:9}function cs(r,t){return (r[t+3]&3)<<11|r[t+4]<<3|(r[t+5]&224)>>>5}function Do(r,t){return t+5<r.length}function be(r,t){return t+1<r.length&&_i(r,t)}function Co(r,t){return Do(r,t)&&_i(r,t)&&cs(r,t)<=r.length-t}function _o(r,t){if(be(r,t)){const e=ki(r,t);if(t+e>=r.length)return  false;const s=cs(r,t);if(s<=e)return  false;const i=t+s;return i===r.length||be(r,i)}return  false}function Pi(r,t,e,s,i){if(!r.samplerate){const n=wo(t,e,s,i);if(!n)return;r.config=n.config,r.samplerate=n.samplerate,r.channelCount=n.channelCount,r.codec=n.codec,r.manifestCodec=n.manifestCodec,b.log(`parsed codec:${r.codec}, rate:${n.samplerate}, channels:${n.channelCount}`);}}function Fi(r){return 1024*9e4/r}function ko(r,t){const e=ki(r,t);if(t+e<=r.length){const s=cs(r,t)-e;if(s>0)return {headerLength:e,frameLength:s}}}function Oi(r,t,e,s,i){const n=Fi(r.samplerate),o=s+i*n,a=ko(t,e);let l;if(a){const{frameLength:u,headerLength:d}=a,f=d+u,g=Math.max(0,e+f-t.length);g?(l=new Uint8Array(f-d),l.set(t.subarray(e+d,t.length),0)):l=t.subarray(e+d,e+f);const m={unit:l,pts:o};return g||r.samples.push(m),{sample:m,length:f,missing:g}}const c=t.length-e;return l=new Uint8Array(c),l.set(t.subarray(e,t.length),0),{sample:{unit:l,pts:o},length:c,missing:-1}}let se=null;const Po=[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],Fo=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Oo=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Mo=[0,1,1,4];function Mi(r,t,e,s,i){if(e+24>t.length)return;const n=Ni(t,e);if(n&&e+n.frameLength<=t.length){const o=n.samplesPerFrame*9e4/n.sampleRate,a=s+i*o,l={unit:t.subarray(e,e+n.frameLength),pts:a,dts:a};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Ni(r,t){const e=r[t+1]>>3&3,s=r[t+1]>>1&3,i=r[t+2]>>4&15,n=r[t+2]>>2&3;if(e!==1&&i!==0&&i!==15&&n!==3){const o=r[t+2]>>1&1,a=r[t+3]>>6,l=e===3?3-s:s===3?3:4,c=Po[l*14+i-1]*1e3,u=Fo[(e===3?0:e===2?1:2)*3+n],d=a===3?1:2,f=Oo[e][s],g=Mo[s],m=f*8*g,p=Math.floor(f*c/u+o)*g;if(se===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);se=T?parseInt(T[1]):0;}return se&&se<=87&&s===2&&c>=224e3&&a===0&&(r[t+3]=r[t+3]|128),{sampleRate:u,channelCount:d,frameLength:p,samplesPerFrame:m}}}function hs(r,t){return r[t]===255&&(r[t+1]&224)===224&&(r[t+1]&6)!==0}function Ui(r,t){return t+1<r.length&&hs(r,t)}function No(r,t){return hs(r,t)&&4<=r.length-t}function Bi(r,t){if(t+1<r.length&&hs(r,t)){const s=Ni(r,t);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const n=t+i;return n===r.length||Ui(r,n)}return  false}class Uo extends ls{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e;}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0};}static probe(t){if(!t)return  false;const e=jt(t,0);let s=e?.length||0;if(Bi(t,s))return  false;for(let i=t.length;s<i;s++)if(_o(t,s))return b.log("ADTS sync word found !"),true;return  false}canParse(t,e){return Co(t,e)}appendFrame(t,e,s){Pi(t,this.observer,e,s,t.manifestCodec);const i=Oi(t,e,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const Bo=/\/emsg[-/]ID3/i;class $o{constructor(t,e){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=e;}resetTimeStamp(){}resetInitSegment(t,e,s,i){const n=this.videoTrack=Et("video",1),o=this.audioTrack=Et("audio",1),a=this.txtTrack=Et("text",1);if(this.id3Track=Et("id3",1),this.timeOffset=0,!(t!=null&&t.byteLength))return;const l=xi(t);if(l.video){const{id:c,timescale:h,codec:u}=l.video;n.id=c,n.timescale=a.timescale=h,n.codec=u;}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;o.id=c,o.timescale=h,o.codec=u;}a.id=gi.text,n.sampleDuration=0,n.duration=o.duration=i;}resetContiguity(){this.remainderData=null;}static probe(t){return dr(t)}demux(t,e){this.timeOffset=e;let s=t;const i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=gt(this.remainderData,t));const a=Sr(s);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array;}else i.samples=s;const o=this.extractID3Track(i,e);return n.samples=As(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return s.samples=As(t,e),{videoTrack:e,audioTrack:Et(),id3Track:i,textTrack:Et()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=K(t.samples,["emsg"]);i&&i.forEach(n=>{const o=Ar(n);if(Bo.test(o.schemeIdUri)){const a=$(o.presentationTime)?o.presentationTime/o.timeScale:e+o.presentationTimeDelta/o.timeScale;let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=o.payload;s.samples.push({data:c,len:c.byteLength,dts:a,pts:a,type:Xt.emsg,duration:l});}});}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const $i=(r,t)=>{let e=0,s=5;t+=s;const i=new Uint32Array(1),n=new Uint32Array(1),o=new Uint8Array(1);for(;s>0;){o[0]=r[t];const a=Math.min(s,8),l=8-a;n[0]=4278190080>>>24+l<<l,i[0]=(o[0]&n[0])>>l,e=e?e<<a|i[0]:i[0],t+=1,s-=a;}return e};class Go extends ls{constructor(t){super(),this.observer=void 0,this.observer=t;}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0};}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const i=Gi(t,e,s,this.basePTS,this.frameIndex);if(i!==-1)return {sample:t.samples[t.samples.length-1],length:i,missing:0}}static probe(t){if(!t)return  false;const e=jt(t,0);if(!e)return  false;const s=e.length;return t[s]===11&&t[s+1]===119&&rs(e)!==void 0&&$i(t,s)<16}}function Gi(r,t,e,s,i){if(e+8>t.length||t[e]!==11||t[e+1]!==119)return  -1;const n=t[e+4]>>6;if(n>=3)return  -1;const a=[48e3,44100,32e3][n],l=t[e+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(e+h>t.length)return  -1;const u=t[e+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(t[e+6]<<8|t[e+7])>>12-d&1,m=[2,1,2,3,3,4,4,5][u]+f,p=t[e+5]>>3,y=t[e+5]&7,A=new Uint8Array([n<<6|p<<1|y>>2,(y&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),T=1536/a*9e4,R=s+i*T,E=t.subarray(e,e+h);return r.config=A,r.channelCount=m,r.samplerate=a,r.samples.push({unit:E,pts:R}),h}class Ko{constructor(){this.VideoSample=null;}createVideoSample(t,e,s,i){return {key:t,frame:false,pts:e,dts:s,units:[],debug:i,length:0}}getLastNalUnit(t){var e;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=t[t.length-1]),(e=s)!=null&&e.units){const n=s.units;i=n[n.length-1];}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(t.pts===void 0){const s=e.samples,i=s.length;if(i){const n=s[i-1];t.pts=n.pts,t.dts=n.dts;}else {e.dropped++;return}}e.samples.push(t);}t.debug.length&&b.log(t.pts+"/"+t.dts+":"+t.debug);}}class Gs{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0;}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,i=new Uint8Array(4),n=Math.min(4,e);if(n===0)throw new Error("no bytes available");i.set(t.subarray(s,s+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n;}skipBits(t){let e;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,e=t>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t);}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return e=t-e,e>0&&this.bitsAvailable?s<<e|this.readBits(e):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if((this.word&2147483648>>>t)!==0)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ());}skipEG(){this.skipBits(1+this.skipLZ());}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e=8,s=8,i;for(let n=0;n<t;n++)s!==0&&(i=this.readEG(),s=(e+i+256)%256),e=s===0?e:s;}readSPS(){let t=0,e=0,s=0,i=0,n,o,a;const l=this.readUByte.bind(this),c=this.readBits.bind(this),h=this.readUEG.bind(this),u=this.readBoolean.bind(this),d=this.skipBits.bind(this),f=this.skipEG.bind(this),g=this.skipUEG.bind(this),m=this.skipScalingList.bind(this);l();const p=l();if(c(5),d(3),l(),g(),p===100||p===110||p===122||p===244||p===44||p===83||p===86||p===118||p===128){const I=h();if(I===3&&d(1),g(),g(),d(1),u())for(o=I!==3?8:12,a=0;a<o;a++)u()&&(a<6?m(16):m(64));}g();const y=h();if(y===0)h();else if(y===1)for(d(1),f(),f(),n=h(),a=0;a<n;a++)f();g(),d(1);const A=h(),T=h(),R=c(1);R===0&&d(1),d(1),u()&&(t=h(),e=h(),s=h(),i=h());let E=[1,1];if(u()&&u())switch(l()){case 1:E=[1,1];break;case 2:E=[12,11];break;case 3:E=[10,11];break;case 4:E=[16,11];break;case 5:E=[40,33];break;case 6:E=[24,11];break;case 7:E=[20,11];break;case 8:E=[32,11];break;case 9:E=[80,33];break;case 10:E=[18,11];break;case 11:E=[15,11];break;case 12:E=[64,33];break;case 13:E=[160,99];break;case 14:E=[4,3];break;case 15:E=[3,2];break;case 16:E=[2,1];break;case 255:{E=[l()<<8|l(),l()<<8|l()];break}}return {width:Math.ceil((A+1)*16-t*2-e*2),height:(2-R)*(T+1)*16-(R?2:4)*(s+i),pixelRatio:E}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Vo extends Ko{parseAVCPES(t,e,s,i,n){const o=this.parseAVCNALu(t,s.data);let a=this.VideoSample,l,c=false;s.data=null,a&&o.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(false,s.pts,s.dts,"")),o.forEach(h=>{var u;switch(h.type){case 1:{let m=false;l=true;const p=h.data;if(c&&p.length>4){const y=new Gs(p).readSliceType();(y===2||y===4||y===7||y===9)&&(m=true);}if(m){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);}a||(a=this.VideoSample=this.createVideoSample(true,s.pts,s.dts,"")),a.frame=true,a.key=m;break}case 5:l=true,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(true,s.pts,s.dts,"")),a.key=true,a.frame=true;break;case 6:{l=true,Ti(h.data,1,s.pts,e.samples);break}case 7:{var f,g;l=true,c=true;const m=h.data,y=new Gs(m).readSPS();if(!t.sps||t.width!==y.width||t.height!==y.height||((f=t.pixelRatio)==null?void 0:f[0])!==y.pixelRatio[0]||((g=t.pixelRatio)==null?void 0:g[1])!==y.pixelRatio[1]){t.width=y.width,t.height=y.height,t.pixelRatio=y.pixelRatio,t.sps=[m],t.duration=n;const A=m.subarray(1,4);let T="avc1.";for(let R=0;R<3;R++){let E=A[R].toString(16);E.length<2&&(E="0"+E),T+=E;}t.codec=T;}break}case 8:l=true,t.pps=[h.data];break;case 9:l=true,t.audFound=true,a&&this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(false,s.pts,s.dts,"");break;case 12:l=true;break;default:l=false,a&&(a.debug+="unknown NAL "+h.type+" ");break}a&&l&&a.units.push(h);}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null);}parseAVCNALu(t,e){const s=e.byteLength;let i=t.naluState||0;const n=i,o=[];let a=0,l,c,h,u=-1,d=0;for(i===-1&&(u=0,d=e[0]&31,i=0,a=1);a<s;){if(l=e[a++],!i){i=l?0:1;continue}if(i===1){i=l?0:2;continue}if(!l)i=3;else if(l===1){if(c=a-i-1,u>=0){const f={data:e.subarray(u,c),type:d};o.push(f);}else {const f=this.getLastNalUnit(t.samples);f&&(n&&a<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),c>0&&(f.data=gt(f.data,e.subarray(0,c)),f.state=0));}a<s?(h=e[a]&31,u=a,d=h,i=0):i=-1;}else i=0;}if(u>=0&&i>=0){const f={data:e.subarray(u,s),type:d,state:i};o.push(f);}if(o.length===0){const f=this.getLastNalUnit(t.samples);f&&(f.data=gt(f.data,e));}return t.naluState=i,o}}class Ho{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new as(e,{removePKCS7Padding:false});}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const n=i.subarray(16,i.length-i.length%16),o=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s);});}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length){s();return}if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=Math.floor((t.length-48)/160)*16+16,s=new Int8Array(e);let i=0;for(let n=32;n<t.length-16;n+=160,i+=16)s.set(t.subarray(n,n+16),i);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let i=0;for(let n=32;n<t.length-16;n+=160,i+=16)t.set(s.subarray(i,i+16),n);return t}decryptAvcSample(t,e,s,i,n){const o=Si(n.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i);});}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length){i();return}const n=t[e].units;for(;!(s>=n.length);s++){const o=n[s];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(t,e,s,i,o),!this.decrypter.isSync()))return}}}}const it=188;class _t{constructor(t,e,s){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=false,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=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=t,this.config=e,this.typeSupported=s,this.videoParser=new Vo;}static probe(t){const e=_t.syncOffset(t);return e>0&&b.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),e!==-1}static syncOffset(t){const e=t.length;let s=Math.min(it*5,e-it)+1,i=0;for(;i<s;){let n=false,o=-1,a=0;for(let l=i;l<e;l+=it)if(t[l]===71&&(e-l===it||t[l+it]===71)){if(a++,o===-1&&(o=l,o!==0&&(s=Math.min(o+it*99,t.length-it)+1)),n||(n=je(t,l)===0),n&&a>1&&(o===0&&a>2||l+it>s))return o}else {if(a)return  -1;break}i++;}return  -1}static createTrack(t,e){return {container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:gi[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?e:void 0}}resetInitSegment(t,e,s,i){this.pmtParsed=false,this._pmtId=-1,this._videoTrack=_t.createTrack("video"),this._audioTrack=_t.createTrack("audio",i),this._id3Track=_t.createTrack("id3"),this._txtTrack=_t.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=i;}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null;}demux(t,e,s=false,i=false){s||(this.sampleAes=null);let n;const o=this._videoTrack,a=this._audioTrack,l=this._id3Track,c=this._txtTrack;let h=o.pid,u=o.pesData,d=a.pid,f=l.pid,g=a.pesData,m=l.pesData,p=null,y=this.pmtParsed,A=this._pmtId,T=t.length;if(this.remainderData&&(t=gt(this.remainderData,t),T=t.length,this.remainderData=null),T<it&&!i)return this.remainderData=t,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};const R=Math.max(0,_t.syncOffset(t));T-=(T-R)%it,T<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,T,t.buffer.byteLength-T));let E=0;for(let v=R;v<T;v+=it)if(t[v]===71){const C=!!(t[v+1]&64),P=je(t,v),L=(t[v+3]&48)>>4;let _;if(L>1){if(_=v+5+t[v+4],_===v+it)continue}else _=v+4;switch(P){case h:C&&(u&&(n=Ut(u))&&this.videoParser.parseAVCPES(o,c,n,false,this._duration),u={data:[],size:0}),u&&(u.data.push(t.subarray(_,v+it)),u.size+=v+it-_);break;case d:if(C){if(g&&(n=Ut(g)))switch(a.segmentCodec){case "aac":this.parseAACPES(a,n);break;case "mp3":this.parseMPEGPES(a,n);break;case "ac3":this.parseAC3PES(a,n);break}g={data:[],size:0};}g&&(g.data.push(t.subarray(_,v+it)),g.size+=v+it-_);break;case f:C&&(m&&(n=Ut(m))&&this.parseID3PES(l,n),m={data:[],size:0}),m&&(m.data.push(t.subarray(_,v+it)),m.size+=v+it-_);break;case 0:C&&(_+=t[_]+1),A=this._pmtId=Wo(t,_);break;case A:{C&&(_+=t[_]+1);const D=Yo(t,_,this.typeSupported,s,this.observer);h=D.videoPid,h>0&&(o.pid=h,o.segmentCodec=D.segmentVideoCodec),d=D.audioPid,d>0&&(a.pid=d,a.segmentCodec=D.segmentAudioCodec),f=D.id3Pid,f>0&&(l.pid=f),p!==null&&!y&&(b.warn(`MPEG-TS PMT found at ${v} after unknown PID '${p}'. Backtracking to sync byte @${R} to parse all TS packets.`),p=null,v=R-188),y=this.pmtParsed=true;break}case 17:case 8191:break;default:p=P;break}}else E++;E>0&&Re(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`)),o.pesData=u,a.pesData=g,l.pesData=m;const I={audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};return i&&this.extractRemainingSamples(I),I}flush(){const{remainderData:t}=this;this.remainderData=null;let e;return t?e=this.demux(t,-1,false,true):e={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:s,id3Track:i,textTrack:n}=t,o=s.pesData,a=e.pesData,l=i.pesData;let c;if(o&&(c=Ut(o))?(this.videoParser.parseAVCPES(s,n,c,true,this._duration),s.pesData=null):s.pesData=o,a&&(c=Ut(a))){switch(e.segmentCodec){case "aac":this.parseAACPES(e,c);break;case "mp3":this.parseMPEGPES(e,c);break;case "ac3":this.parseAC3PES(e,c);break}e.pesData=null;}else a!=null&&a.size&&b.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;l&&(c=Ut(l))?(this.parseID3PES(i,c),i.pesData=null):i.pesData=l;}demuxSampleAes(t,e,s){const i=this.demux(t,s,true,!this.config.progressive),n=this.sampleAes=new Ho(this.observer,this.config,e);return this.decrypt(i,n)}decrypt(t,e){return new Promise(s=>{const{audioTrack:i,videoTrack:n}=t;i.samples&&i.segmentCodec==="aac"?e.decryptAacSamples(i.samples,0,()=>{n.samples?e.decryptAvcSamples(n.samples,0,0,()=>{s(t);}):s(t);}):n.samples&&e.decryptAvcSamples(n.samples,0,0,()=>{s(t);});})}destroy(){this._duration=0;}parseAACPES(t,e){let s=0;const i=this.aacOverFlow;let n=e.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)n=gt(i.sample.unit,n);else {const f=d-u;i.sample.unit.set(n.subarray(0,u),f),t.samples.push(i.sample),s=i.missing;}}let o,a;for(o=s,a=n.length;o<a-1&&!be(n,o);o++);if(o!==s){let u;const d=o<a-1;if(d?u=`AAC PES did not start with ADTS header,offset:${o}`:u="No ADTS header found in AAC PES",Re(this.observer,new Error(u),d),!d)return}Pi(t,this.observer,n,o,this.audioCodec);let l;if(e.pts!==void 0)l=e.pts;else if(i){const u=Fi(t.samplerate);l=i.sample.pts+u;}else {b.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;o<a;)if(h=Oi(t,n,o,l,c),o+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;o<a-1&&!be(n,o);o++);}parseMPEGPES(t,e){const s=e.data,i=s.length;let n=0,o=0;const a=e.pts;if(a===void 0){b.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<i;)if(Ui(s,o)){const l=Mi(t,s,o,a,n);if(l)o+=l.length,n++;else break}else o++;}parseAC3PES(t,e){{const s=e.data,i=e.pts;if(i===void 0){b.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=s.length;let o=0,a=0,l;for(;a<n&&(l=Gi(t,s,a,i,o++))>0;)a+=l;}}parseID3PES(t,e){if(e.pts===void 0){b.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ct({},e,{type:this._videoTrack?Xt.emsg:Xt.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s);}}function je(r,t){return ((r[t+1]&31)<<8)+r[t+2]}function Wo(r,t){return (r[t+10]&31)<<8|r[t+11]}function Yo(r,t,e,s,i){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(r[t+1]&15)<<8|r[t+2],a=t+3+o-4,l=(r[t+10]&15)<<8|r[t+11];for(t+=12+l;t<a;){const c=je(r,t),h=(r[t+3]&15)<<8|r[t+4];switch(r[t]){case 207:if(!s){Pe("ADTS AAC");break}case 15:n.audioPid===-1&&(n.audioPid=c);break;case 21:n.id3Pid===-1&&(n.id3Pid=c);break;case 219:if(!s){Pe("H.264");break}case 27:n.videoPid===-1&&(n.videoPid=c,n.segmentVideoCodec="avc");break;case 3:case 4:!e.mpeg&&!e.mp3?b.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=c,n.segmentAudioCodec="mp3");break;case 193:if(!s){Pe("AC-3");break}case 129:e.ac3?n.audioPid===-1&&(n.audioPid=c,n.segmentAudioCodec="ac3"):b.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&h>0){let u=t+5,d=h;for(;d>2;){r[u]===106&&(e.ac3!==true?b.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=c,n.segmentAudioCodec="ac3"));const g=r[u+1]+2;u+=g,d-=g;}}break;case 194:case 135:return Re(i,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return Re(i,new Error("Unsupported HEVC in M2TS found")),n}t+=h+5;}return n}function Re(r,t,e){b.warn(`parsing error: ${t.message}`),r.emit(x.ERROR,x.ERROR,{type:H.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:false,levelRetry:e,error:t,reason:t.message});}function Pe(r){b.log(`${r} with AES-128-CBC encryption found in unencrypted stream`);}function Ut(r){let t=0,e,s,i,n,o;const a=r.data;if(!r||r.size===0)return null;for(;a[0].length<19&&a.length>1;)a[0]=gt(a[0],a[1]),a.splice(1,1);if(e=a[0],(e[0]<<16)+(e[1]<<8)+e[2]===1){if(s=(e[4]<<8)+e[5],s&&s>r.size-6)return null;const c=e[7];c&192&&(n=(e[9]&14)*536870912+(e[10]&255)*4194304+(e[11]&254)*16384+(e[12]&255)*128+(e[13]&254)/2,c&64?(o=(e[14]&14)*536870912+(e[15]&255)*4194304+(e[16]&254)*16384+(e[17]&255)*128+(e[18]&254)/2,n-o>60*9e4&&(b.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),i=e[8];let h=i+9;if(r.size<=h)return null;r.size-=h;const u=new Uint8Array(r.size);for(let d=0,f=a.length;d<f;d++){e=a[d];let g=e.byteLength;if(h)if(h>g){h-=g;continue}else e=e.subarray(h),g-=h,h=0;u.set(e,t),t+=g;}return s&&(s-=i+3),{data:u,pts:n,dts:o,len:s}}return null}class zo extends ls{resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0};}static probe(t){if(!t)return  false;const e=jt(t,0);let s=e?.length||0;if(e&&t[s]===11&&t[s+1]===119&&rs(e)!==void 0&&$i(t,s)<=16)return  false;for(let i=t.length;s<i;s++)if(Bi(t,s))return b.log("MPEG Audio sync word found !"),true;return  false}canParse(t,e){return No(t,e)}appendFrame(t,e,s){if(this.basePTS!==null)return Mi(t,e,s,this.basePTS,this.frameIndex)}}class Ks{static getSilentFrame(t,e){switch(t){case "mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(e===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(e===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(e===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(e===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(e===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 Dt=Math.pow(2,32)-1;class S{static init(){S.types={avc1:[],avcC:[],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 t;for(t in S.types)S.types.hasOwnProperty(t)&&(S.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]);S.HDLR_TYPES={video:e,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]),n=new Uint8Array([0,0,0,0,0,0,0,0]);S.STTS=S.STSC=S.STCO=n,S.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),S.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),S.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),S.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);S.FTYP=S.box(S.types.ftyp,o,l,o,a),S.DINF=S.box(S.types.dinf,S.box(S.types.dref,i));}static box(t,...e){let s=8,i=e.length;const n=i;for(;i--;)s+=e[i].byteLength;const o=new Uint8Array(s);for(o[0]=s>>24&255,o[1]=s>>16&255,o[2]=s>>8&255,o[3]=s&255,o.set(t,4),i=0,s=8;i<n;i++)o.set(e[i],s),s+=e[i].byteLength;return o}static hdlr(t){return S.box(S.types.hdlr,S.HDLR_TYPES[t])}static mdat(t){return S.box(S.types.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(Dt+1)),i=Math.floor(e%(Dt+1));return S.box(S.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&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(t){return S.box(S.types.mdia,S.mdhd(t.timescale,t.duration),S.hdlr(t.type),S.minf(t))}static mfhd(t){return S.box(S.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?S.box(S.types.minf,S.box(S.types.smhd,S.SMHD),S.DINF,S.stbl(t)):S.box(S.types.minf,S.box(S.types.vmhd,S.VMHD),S.DINF,S.stbl(t))}static moof(t,e,s){return S.box(S.types.moof,S.mfhd(t),S.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=S.trak(t[e]);return S.box.apply(null,[S.types.moov,S.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(S.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=S.trex(t[e]);return S.box.apply(null,[S.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(Dt+1)),i=Math.floor(e%(Dt+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&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 S.box(S.types.mvhd,n)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,n;for(i=0;i<e.length;i++)n=e[i].flags,s[i+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return S.box(S.types.sdtp,s)}static stbl(t){return S.box(S.types.stbl,S.stsd(t),S.box(S.types.stts,S.STTS),S.box(S.types.stsc,S.STSC),S.box(S.types.stsz,S.STSZ),S.box(S.types.stco,S.STCO))}static avc1(t){let e=[],s=[],i,n,o;for(i=0;i<t.sps.length;i++)n=t.sps[i],o=n.byteLength,e.push(o>>>8&255),e.push(o&255),e=e.concat(Array.prototype.slice.call(n));for(i=0;i<t.pps.length;i++)n=t.pps[i],o=n.byteLength,s.push(o>>>8&255),s.push(o&255),s=s.concat(Array.prototype.slice.call(n));const a=S.box(S.types.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(s))),l=t.width,c=t.height,h=t.pixelRatio[0],u=t.pixelRatio[1];return S.box(S.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&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]),a,S.box(S.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),S.box(S.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,e&255,0,0])}static mp4a(t){return S.box(S.types.mp4a,S.audioStsd(t),S.box(S.types.esds,S.esds(t)))}static mp3(t){return S.box(S.types[".mp3"],S.audioStsd(t))}static ac3(t){return S.box(S.types["ac-3"],S.audioStsd(t),S.box(S.types.dac3,t.config))}static stsd(t){return t.type==="audio"?t.segmentCodec==="mp3"&&t.codec==="mp3"?S.box(S.types.stsd,S.STSD,S.mp3(t)):t.segmentCodec==="ac3"?S.box(S.types.stsd,S.STSD,S.ac3(t)):S.box(S.types.stsd,S.STSD,S.mp4a(t)):S.box(S.types.stsd,S.STSD,S.avc1(t))}static tkhd(t){const e=t.id,s=t.duration*t.timescale,i=t.width,n=t.height,o=Math.floor(s/(Dt+1)),a=Math.floor(s%(Dt+1));return S.box(S.types.tkhd,new Uint8Array([1,0,0,7,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,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,a>>24,a>>16&255,a>>8&255,a&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,n>>8&255,n&255,0,0]))}static traf(t,e){const s=S.sdtp(t),i=t.id,n=Math.floor(e/(Dt+1)),o=Math.floor(e%(Dt+1));return S.box(S.types.traf,S.box(S.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),S.box(S.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255])),S.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,S.box(S.types.trak,S.tkhd(t),S.mdia(t))}static trex(t){const e=t.id;return S.box(S.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const s=t.samples||[],i=s.length,n=12+16*i,o=new Uint8Array(n);let a,l,c,h,u,d;for(e+=8+n,o.set([t.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0),a=0;a<i;a++)l=s[a],c=l.duration,h=l.size,u=l.flags,d=l.cts,o.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*a);return S.box(S.types.trun,o)}static initSegment(t){S.types||S.init();const e=S.moov(t);return gt(S.FTYP,e)}}S.types=void 0;S.HDLR_TYPES=void 0;S.STTS=void 0;S.STSC=void 0;S.STCO=void 0;S.STSZ=void 0;S.VMHD=void 0;S.SMHD=void 0;S.STSD=void 0;S.FTYP=void 0;S.DINF=void 0;const Ki=9e4;function us(r,t,e=1,s=false){const i=r*t*e;return s?Math.round(i):i}function qo(r,t,e=1,s=false){return us(r,t,1/e,s)}function Yt(r,t=false){return us(r,1e3,1/Ki,t)}function jo(r,t=1){return us(r,Ki,1/t)}const Xo=10*1e3,Vs=1024,Qo=1152,Zo=1536;let Bt=null,Fe=null;class de{constructor(t,e,s,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=false,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=false,this.isVideoContiguous=false,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=false,Bt===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bt=o?parseInt(o[1]):0;}if(Fe===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);Fe=n?parseInt(n[1]):0;}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null;}resetTimeStamp(t){b.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t;}resetNextTimestamp(){b.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=false,this.isAudioContiguous=false;}resetInitSegment(){b.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=false,this.videoTrackConfig=void 0;}getVideoStartPts(t){let e=false;const s=t.reduce((i,n)=>{const o=n.pts-i;return o<-4294967296?(e=true,ft(i,n.pts)):o>0?i:n.pts},t[0].pts);return e&&b.debug("PTS rollover detected"),s}remux(t,e,s,i,n,o,a,l){let c,h,u,d,f,g,m=n,p=n;const y=t.pid>-1,A=e.pid>-1,T=e.samples.length,R=t.samples.length>0,E=a&&T>0||T>1;if((!y||R)&&(!A||E)||this.ISGenerated||a){if(this.ISGenerated){var v,C,P,L;const X=this.videoTrackConfig;X&&(e.width!==X.width||e.height!==X.height||((v=e.pixelRatio)==null?void 0:v[0])!==((C=X.pixelRatio)==null?void 0:C[0])||((P=e.pixelRatio)==null?void 0:P[1])!==((L=X.pixelRatio)==null?void 0:L[1]))&&this.resetInitSegment();}else u=this.generateIS(t,e,n,o);const _=this.isVideoContiguous;let D=-1,q;if(E&&(D=Jo(e.samples),!_&&this.config.forceKeyFrameOnDiscontinuity))if(g=true,D>0){b.warn(`[mp4-remuxer]: Dropped ${D} out of ${T} video samples due to a missing keyframe`);const X=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(D),e.dropped+=D,p+=(e.samples[0].pts-X)/e.inputTimeScale,q=p;}else D===-1&&(b.warn(`[mp4-remuxer]: No keyframe found out of ${T} video samples`),g=false);if(this.ISGenerated){if(R&&E){const X=this.getVideoStartPts(e.samples),B=(ft(t.samples[0].pts,X)-X)/e.inputTimeScale;m+=Math.max(0,B),p+=Math.max(0,-B);}if(R){if(t.samplerate||(b.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(t,e,n,o)),h=this.remuxAudio(t,m,this.isAudioContiguous,o,A||E||l===W.AUDIO?p:void 0),E){const X=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(b.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(t,e,n,o)),c=this.remuxVideo(e,p,_,X);}}else E&&(c=this.remuxVideo(e,p,_,0));c&&(c.firstKeyFrame=D,c.independent=D!==-1,c.firstKeyFramePTS=q);}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Vi(s,n,this._initPTS,this._initDTS)),i.samples.length&&(d=Hi(i,n,this._initPTS))),{audio:h,video:c,initSegment:u,independent:g,text:d,id3:f}}generateIS(t,e,s,i){const n=t.samples,o=e.samples,a=this.typeSupported,l={},c=this._initPTS;let h=!c||i,u="audio/mp4",d,f,g;if(h&&(d=f=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case "mp3":a.mpeg?(u="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case "ac3":t.codec="ac-3";break}l.audio={id:"audio",container:u,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):S.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(g=t.inputTimeScale,!c||g!==c.timescale?d=f=n[0].pts-Math.round(g*s):h=false);}if(e.sps&&e.pps&&o.length){if(e.timescale=e.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:S.initSegment([e]),metadata:{width:e.width,height:e.height}},h)if(g=e.inputTimeScale,!c||g!==c.timescale){const m=this.getVideoStartPts(o),p=Math.round(g*s);f=Math.min(f,ft(o[0].dts,m)-p),d=Math.min(d,m-p);}else h=false;this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio};}if(Object.keys(l).length)return this.ISGenerated=true,h?(this._initPTS={baseTime:d,timescale:g},this._initDTS={baseTime:f,timescale:g}):d=g=void 0,{tracks:l,initPTS:d,timescale:g}}remuxVideo(t,e,s,i){const n=t.inputTimeScale,o=t.samples,a=[],l=o.length,c=this._initPTS;let h=this.nextAvcDts,u=8,d=this.videoSampleDuration,f,g,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,y=false;if(!s||h===null){const O=e*n,F=o[0].pts-ft(o[0].dts,o[0].pts);Bt&&h!==null&&Math.abs(O-F-h)<15e3?s=true:h=O-F;}const A=c.baseTime*n/c.timescale;for(let O=0;O<l;O++){const F=o[O];F.pts=ft(F.pts-A,h),F.dts=ft(F.dts-A,h),F.dts<o[O>0?O-1:O].dts&&(y=true);}y&&o.sort(function(O,F){const Y=O.dts-F.dts,G=O.pts-F.pts;return Y||G}),f=o[0].dts,g=o[o.length-1].dts;const T=g-f,R=T?Math.round(T/(l-1)):d||t.inputTimeScale/30;if(s){const O=f-h,F=O>R,Y=O<-1;if((F||Y)&&(F?b.warn(`AVC: ${Yt(O,true)} ms (${O}dts) hole between fragments detected at ${e.toFixed(3)}`):b.warn(`AVC: ${Yt(-O,true)} ms (${O}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!Y||h>=o[0].pts||Bt)){f=h;const G=o[0].pts-O;if(F)o[0].dts=f,o[0].pts=G;else for(let z=0;z<o.length&&!(o[z].dts>G);z++)o[z].dts-=O,o[z].pts-=O;b.log(`Video: Initial PTS/DTS adjusted: ${Yt(G,true)}/${Yt(f,true)}, delta: ${Yt(O,true)} ms`);}}f=Math.max(0,f);let E=0,I=0,v=f;for(let O=0;O<l;O++){const F=o[O],Y=F.units,G=Y.length;let z=0;for(let tt=0;tt<G;tt++)z+=Y[tt].data.length;I+=z,E+=G,F.length=z,F.dts<v?(F.dts=v,v+=R/4|0||1):v=F.dts,m=Math.min(F.pts,m),p=Math.max(F.pts,p);}g=o[l-1].dts;const C=I+4*E+8;let P;try{P=new Uint8Array(C);}catch(O){this.observer.emit(x.ERROR,x.ERROR,{type:H.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:false,error:O,bytes:C,reason:`fail allocating video mdat ${C}`});return}const L=new DataView(P.buffer);L.setUint32(0,C),P.set(S.types.mdat,4);let _=false,D=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,X=Number.NEGATIVE_INFINITY,V=Number.NEGATIVE_INFINITY;for(let O=0;O<l;O++){const F=o[O],Y=F.units;let G=0;for(let U=0,N=Y.length;U<N;U++){const Z=Y[U],ot=Z.data,yt=Z.data.byteLength;L.setUint32(u,yt),u+=4,P.set(ot,u),u+=yt,G+=4+yt;}let z;if(O<l-1)d=o[O+1].dts-F.dts,z=o[O+1].pts-F.pts;else {const U=this.config,N=O>0?F.dts-o[O-1].dts:R;if(z=O>0?F.pts-o[O-1].pts:R,U.stretchShortVideoTrack&&this.nextAudioPts!==null){const Z=Math.floor(U.maxBufferHole*n),ot=(i?m+i*n:this.nextAudioPts)-F.pts;ot>Z?(d=ot-N,d<0?d=N:_=true,b.log(`[mp4-remuxer]: It is approximately ${ot/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=N;}else d=N;}const tt=Math.round(F.pts-F.dts);D=Math.min(D,d),X=Math.max(X,d),q=Math.min(q,z),V=Math.max(V,z),a.push(new Hs(F.key,d,G,tt));}if(a.length){if(Bt){if(Bt<70){const O=a[0].flags;O.dependsOn=2,O.isNonSync=0;}}else if(Fe&&V-q<X-D&&R/X<.025&&a[0].cts===0){b.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let O=f;for(let F=0,Y=a.length;F<Y;F++){const G=O+a[F].duration,z=O+a[F].cts;if(F<Y-1){const tt=G+a[F+1].cts;a[F].duration=tt-z;}else a[F].duration=F?a[F-1].duration:R;a[F].cts=0,O=G;}}}d=_||!d?R:d,this.nextAvcDts=h=g+d,this.videoSampleDuration=d,this.isVideoContiguous=true;const Q={data1:S.moof(t.sequenceNumber++,f,ct({},t,{samples:a})),data2:P,startPTS:m/n,endPTS:(p+d)/n,startDTS:f/n,endDTS:h/n,type:"video",hasAudio:false,hasVideo:true,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,Q}getSamplesPerFrame(t){switch(t.segmentCodec){case "mp3":return Qo;case "ac3":return Zo;default:return Vs}}remuxAudio(t,e,s,i,n){const o=t.inputTimeScale,a=t.samplerate?t.samplerate:o,l=o/a,c=this.getSamplesPerFrame(t),h=c*l,u=this._initPTS,d=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=n!==void 0;let m=t.samples,p=d?0:8,y=this.nextAudioPts||-1;const A=e*o,T=u.baseTime*o/u.timescale;if(this.isAudioContiguous=s=s||m.length&&y>0&&(i&&Math.abs(A-y)<9e3||Math.abs(ft(m[0].pts-T,A)-y)<20*h),m.forEach(function(B){B.pts=ft(B.pts-T,A);}),!s||y<0){if(m=m.filter(B=>B.pts>=0),!m.length)return;n===0?y=0:i&&!g?y=Math.max(0,A):y=m[0].pts;}if(t.segmentCodec==="aac"){const B=this.config.maxAudioFramesDrift;for(let j=0,Q=y;j<m.length;j++){const O=m[j],F=O.pts,Y=F-Q,G=Math.abs(1e3*Y/o);if(Y<=-B*h&&g)j===0&&(b.warn(`Audio frame @ ${(F/o).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*Y/o)} ms.`),this.nextAudioPts=y=Q=F);else if(Y>=B*h&&G<Xo&&g){let z=Math.round(Y/h);Q=F-z*h,Q<0&&(z--,Q+=h),j===0&&(this.nextAudioPts=y=Q),b.warn(`[mp4-remuxer]: Injecting ${z} audio frame @ ${(Q/o).toFixed(3)}s due to ${Math.round(1e3*Y/o)} ms gap.`);for(let tt=0;tt<z;tt++){const U=Math.max(Q,0);let N=Ks.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);N||(b.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),N=O.unit.subarray()),m.splice(j,0,{unit:N,pts:U}),Q+=h,j++;}}O.pts=Q,Q+=h;}}let R=null,E=null,I,v=0,C=m.length;for(;C--;)v+=m[C].unit.byteLength;for(let B=0,j=m.length;B<j;B++){const Q=m[B],O=Q.unit;let F=Q.pts;if(E!==null){const G=f[B-1];G.duration=Math.round((F-E)/l);}else if(s&&t.segmentCodec==="aac"&&(F=y),R=F,v>0){v+=p;try{I=new Uint8Array(v);}catch(G){this.observer.emit(x.ERROR,x.ERROR,{type:H.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:false,error:G,bytes:v,reason:`fail allocating audio mdat ${v}`});return}d||(new DataView(I.buffer).setUint32(0,v),I.set(S.types.mdat,4));}else return;I.set(O,p);const Y=O.byteLength;p+=Y,f.push(new Hs(true,c,Y,0)),E=F;}const P=f.length;if(!P)return;const L=f[f.length-1];this.nextAudioPts=y=E+l*L.duration;const _=d?new Uint8Array(0):S.moof(t.sequenceNumber++,R/l,ct({},t,{samples:f}));t.samples=[];const D=R/o,q=y/o,V={data1:_,data2:I,startPTS:D,endPTS:q,startDTS:D,endDTS:q,type:"audio",hasAudio:true,hasVideo:false,nb:P};return this.isAudioContiguous=true,V}remuxEmptyAudio(t,e,s,i){const n=t.inputTimeScale,o=t.samplerate?t.samplerate:n,a=n/o,l=this.nextAudioPts,c=this._initDTS,h=c.baseTime*9e4/c.timescale,u=(l!==null?l:i.startDTS*n)+h,d=i.endDTS*n+h,f=a*Vs,g=Math.ceil((d-u)/f),m=Ks.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(b.warn("[mp4-remuxer]: remux empty Audio"),!m){b.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const p=[];for(let y=0;y<g;y++){const A=u+y*f;p.push({unit:m,pts:A,dts:A});}return t.samples=p,this.remuxAudio(t,e,s,false)}}function ft(r,t){let e;if(t===null)return r;for(t<r?e=-8589934592:e=8589934592;Math.abs(r-t)>4294967296;)r+=e;return r}function Jo(r){for(let t=0;t<r.length;t++)if(r[t].key)return t;return  -1}function Vi(r,t,e,s){const i=r.samples.length;if(!i)return;const n=r.inputTimeScale;for(let a=0;a<i;a++){const l=r.samples[a];l.pts=ft(l.pts-e.baseTime*n/e.timescale,t*n)/n,l.dts=ft(l.dts-s.baseTime*n/s.timescale,t*n)/n;}const o=r.samples;return r.samples=[],{samples:o}}function Hi(r,t,e){const s=r.samples.length;if(!s)return;const i=r.inputTimeScale;for(let o=0;o<s;o++){const a=r.samples[o];a.pts=ft(a.pts-e.baseTime*i/e.timescale,t*i)/i;}r.samples.sort((o,a)=>o.pts-a.pts);const n=r.samples;return r.samples=[],{samples:n}}class Hs{constructor(t,e,s,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=s,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1};}}class ta{constructor(){this.emitInitSegment=false,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null;}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null;}resetNextTimestamp(){this.lastEndTime=null;}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(mr(t,i)),this.emitInitSegment=true;}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=xi(t);i.audio&&(e=Ws(i.audio,lt.AUDIO)),i.video&&(s=Ws(i.video,lt.VIDEO));const n={};i.audio&&i.video?n.audiovideo={container:"video/mp4",codec:e+","+s,initSegment:t,id:"main"}:i.audio?n.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?n.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:b.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n;}remux(t,e,s,i,n,o){var a,l;let{initPTS:c,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};$(h)||(h=this.lastEndTime=n||0);const d=e.samples;if(!(d!=null&&d.length))return u;const f={initPTS:void 0,timescale:1};let g=this.initData;if((a=g)!=null&&a.length||(this.generateInitSegment(d),g=this.initData),!((l=g)!=null&&l.length))return b.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=false);const m=xr(d,g),p=pr(g,d),y=p===null?n:p;(ea(c,y,n,m)||f.timescale!==c.timescale&&o)&&(f.initPTS=y-n,c&&c.timescale===1&&b.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const A=t?y-c.baseTime/c.timescale:h,T=A+m;Tr(g,d,c.baseTime/c.timescale),m>0?this.lastEndTime=T:(b.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const R=!!g.audio,E=!!g.video;let I="";R&&(I+="audio"),E&&(I+="video");const v={data1:d,startPTS:A,startDTS:A,endPTS:T,endDTS:T,type:I,hasAudio:R,hasVideo:E,nb:1,dropped:0};return u.audio=v.type==="audio"?v:void 0,u.video=v.type!=="audio"?v:void 0,u.initSegment=f,u.id3=Vi(s,n,c,c),i.samples.length&&(u.text=Hi(i,n,c)),u}}function ea(r,t,e,s){if(r===null)return  true;const i=Math.max(s,1),n=t-r.baseTime/r.timescale;return Math.abs(n-e)>i}function Ws(r,t){const e=r?.codec;if(e&&e.length>4)return e;if(t===lt.AUDIO){if(e==="ec-3"||e==="ac-3"||e==="alac")return e;if(e==="fLaC"||e==="Opus")return Ye(e,false);const s="mp4a.40.5";return b.info(`Parsed audio codec "${e}" or audio object type not handled. Using "${s}"`),s}return b.warn(`Unhandled video codec "${e}"`),e==="hvc1"||e==="hev1"?"hvc1.1.6.L120.90":e==="av01"?"av01.0.04M.08":"avc1.42e01e"}let It;try{It=self.performance.now.bind(self.performance);}catch{b.debug("Unable to use Performance API on this environment"),It=Kt?.Date.now;}const fe=[{demux:$o,remux:ta},{demux:_t,remux:de},{demux:Uo,remux:de},{demux:zo,remux:de}];fe.splice(2,0,{demux:Go,remux:de});class Ys{constructor(t,e,s,i,n){this.async=false,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=t,this.typeSupported=e,this.config=s,this.vendor=i,this.id=n;}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset();}push(t,e,s,i){const n=s.transmuxing;n.executeStart=It();let o=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||a,{audioCodec:m,videoCodec:p,defaultInitPts:y,duration:A,initSegmentData:T}=l,R=sa(o,e);if(R&&R.method==="AES-128"){const C=this.getDecrypter();if(C.isSync()){let P=C.softwareDecrypt(o,R.key.buffer,R.iv.buffer);if(s.part>-1&&(P=C.flush()),!P)return n.executeEnd=It(),Oe(s);o=new Uint8Array(P);}else return this.decryptionPromise=C.webCryptoDecrypt(o,R.key.buffer,R.iv.buffer).then(P=>{const L=this.push(P,null,s);return this.decryptionPromise=null,L}),this.decryptionPromise}const E=this.needsProbing(h,u);if(E){const C=this.configureTransmuxer(o);if(C)return b.warn(`[transmuxer] ${C.message}`),this.observer.emit(x.ERROR,x.ERROR,{type:H.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:false,error:C,reason:C.message}),n.executeEnd=It(),Oe(s)}(h||u||g||E)&&this.resetInitSegment(T,m,p,A,e),(h||g||E)&&this.resetInitialTimestamp(y),c||this.resetContiguity();const I=this.transmux(o,R,f,d,s),v=this.currentTransmuxState;return v.contiguous=true,v.discontinuity=false,v.trackSwitch=false,n.executeEnd=It(),I}flush(t){const e=t.transmuxing;e.executeStart=It();const{decrypter:s,currentTransmuxState:i,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(t));const o=[],{timeOffset:a}=i;if(s){const u=s.flush();u&&o.push(this.push(u,null,t));}const{demuxer:l,remuxer:c}=this;if(!l||!c)return e.executeEnd=It(),[Oe(t)];const h=l.flush(a);return ge(h)?h.then(u=>(this.flushRemux(o,u,t),o)):(this.flushRemux(o,h,t),o)}flushRemux(t,e,s){const{audioTrack:i,videoTrack:n,id3Track:o,textTrack:a}=e,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;b.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(i,n,o,a,c,l,true,this.id);t.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=It();}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;!e||!s||(e.resetTimeStamp(t),s.resetTimeStamp(t));}resetContiguity(){const{demuxer:t,remuxer:e}=this;!t||!e||(t.resetContiguity(),e.resetNextTimestamp());}resetInitSegment(t,e,s,i,n){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(t,e,s,i),a.resetInitSegment(t,e,s,n));}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0);}transmux(t,e,s,i,n){let o;return e&&e.method==="SAMPLE-AES"?o=this.transmuxSampleAes(t,e,s,i,n):o=this.transmuxUnencrypted(t,s,i,n),o}transmuxUnencrypted(t,e,s,i){const{audioTrack:n,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(t,e,false,!this.config.progressive);return {remuxResult:this.remuxer.remux(n,o,a,l,e,s,false,this.id),chunkMeta:i}}transmuxSampleAes(t,e,s,i,n){return this.demuxer.demuxSampleAes(t,e,s).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,s,i,false,this.id),chunkMeta:n}))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i,vendor:n}=this;let o;for(let d=0,f=fe.length;d<f;d++){var a;if((a=fe[d].demux)!=null&&a.probe(t)){o=fe[d];break}}if(!o)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,h=o.remux,u=o.demux;(!c||!(c instanceof h))&&(this.remuxer=new h(s,e,i,n)),(!l||!(l instanceof u))&&(this.demuxer=new u(s,e,i),this.probe=u.probe);}needsProbing(t,e){return !this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new as(this.config)),t}}function sa(r,t){let e=null;return r.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(e=t),e}const Oe=r=>({remuxResult:{},chunkMeta:r});function ge(r){return "then"in r&&r.then instanceof Function}class ia{constructor(t,e,s,i,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=n||null;}}class na{constructor(t,e,s,i,n,o){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=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=n,this.initSegmentChange=o;}}var Wi={exports:{}};(function(r){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=false));function i(l,c,h){this.fn=l,this.context=c,this.once=h||false;}function n(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,u||l,d),g=e?e+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c];}function a(){this._events=new s,this._eventsCount=0;}a.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)t.call(h,u)&&c.push(e?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=e?e+c:c,u=this._events[h];if(!u)return [];if(u.fn)return [u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},a.prototype.listenerCount=function(c){var h=e?e+c:c,u=this._events[h];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,h,u,d,f,g){var m=e?e+c:c;if(!this._events[m])return  false;var p=this._events[m],y=arguments.length,A,T;if(p.fn){switch(p.once&&this.removeListener(c,p.fn,void 0,true),y){case 1:return p.fn.call(p.context),true;case 2:return p.fn.call(p.context,h),true;case 3:return p.fn.call(p.context,h,u),true;case 4:return p.fn.call(p.context,h,u,d),true;case 5:return p.fn.call(p.context,h,u,d,f),true;case 6:return p.fn.call(p.context,h,u,d,f,g),true}for(T=1,A=new Array(y-1);T<y;T++)A[T-1]=arguments[T];p.fn.apply(p.context,A);}else {var R=p.length,E;for(T=0;T<R;T++)switch(p[T].once&&this.removeListener(c,p[T].fn,void 0,true),y){case 1:p[T].fn.call(p[T].context);break;case 2:p[T].fn.call(p[T].context,h);break;case 3:p[T].fn.call(p[T].context,h,u);break;case 4:p[T].fn.call(p[T].context,h,u,d);break;default:if(!A)for(E=1,A=new Array(y-1);E<y;E++)A[E-1]=arguments[E];p[T].fn.apply(p[T].context,A);}}return  true},a.prototype.on=function(c,h,u){return n(this,c,h,u,false)},a.prototype.once=function(c,h,u){return n(this,c,h,u,true)},a.prototype.removeListener=function(c,h,u,d){var f=e?e+c:c;if(!this._events[f])return this;if(!h)return o(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!d||g.once)&&(!u||g.context===u)&&o(this,f);else {for(var m=0,p=[],y=g.length;m<y;m++)(g[m].fn!==h||d&&!g[m].once||u&&g[m].context!==u)&&p.push(g[m]);p.length?this._events[f]=p.length===1?p[0]:p:o(this,f);}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=e?e+c:c,this._events[h]&&o(this,h)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=e,a.EventEmitter=a,r.exports=a;})(Wi);var ra=Wi.exports,Yi=Nn(ra);class oa{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=t.config;this.hls=t,this.id=e,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const o=(c,h)=>{h=h||{},h.frag=this.frag,h.id=this.id,c===x.ERROR&&(this.error=h.error),this.hls.trigger(c,h);};this.observer=new Yi,this.observer.on(x.FRAG_DECRYPTED,o),this.observer.on(x.ERROR,o);const a=ye(n.preferManagedMediaSource)||{isTypeSupported:()=>false},l={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(n.workerPath||bo())){try{n.workerPath?(b.log(`loading Web Worker ${n.workerPath} for "${e}"`),this.workerContext=Lo(n.workerPath)):(b.log(`injecting Web Worker for "${e}"`),this.workerContext=Ro()),this.onwmsg=u=>this.onWorkerMessage(u);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=u=>{const d=new Error(`${u.message}  (${u.filename}:${u.lineno})`);n.enableWorker=!1,b.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(x.ERROR,{type:H.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d});},h.postMessage({cmd:"init",typeSupported:l,vendor:"",id:e,config:JSON.stringify(n)});}catch(h){b.warn(`Error setting up "${e}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new Ys(this.observer,l,n,"",e);}return}this.transmuxer=new Ys(this.observer,l,n,"",e);}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null;}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else {const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null);}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null;}push(t,e,s,i,n,o,a,l,c,h){var u,d;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,g=o?o.start:n.start,m=n.decryptdata,p=this.frag,y=!(p&&n.cc===p.cc),A=!(p&&c.level===p.level),T=p?c.sn-p.sn:-1,R=this.part?c.part-this.part.index:-1,E=T===0&&c.id>1&&c.id===p?.stats.chunkCount,I=!A&&(T===1||T===0&&(R===1||E&&R<=0)),v=self.performance.now();(A||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=v),o&&(R||!I)&&(o.stats.parsing.start=v);const C=!(p&&((u=n.initSegment)==null?void 0:u.url)===((d=p.initSegment)==null?void 0:d.url)),P=new na(y,I,l,A,g,C);if(!I||y||C){b.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
        discontinuity: ${y}
        trackSwitch: ${A}
        contiguous: ${I}
        accurateTimeOffset: ${l}
        timeOffset: ${g}
        initSegmentChange: ${C}`);const L=new ia(s,i,e,a,h);this.configureTransmuxer(L);}if(this.frag=n,this.part=o,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:m,chunkMeta:c,state:P},t instanceof ArrayBuffer?[t]:[]);else if(f){const L=f.push(t,m,c,P);ge(L)?(f.async=true,L.then(_=>{this.handleTransmuxComplete(_);}).catch(_=>{this.transmuxerError(_,c,"transmuxer-interface push error");})):(f.async=false,this.handleTransmuxComplete(L));}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let s=e.flush(t);ge(s)||e.async?(ge(s)||(s=Promise.resolve(s)),s.then(n=>{this.handleFlushResult(n,t);}).catch(n=>{this.transmuxerError(n,t,"transmuxer-interface flush error");})):this.handleFlushResult(s,t);}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(x.ERROR,{type:H.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:false,error:t,err:t,reason:s}));}handleFlushResult(t,e){t.forEach(s=>{this.handleTransmuxComplete(s);}),this.onFlush(e);}onWorkerMessage(t){const e=t.data;if(!(e!=null&&e.event)){b.warn(`worker message received with no ${e?"event name":"data"}`);return}const s=this.hls;if(this.hls)switch(e.event){case "init":{var i;const n=(i=this.workerContext)==null?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break}case "transmuxComplete":{this.handleTransmuxComplete(e.data);break}case "flush":{this.onFlush(e.data);break}case "workerLog":b[e.data.logType]&&b[e.data.logType](e.data.message);break;default:{e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,s.trigger(e.event,e.data);break}}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t);}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t);}}function zi(r,t){if(r.length!==t.length)return  false;for(let e=0;e<r.length;e++)if(!Vt(r[e].attrs,t[e].attrs))return  false;return  true}function Vt(r,t,e){const s=r["STABLE-RENDITION-ID"];return s&&!e?s===t["STABLE-RENDITION-ID"]:!(e||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>r[i]!==t[i])}function Xe(r,t){return t.label.toLowerCase()===r.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(r.lang||"").toLowerCase())}const zs=100;class aa extends Ci{constructor(t,e,s){super(t,e,s,"[audio-stream-controller]",W.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=false,this.bufferFlushed=false,this.cachedTrackLoadedData=null,this._registerListeners();}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null;}_registerListeners(){const{hls:t}=this;t.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.LEVEL_LOADED,this.onLevelLoaded,this),t.on(x.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(x.ERROR,this.onError,this),t.on(x.BUFFER_RESET,this.onBufferReset,this),t.on(x.BUFFER_CREATED,this.onBufferCreated,this),t.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(x.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(x.FRAG_BUFFERED,this.onFragBuffered,this);}_unregisterListeners(){const{hls:t}=this;t.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.LEVEL_LOADED,this.onLevelLoaded,this),t.off(x.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(x.ERROR,this.onError,this),t.off(x.BUFFER_RESET,this.onBufferReset,this),t.off(x.BUFFER_CREATED,this.onBufferCreated,this),t.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(x.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(x.FRAG_BUFFERED,this.onFragBuffered,this);}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:n}){if(s==="main"){const o=e.cc;this.initPTS[e.cc]={baseTime:i,timescale:n},this.log(`InitPTS for cc: ${o} found from main: ${i}`),this.videoTrackCC=o,this.state===k.WAITING_INIT_PTS&&this.tick();}}startLoad(t){if(!this.levels){this.startPosition=t,this.state=k.STOPPED;return}const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(zs),e>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=k.IDLE):(this.loadedmetadata=false,this.state=k.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick();}doTick(){switch(this.state){case k.IDLE:this.doTickIdle();break;case k.WAITING_TRACK:{var t;const{levels:s,trackId:i}=this,n=s==null||(t=s[i])==null?void 0:t.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=k.WAITING_INIT_PTS;}break}case k.FRAG_LOADING_WAITING_RETRY:{var e;const s=performance.now(),i=this.retryDate;if(!i||s>=i||(e=this.media)!=null&&e.seeking){const{levels:n,trackId:o}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(n?.[o]||null),this.state=k.IDLE;}break}case k.WAITING_INIT_PTS:{const s=this.waitingData;if(s){const{frag:i,part:n,cache:o,complete:a}=s;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=k.FRAG_LOADING;const l=o.flush(),c={frag:i,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),a&&super._handleFragmentLoadComplete(c);}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else {const l=this.getLoadPosition(),c=nt.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);qe(c.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment());}}else this.state=k.IDLE;}}this.onTickEnd();}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=k.IDLE);}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState();}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime);}doTickIdle(){const{hls:t,levels:e,media:s,trackId:i}=this,n=t.config;if(!s&&(this.startFragRequested||!n.startFragPrefetch)||!(e!=null&&e[i]))return;const o=e[i],a=o.details;if(!a||a.live&&this.levelLastLoaded!==o||this.waitForCdnTuneIn(a)){this.state=k.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=false,this.afterBufferFlushed(l,lt.AUDIO,W.AUDIO));const c=this.getFwdBufferInfo(l,W.AUDIO);if(c===null)return;const{bufferedTrack:h,switchingTrack:u}=this;if(!u&&this._streamEnded(c,a)){t.trigger(x.BUFFER_EOS,{type:"audio"}),this.state=k.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,W.MAIN),f=c.len,g=this.getMaxBufferLength(d?.len),m=a.fragments,p=m[0].start;let y=this.flushing?this.getLoadPosition():c.end;if(u&&s){const E=this.getLoadPosition();h&&!Vt(u.attrs,h.attrs)&&(y=E),a.PTSKnown&&E<p&&(c.end>p||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=p+.05);}if(f>=g&&!u&&y<m[m.length-1].start)return;let A=this.getNextFragment(y,a),T=false;if(A&&this.isLoopLoading(A,y)&&(T=!!A.gap,A=this.getNextFragmentLoopLoading(A,a,c,W.MAIN,g)),!A){this.bufferFlushed=true;return}const R=d&&A.start>d.end+a.targetduration;if(R||!(d!=null&&d.len)&&c.len){const E=this.getAppendedFrag(A.start,W.MAIN);if(E===null||(T||(T=!!E.gap||!!R&&d.len===0),R&&!T||T&&c.nextStart&&c.nextStart<E.end))return}this.loadFragment(A,o,y);}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=false,super.onMediaDetaching();}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(s=>new Te(s));}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?this.setInterval(zs):this.resetTransmuxer(),s?(this.switchingTrack=e,this.state=k.IDLE,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=k.STOPPED),this.tick();}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=false,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=false,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1;}onLevelLoaded(t,e){this.mainDetails=e.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(x.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null);}onAudioTrackLoaded(t,e){var s;if(this.mainDetails==null){this.cachedTrackLoadedData=e;return}const{levels:i}=this,{details:n,id:o}=e;if(!i){this.warn(`Audio tracks were reset while loading level ${o}`);return}this.log(`Audio track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const a=i[o];let l=0;if(n.live||(s=a.details)!=null&&s.live){this.checkLiveUpdate(n);const h=this.mainDetails;if(n.deltaUpdateFailed||!h)return;if(!a.details&&n.hasProgramDateTime&&h.hasProgramDateTime)Ae(n,h),l=n.fragments[0].start;else {var c;l=this.alignPlaylists(n,a.details,(c=this.levelLastLoaded)==null?void 0:c.details);}}a.details=n,this.levelLastLoaded=a,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(this.mainDetails||n,l),this.state===k.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=k.IDLE),this.tick();}_handleFragmentLoadProgress(t){var e;const{frag:s,part:i,payload:n}=t,{config:o,trackId:a,levels:l}=this;if(!l){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 c=l[a];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=o.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new oa(this.hls,W.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(e=s.initSegment)==null?void 0:e.data;if(f!==void 0){const p=i?i.index:-1,y=p!==-1,A=new wi(s.level,s.sn,s.stats.chunkCount,n.byteLength,p,y);d.push(n,g,u,"",s,i,h.totalduration,false,A,f);}else {this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:m}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new vo,complete:false};m.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=k.WAITING_INIT_PTS;}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=true;return}super._handleFragmentLoadComplete(t);}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=false;}onBufferCreated(t,e){const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null);}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type!==W.AUDIO){if(!this.loadedmetadata&&s.type===W.MAIN){const n=this.videoBuffer||this.media;n&&nt.getBuffered(n).length&&(this.loadedmetadata=true);}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(s.sn!=="initSegment"){this.fragPrevious=s;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(x.AUDIO_TRACK_SWITCHED,ut({},n)));}this.fragBufferedComplete(s,i);}onError(t,e){var s;if(e.fatal){this.state=k.ERROR;return}switch(e.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.AUDIO,e);break;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===k.WAITING_TRACK&&((s=e.context)==null?void 0:s.type)===wt.AUDIO_TRACK&&(this.state=k.IDLE);break;case w.BUFFER_APPEND_ERROR:case w.BUFFER_FULL_ERROR:if(!e.parent||e.parent!=="audio")return;if(e.details===w.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onBufferFlushing(t,{type:e}){e!==lt.VIDEO&&(this.flushing=true);}onBufferFlushed(t,{type:e}){if(e!==lt.VIDEO){this.flushing=false,this.bufferFlushed=true,this.state===k.ENDED&&(this.state=k.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,e,W.AUDIO),this.tick());}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:n,chunkMeta:o}=t,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:h}=a,{details:u}=h,{audio:d,text:f,id3:g,initSegment:m}=n;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=k.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const p=l.initSegment||l;this._bufferInitSegment(h,m.tracks,p,o),i.trigger(x.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:s,tracks:m.tracks});}if(d){const{startPTS:p,endPTS:y,startDTS:A,endDTS:T}=d;c&&(c.elementaryStreams[lt.AUDIO]={startPTS:p,endPTS:y,startDTS:A,endDTS:T}),l.setElementaryStreamInfo(lt.AUDIO,p,y,A,T),this.bufferFragmentData(d,l,c,o);}if(g!=null&&(e=g.samples)!=null&&e.length){const p=ct({id:s,frag:l,details:u},g);i.trigger(x.FRAG_PARSING_METADATA,p);}if(f){const p=ct({id:s,frag:l,details:u},f);i.trigger(x.FRAG_PARSING_USERDATA,p);}}_bufferInitSegment(t,e,s,i){if(this.state!==k.PARSING)return;e.video&&delete e.video;const n=e.audio;if(!n)return;n.id="audio";const o=t.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${o}/${n.codec}]`),o&&o.split(",").length===1&&(n.levelCodec=o),this.hls.trigger(x.BUFFER_CODECS,e);const a=n.initSegment;if(a!=null&&a.byteLength){const l={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(x.BUFFER_APPENDING,l);}this.tickImmediate();}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);if(this.fragCurrent=t,this.switchingTrack||i===xt.NOT_LOADED||i===xt.PARTIAL){var n;if(t.sn==="initSegment")this._loadInitSegment(t,e);else if((n=e.details)!=null&&n.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=k.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragments[0].start!==e.details.fragments[0].start&&Ae(e.details,o);}else this.startFragRequested=true,super.loadFragment(t,e,s);}else this.clearTrackerIfNeeded(t);}flushAudioIfNeeded(t){const{media:e,bufferedTrack:s}=this,i=s?.attrs,n=t.attrs;e&&i&&(i.CHANNELS!==n.CHANNELS||s.name!==t.name||s.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null);}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(x.AUDIO_TRACK_SWITCHED,ut({},t));}}class la extends Li{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true,this.registerListeners();}registerListeners(){const{hls:t}=this;t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.MANIFEST_PARSED,this.onManifestParsed,this),t.on(x.LEVEL_LOADING,this.onLevelLoading,this),t.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(x.ERROR,this.onError,this);}unregisterListeners(){const{hls:t}=this;t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.MANIFEST_PARSED,this.onManifestParsed,this),t.off(x.LEVEL_LOADING,this.onLevelLoading,this),t.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(x.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(x.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=true;}onManifestParsed(t,e){this.tracks=e.audioTracks||[];}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:n}=e,o=this.tracksInGroup[s];if(!o||o.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${o?.groupId}`);return}const a=o.details;o.details=e.details,this.log(`Audio track ${s} "${o.name}" lang:${o.lang} group:${i} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a);}onLevelLoading(t,e){this.switchLevel(e.level);}onLevelSwitching(t,e){this.switchLevel(e.level);}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,i=this.groupIds;let n=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(d=>d.default)&&(this.selectDefaultTrack=false),a.forEach((d,f)=>{d.id=f;});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const l=this.hls.config.audioPreference;if(!n&&l){const d=vt(l,a,Nt);if(d>-1)n=a[d];else {const f=vt(l,this.tracks);n=this.tracks[f];}}let c=this.findTrackId(n);c===-1&&n&&(c=this.findTrackId(null));const h={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(x.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(a.length&&u===-1){var o;const d=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(d.message),this.hls.trigger(x.ERROR,{type:H.MEDIA_ERROR,details:w.AUDIO_TRACK_LOAD_ERROR,fatal:true,error:d});}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId);}onError(t,e){e.fatal||!e.context||e.context.type===wt.AUDIO_TRACK&&e.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(e.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(e));}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=false,this.setAudioTrack(t);}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=false,s.length){const i=this.currentTrack;if(i&&$t(t,i,Nt))return i;const n=vt(t,this.tracksInGroup,Nt);if(n>-1){const o=this.tracksInGroup[n];return this.setAudioTrack(n),o}else if(i){let o=e.loadLevel;o===-1&&(o=e.firstAutoLevel);const a=oo(t,e.levels,s,o,Nt);if(a===-1)return null;e.nextLoadLevel=a;}if(t.channels||t.audioCodec){const o=vt(t,s);if(o>-1)return s[o]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length){this.warn(`Invalid audio track id: ${t}`);return}this.clearTimer(),this.selectDefaultTrack=false;const s=this.currentTrack,i=e[t],n=i.details&&!i.details.live;if(t===this.trackId&&i===s&&n||(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger(x.AUDIO_TRACK_SWITCHING,ut({},i)),n))return;const o=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(o);}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if(!(this.selectDefaultTrack&&!i.default)&&(!t||$t(t,i,Nt)))return s}if(t){const{name:s,lang:i,assocLang:n,characteristics:o,audioCodec:a,channels:l}=t;for(let c=0;c<e.length;c++){const h=e[c];if($t({name:s,lang:i,assocLang:n,characteristics:o,audioCodec:a,channels:l},h,Nt))return c}for(let c=0;c<e.length;c++){const h=e[c];if(Vt(t.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<e.length;c++){const h=e[c];if(Vt(t.attrs,h.attrs,["LANGUAGE"]))return c}}return  -1}loadPlaylist(t){const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){super.loadPlaylist();const s=e.id,i=e.groupId;let n=e.url;if(t)try{n=t.addDirectives(n);}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`);}this.log(`loading audio-track playlist ${s} "${e.name}" lang:${e.lang} group:${i}`),this.clearTimer(),this.hls.trigger(x.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:i,deliveryDirectives:t||null});}}}const qs=500;class ca extends Ci{constructor(t,e,s){super(t,e,s,"[subtitle-stream-controller]",W.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners();}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null;}_registerListeners(){const{hls:t}=this;t.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.LEVEL_LOADED,this.onLevelLoaded,this),t.on(x.ERROR,this.onError,this),t.on(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(x.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(x.FRAG_BUFFERED,this.onFragBuffered,this);}_unregisterListeners(){const{hls:t}=this;t.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.LEVEL_LOADED,this.onLevelLoaded,this),t.off(x.ERROR,this.onError,this),t.off(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(x.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(x.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(x.FRAG_BUFFERED,this.onFragBuffered,this);}startLoad(t){this.stopLoad(),this.state=k.IDLE,this.setInterval(qs),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick();}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments();}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching();}onLevelLoaded(t,e){this.mainDetails=e.details;}onSubtitleFragProcessed(t,e){const{frag:s,success:i}=e;if(this.fragPrevious=s,this.state=k.IDLE,!i)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let o;const a=s.start;for(let c=0;c<n.length;c++)if(a>=n[c].start&&a<=n[c].end){o=n[c];break}const l=s.start+s.duration;o?o.end=l:(o={start:a,end:l},n.push(o)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null);}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(s===0&&i!==Number.POSITIVE_INFINITY){const n=i-1;if(n<=0)return;e.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(o=>{for(let a=0;a<o.length;){if(o[a].end<=n){o.shift();continue}else if(o[a].start<n)o[a].start=n;else break;a++;}}),this.fragmentTracker.removeFragmentsInRange(s,n,W.SUBTITLE);}}onFragBuffered(t,e){if(!this.loadedmetadata&&e.frag.type===W.MAIN){var s;(s=this.media)!=null&&s.buffered.length&&(this.loadedmetadata=true);}}onError(t,e){const s=e.frag;s?.type===W.SUBTITLE&&(e.details===w.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,true),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==k.STOPPED&&(this.state=k.IDLE));}onSubtitleTracksUpdated(t,{subtitleTracks:e}){if(this.levels&&zi(this.levels,e)){this.levels=e.map(s=>new Te(s));return}this.tracksBuffered=[],this.levels=e.map(s=>{const i=new Te(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,W.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null;}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.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.setInterval(qs);}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:n}=this,{details:o,id:a}=e;if(!n){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const l=n[a];if(a>=n.length||!l)return;this.log(`Subtitle track ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(o.live||(s=l.details)!=null&&s.live){const u=this.mainDetails;if(o.deltaUpdateFailed||!u)return;const d=u.fragments[0];if(!l.details)o.hasProgramDateTime&&u.hasProgramDateTime?(Ae(o,u),c=o.fragments[0].start):d&&(c=d.start,ze(o,c));else {var h;c=this.alignPlaylists(o,l.details,(h=this.levelLastLoaded)==null?void 0:h.details),c===0&&d&&(c=d.start,ze(o,c));}}l.details=o,this.levelLastLoaded=l,a===i&&(!this.startFragRequested&&(this.mainDetails||!o.live)&&this.setStartPosition(this.mainDetails||o,c),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===k.IDLE&&(ve(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)));}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,i=e.decryptdata,n=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&i.method==="AES-128"){const o=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch(a=>{throw n.trigger(x.ERROR,{type:H.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:false,error:a,reason:a.message,frag:e}),a}).then(a=>{const l=performance.now();n.trigger(x.FRAG_DECRYPTED,{frag:e,payload:a,stats:{tstart:o,tdecrypt:l}});}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=k.IDLE;});}}doTick(){if(!this.media){this.state=k.IDLE;return}if(this.state===k.IDLE){const{currentTrackId:t,levels:e}=this,s=e?.[t];if(!s||!e.length||!s.details)return;const{config:i}=this,n=this.getLoadPosition(),o=nt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),{end:a,len:l}=o,c=this.getFwdBufferInfo(this.media,W.MAIN),h=s.details,u=this.getMaxBufferLength(c?.len)+h.levelTargetDuration;if(l>u)return;const d=h.fragments,f=d.length,g=h.edge;let m=null;const p=this.fragPrevious;if(a<g){const y=i.maxFragLookUpTolerance,A=a>g-y?0:y;m=ve(p,d,Math.max(d[0].start,a),A),!m&&p&&p.start<d[0].start&&(m=d[0]);}else m=d[f-1];if(!m)return;if(m=this.mapToInitFragWhenRequired(m),m.sn!=="initSegment"){const y=m.sn-h.startSN,A=d[y-1];A&&A.cc===m.cc&&this.fragmentTracker.getState(A)===xt.NOT_LOADED&&(m=A);}this.fragmentTracker.getState(m)===xt.NOT_LOADED&&this.loadFragment(m,s,a);}}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,s){this.fragCurrent=t,t.sn==="initSegment"?this._loadInitSegment(t,e):(this.startFragRequested=true,super.loadFragment(t,e,s));}get mediaBufferTimeRanges(){return new ha(this.tracksBuffered[this.currentTrackId]||[])}}class ha{constructor(t){this.buffered=void 0;const e=(s,i,n)=>{if(i=i>>>0,i>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${n})`);return t[i][s]};this.buffered={get length(){return t.length},end(s){return e("end",s,t.length)},start(s){return e("start",s,t.length)}};}}class ua extends Li{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=false,this.subtitlePollingInterval=-1,this._subtitleDisplay=true,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const s=ce(this.media.textTracks);for(let n=0;n<s.length;n++)if(s[n].mode==="hidden")e=s[n];else if(s[n].mode==="showing"){e=s[n];break}const i=this.findTrackForTextTrack(e);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(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes();}registerListeners(){const{hls:t}=this;t.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.MANIFEST_PARSED,this.onManifestParsed,this),t.on(x.LEVEL_LOADING,this.onLevelLoading,this),t.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(x.ERROR,this.onError,this);}unregisterListeners(){const{hls:t}=this;t.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.MANIFEST_PARSED,this.onManifestParsed,this),t.off(x.LEVEL_LOADING,this.onLevelLoading,this),t.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(x.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(x.ERROR,this.onError,this);}onMediaAttached(t,e){this.media=e.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(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t);}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),ce(this.media.textTracks).forEach(e=>{qt(e);}),this.subtitleTrack=-1,this.media=null;}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true;}onManifestParsed(t,e){this.tracks=e.subtitleTracks;}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:n}=e,o=this.tracksInGroup[s];if(!o||o.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${o?.groupId}`);return}const a=o.details;o.details=e.details,this.log(`Subtitle track ${s} "${o.name}" lang:${o.lang} group:${i} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a);}onLevelLoading(t,e){this.switchLevel(e.level);}onLevelSwitching(t,e){this.switchLevel(e.level);}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let n=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>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=false),o.forEach((h,u)=>{h.id=u;});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const a=this.hls.config.subtitlePreference;if(!n&&a){this.selectDefaultTrack=false;const h=vt(a,o);if(h>-1)n=o[h];else {const u=vt(a,this.tracks);n=this.tracks[u];}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));const c={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(x.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l);}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId);}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<e.length;i++){const n=e[i];if(!(s&&!n.default||!s&&!t)&&(!t||$t(n,t)))return i}if(t){for(let i=0;i<e.length;i++){const n=e[i];if(Vt(t.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const n=e[i];if(Vt(t.attrs,n.attrs,["LANGUAGE"]))return i}}return  -1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if(Xe(i,t))return s}}return  -1}onError(t,e){e.fatal||!e.context||e.context.type===wt.SUBTITLE_TRACK&&e.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(e.context.groupId)!==-1)&&this.checkRetry(e);}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=false,this.setSubtitleTrack(t);}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const e=this.allSubtitleTracks;if(this.selectDefaultTrack=false,e.length){const s=this.currentTrack;if(s&&$t(t,s))return s;const i=vt(t,this.tracksInGroup);if(i>-1){const n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}else {if(s)return null;{const n=vt(t,e);if(n>-1)return e[n]}}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const s=e.id,i=e.groupId;let n=e.url;if(t)try{n=t.addDirectives(n);}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`);}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(x.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:i,deliveryDirectives:t||null});}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=ce(t.textTracks),s=this.currentTrack;let i;if(s&&(i=e.filter(n=>Xe(s,n))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach(n=>{n.mode!=="disabled"&&n!==i&&(n.mode="disabled");}),i){const n=this.subtitleDisplay?"showing":"hidden";i.mode!==n&&(i.mode=n);}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=e.length||!$(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.clearTimer(),this.selectDefaultTrack=false;const s=this.currentTrack,i=e[t]||null;if(this.trackId=t,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(x.SUBTITLE_TRACK_SWITCH,{id:t});return}const n=!!i.details&&!i.details.live;if(t===this.trackId&&i===s&&n)return;this.log(`Switching to subtitle-track ${t}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:o,groupId:a="",name:l,type:c,url:h}=i;this.hls.trigger(x.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:c,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u);}}class da{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t;}append(t,e,s){const i=this.queues[e];i.push(t),i.length===1&&!s&&this.executeNext(e);}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e);}appendBlocker(t){let e;const s=new Promise(n=>{e=n;}),i={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,t),s}executeNext(t){const e=this.queues[t];if(e.length){const s=e[0];try{s.execute();}catch(i){b.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${i}`),s.onError(i);const n=this.buffers[t];n!=null&&n.updating||this.shiftAndExecuteNext(t);}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t);}current(t){return this.queues[t][0]}}const js=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class fa{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=s=>{this.hls&&this.hls.pauseBuffering();},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering();},this._onMediaSourceOpen=()=>{const{media:s,mediaSource:i}=this;this.log("Media source opened"),s&&(s.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(x.MEDIA_ATTACHED,{media:s,mediaSource:i})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),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&&b.error(`Media element src was set while attaching MediaSource (${i} > ${s})`);},this.hls=t;const e="[buffer-controller]";this.appendSource=wr(ye(t.config.preferManagedMediaSource)),this.log=b.log.bind(b,e),this.warn=b.warn.bind(b,e),this.error=b.error.bind(b,e),this._initSourceBuffer(),this.registerListeners();}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null;}registerListeners(){const{hls:t}=this;t.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.MANIFEST_PARSED,this.onManifestParsed,this),t.on(x.BUFFER_RESET,this.onBufferReset,this),t.on(x.BUFFER_APPENDING,this.onBufferAppending,this),t.on(x.BUFFER_CODECS,this.onBufferCodecs,this),t.on(x.BUFFER_EOS,this.onBufferEos,this),t.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(x.FRAG_PARSED,this.onFragParsed,this),t.on(x.FRAG_CHANGED,this.onFragChanged,this);}unregisterListeners(){const{hls:t}=this;t.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.MANIFEST_PARSED,this.onManifestParsed,this),t.off(x.BUFFER_RESET,this.onBufferReset,this),t.off(x.BUFFER_APPENDING,this.onBufferAppending,this),t.off(x.BUFFER_CODECS,this.onBufferCodecs,this),t.off(x.BUFFER_EOS,this.onBufferEos,this),t.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(x.FRAG_PARSED,this.onFragParsed,this),t.off(x.FRAG_CHANGED,this.onFragChanged,this);}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new da(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null;}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null;}onManifestParsed(t,e){let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);}onMediaAttaching(t,e){const s=this.media=e.media,i=ye(this.appendSource);if(s&&i){var n;const o=this.mediaSource=new i;this.log(`created media source: ${(n=o.constructor)==null?void 0:n.name}`),o.addEventListener("sourceopen",this._onMediaSourceOpen),o.addEventListener("sourceended",this._onMediaSourceEnded),o.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(o.addEventListener("startstreaming",this._onStartStreaming),o.addEventListener("endstreaming",this._onEndStreaming));const a=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{s.removeAttribute("src");const l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&o instanceof l,Xs(s),ga(s,a),s.load();}catch{s.src=a;}else s.src=a;s.addEventListener("emptied",this._onMediaEmptied);}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=this;if(e){if(this.log("media source detaching"),e.readyState==="open")try{e.endOfStream();}catch(i){this.warn(`onMediaDetaching: ${i.message} while calling endOfStream`);}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(t.removeAttribute("src"),this.appendSource&&Xs(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={};}this.hls.trigger(x.MEDIA_DETACHED,void 0);}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{this.resetBuffer(t);}),this._initSourceBuffer();}resetBuffer(t){const e=this.sourceBuffer[t];try{if(e){var s;this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e);}}catch(i){this.warn(`onBufferReset ${t}`,i);}}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length,i=Object.keys(e);if(i.forEach(o=>{if(s){const l=this.tracks[o];if(l&&typeof l.buffer.changeType=="function"){var a;const{id:c,codec:h,levelCodec:u,container:d,metadata:f}=e[o],g=Ls(l.codec,l.levelCodec),m=g?.replace(js,"$1");let p=Ls(h,u);const y=(a=p)==null?void 0:a.replace(js,"$1");if(p&&m!==y){o.slice(0,5)==="audio"&&(p=Ye(p,this.appendSource));const A=`${d};codecs=${p}`;this.appendChangeType(o,A),this.log(`switching codec ${g} to ${p}`),this.tracks[o]={buffer:l.buffer,codec:h,container:d,levelCodec:u,metadata:f,id:c};}}}else this.pendingTracks[o]=e[o];}),s)return;const n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(`${n} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=n),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks();}appendChangeType(t,e){const{operationQueue:s}=this,i={execute:()=>{const n=this.sourceBuffer[t];n&&(this.log(`changing ${t} sourceBuffer type to ${e}`),n.changeType(e)),s.shiftAndExecuteNext(t);},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${t} SourceBuffer type`,n);}};s.append(i,t,!!this.pendingTracks[t]);}onBufferAppending(t,e){const{hls:s,operationQueue:i,tracks:n}=this,{data:o,type:a,frag:l,part:c,chunkMeta:h}=e,u=h.buffering[a],d=self.performance.now();u.start=d;const f=l.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=d),g&&g.start===0&&(g.start=d);const m=n.audio;let p=false;a==="audio"&&m?.container==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const y=l.start,A={execute:()=>{if(u.executeStart=self.performance.now(),p){const T=this.sourceBuffer[a];if(T){const R=y-T.timestampOffset;Math.abs(R)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${y} (delta: ${R}) sn: ${l.sn})`),T.timestampOffset=y);}}this.appendExecutor(o,a);},onStart:()=>{},onComplete:()=>{const T=self.performance.now();u.executeEnd=u.end=T,f.first===0&&(f.first=T),g&&g.first===0&&(g.first=T);const{sourceBuffer:R}=this,E={};for(const I in R)E[I]=nt.getBuffered(R[I]);this.appendErrors[a]=0,a==="audio"||a==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(x.BUFFER_APPENDED,{type:a,frag:l,part:c,chunkMeta:h,parent:l.type,timeRanges:E});},onError:T=>{const R={type:H.MEDIA_ERROR,parent:l.type,details:w.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:l,part:c,chunkMeta:h,error:T,err:T,fatal:false};if(T.code===DOMException.QUOTA_EXCEEDED_ERR)R.details=w.BUFFER_FULL_ERROR;else {const E=++this.appendErrors[a];R.details=w.BUFFER_APPEND_ERROR,this.warn(`Failed ${E}/${s.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),E>=s.config.appendErrorMaxRetry&&(R.fatal=true);}s.trigger(x.ERROR,R);}};i.append(A,a,!!this.pendingTracks[a]);}onBufferFlushing(t,e){const{operationQueue:s}=this,i=n=>({execute:this.removeExecutor.bind(this,n,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(x.BUFFER_FLUSHED,{type:n});},onError:o=>{this.warn(`Failed to remove from ${n} SourceBuffer`,o);}});e.type?s.append(i(e.type),e.type):this.getSourceBufferTypes().forEach(n=>{s.append(i(n),n);});}onFragParsed(t,e){const{frag:s,part:i}=e,n=[],o=i?i.elementaryStreams:s.elementaryStreams;o[lt.AUDIOVIDEO]?n.push("audiovideo"):(o[lt.AUDIO]&&n.push("audio"),o[lt.VIDEO]&&n.push("video"));const a=()=>{const l=self.performance.now();s.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const c=i?i.stats:s.stats;this.hls.trigger(x.FRAG_BUFFERED,{frag:s,part:i,stats:c,id:s.type});};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(a,n);}onFragChanged(t,e){this.trimBuffers();}onBufferEos(t,e){this.getSourceBufferTypes().reduce((i,n)=>{const o=this.sourceBuffer[n];return o&&(!e.type||e.type===n)&&(o.ending=true,o.ended||(o.ended=true,this.log(`${n} sourceBuffer now EOS`))),i&&!!(!o||o.ended)},true)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(n=>{const o=this.sourceBuffer[n];o&&(o.ending=false);});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),i.endOfStream();}));}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration());}trimBuffers(){const{hls:t,details:e,media:s}=this;if(!s||e===null||!this.getSourceBufferTypes().length)return;const n=t.config,o=s.currentTime,a=e.levelTargetDuration,l=e.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if($(l)&&l>0){const c=Math.max(l,a),h=Math.floor(o/a)*a-c;this.flushBackBuffer(o,a,h);}if($(n.frontBufferFlushThreshold)&&n.frontBufferFlushThreshold>0){const c=Math.max(n.maxBufferLength,n.frontBufferFlushThreshold),h=Math.max(c,a),u=Math.floor(o/a)*a+h;this.flushFrontBuffer(o,a,u);}}flushBackBuffer(t,e,s){const{details:i,sourceBuffer:n}=this;this.getSourceBufferTypes().forEach(a=>{const l=n[a];if(l){const c=nt.getBuffered(l);if(c.length>0&&s>c.start(0)){if(this.hls.trigger(x.BACK_BUFFER_REACHED,{bufferEnd:s}),i!=null&&i.live)this.hls.trigger(x.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(l.ended&&c.end(c.length-1)-t<e*2){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:a});}}});}flushFrontBuffer(t,e,s){const{sourceBuffer:i}=this;this.getSourceBufferTypes().forEach(o=>{const a=i[o];if(a){const l=nt.getBuffered(a),c=l.length;if(c<2)return;const h=l.start(c-1),u=l.end(c-1);if(s>h||t>=h&&t<=u)return;if(a.ended&&t-u<2*e){this.log(`Cannot flush ${o} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(x.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:o});}});}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:t,hls:e,media:s,mediaSource:i}=this,n=t.fragments[0].start+t.totalduration,o=s.duration,a=$(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(t)):(n>a&&n>o||!$(o))&&(this.log(`Updating Media Source duration to ${n.toFixed(3)}`),i.duration=n);}updateSeekableRange(t){const e=this.mediaSource,s=t.fragments;if(s.length&&t.live&&e!=null&&e.setLiveSeekableRange){const n=Math.max(0,s[0].start),o=Math.max(n,n+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${n}-${o}.`),e.setLiveSeekableRange(n,o);}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,i=Object.keys(s).length;if(i&&(!t||i===2||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(x.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(o=>{e.executeNext(o);});else {const o=new Error("could not create source buffer for media codec(s)");this.hls.trigger(x.ERROR,{type:H.MEDIA_ERROR,details:w.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:true,error:o,reason:o.message});}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const n in t)if(!e[n]){var i;const o=t[n];if(!o)throw Error(`source buffer exists for track ${n}, however track does not`);let a=((i=o.levelCodec)==null?void 0:i.indexOf(","))===-1?o.levelCodec:o.codec;a&&n.slice(0,5)==="audio"&&(a=Ye(a,this.appendSource));const l=`${o.container};codecs=${a}`;this.log(`creating sourceBuffer(${l})`);try{const c=e[n]=s.addSourceBuffer(l),h=n;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(h,"bufferedchange",(u,d)=>{const f=d.removedRanges;f!=null&&f.length&&this.hls.trigger(x.BUFFER_FLUSHED,{type:n});}),this.tracks[n]={buffer:c,codec:a,container:o.container,levelCodec:o.levelCodec,metadata:o.metadata,id:o.id};}catch(c){this.error(`error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger(x.ERROR,{type:H.MEDIA_ERROR,details:w.BUFFER_ADD_CODEC_ERROR,fatal:false,error:c,sourceBufferName:n,mimeType:l});}}}get mediaSrc(){var t;const e=((t=this.media)==null?void 0:t.firstChild)||this.media;return e?.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart();}_onSBUpdateEnd(t){var e;if(((e=this.mediaSource)==null?void 0:e.readyState)==="closed"){this.resetBuffer(t);return}const{operationQueue:s}=this;s.current(t).onComplete(),s.shiftAndExecuteNext(t);}_onSBUpdateError(t,e){var s;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,e),this.hls.trigger(x.ERROR,{type:H.MEDIA_ERROR,details:w.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:false});const n=this.operationQueue.current(t);n&&n.onError(i);}removeExecutor(t,e,s){const{media:i,mediaSource:n,operationQueue:o,sourceBuffer:a}=this,l=a[t];if(!i||!n||!l){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),o.shiftAndExecuteNext(t);return}const c=$(i.duration)?i.duration:1/0,h=$(n.duration)?n.duration:1/0,u=Math.max(0,e),d=Math.min(s,c,h);d>u&&(!l.ending||l.ended)?(l.ended=false,this.log(`Removing [${u},${d}] from the ${t} SourceBuffer`),l.remove(u,d)):o.shiftAndExecuteNext(t);}appendExecutor(t,e){const s=this.sourceBuffer[e];if(!s){if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);return}s.ended=false,s.appendBuffer(t);}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);return}const{operationQueue:s}=this,i=e.map(n=>s.appendBlocker(n));Promise.all(i).then(()=>{t(),e.forEach(n=>{const o=this.sourceBuffer[n];o!=null&&o.updating||s.shiftAndExecuteNext(n);});});}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,s){const i=this.sourceBuffer[t];if(!i)return;const n=s.bind(this,t);this.listeners[t].push({event:e,listener:n}),i.addEventListener(e,n);}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach(s=>{e.removeEventListener(s.event,s.listener);});}}function Xs(r){const t=r.querySelectorAll("source");[].slice.call(t).forEach(e=>{r.removeChild(e);});}function ga(r,t){const e=self.document.createElement("source");e.type="video/mp4",e.src=t,r.appendChild(e);}const ma={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},qi=r=>String.fromCharCode(ma[r]||r),pt=15,Lt=100,pa={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},xa={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ya={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ta={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Sa=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ea{constructor(){this.time=null,this.verboseLevel=0;}log(t,e){if(this.verboseLevel>=t){const s=typeof e=="function"?e():e;b.log(`${this.time} [${t}] ${s}`);}}}const kt=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e};class ji{constructor(){this.foreground="white",this.underline=false,this.italics=false,this.background="black",this.flash=false;}reset(){this.foreground="white",this.underline=false,this.italics=false,this.background="black",this.flash=false;}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let s=0;s<e.length;s++){const i=e[s];t.hasOwnProperty(i)&&(this[i]=t[i]);}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash;}toString(){return "color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class va{constructor(){this.uchar=" ",this.penState=new ji;}reset(){this.uchar=" ",this.penState.reset();}setChar(t,e){this.uchar=t,this.penState.copy(e);}setPenState(t){this.penState.copy(t);}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState);}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Aa{constructor(t){this.chars=[],this.pos=0,this.currPenState=new ji,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Lt;e++)this.chars.push(new va);this.logger=t;}equals(t){for(let e=0;e<Lt;e++)if(!this.chars[e].equals(t.chars[e]))return  false;return  true}copy(t){for(let e=0;e<Lt;e++)this.chars[e].copy(t.chars[e]);}isEmpty(){let t=true;for(let e=0;e<Lt;e++)if(!this.chars[e].isEmpty()){t=false;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Lt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Lt);}moveCursor(t){const e=this.pos+t;if(t>1)for(let s=this.pos+1;s<e+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(e);}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState);}insertChar(t){t>=144&&this.backSpace();const e=qi(t);if(this.pos>=Lt){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1);}clearFromPos(t){let e;for(e=t;e<Lt;e++)this.chars[e].reset();}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset();}clearToEndOfRow(){this.clearFromPos(this.pos);}getTextString(){const t=[];let e=true;for(let s=0;s<Lt;s++){const i=this.chars[s].uchar;i!==" "&&(e=false),t.push(i);}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState);}}class Me{constructor(t){this.rows=[],this.currRow=pt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<pt;e++)this.rows.push(new Aa(t));this.logger=t;}reset(){for(let t=0;t<pt;t++)this.rows[t].clear();this.currRow=pt-1;}equals(t){let e=true;for(let s=0;s<pt;s++)if(!this.rows[s].equals(t.rows[s])){e=false;break}return e}copy(t){for(let e=0;e<pt;e++)this.rows[e].copy(t.rows[e]);}isEmpty(){let t=true;for(let e=0;e<pt;e++)if(!this.rows[e].isEmpty()){t=false;break}return t}backSpace(){this.rows[this.currRow].backSpace();}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow();}insertChar(t){this.rows[this.currRow].insertChar(t);}setPen(t){this.rows[this.currRow].setPenStyles(t);}moveCursor(t){this.rows[this.currRow].moveCursor(t);}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t);}setPAC(t){this.logger.log(2,()=>"pacData = "+JSON.stringify(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let a=0;a<pt;a++)this.rows[a].clear();const n=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[n].cueStartTime,l=this.logger.time;if(a!==null&&l!==null&&a<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[e-this.nrRollUpRows+c+1].copy(o.rows[n+c]);}}this.currRow=e;const s=this.rows[this.currRow];if(t.indent!==null){const n=t.indent,o=Math.max(n-1,0);s.setCursor(t.indent),t.color=s.chars[o].penState.foreground;}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:false};this.setPen(i);}setBkgData(t){this.logger.log(2,()=>"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32);}setRollUpRows(t){this.nrRollUpRows=t;}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up");}getDisplayText(t){t=t||false;const e=[];let s="",i=-1;for(let n=0;n<pt;n++){const o=this.rows[n].getTextString();o&&(i=n+1,t?e.push("Row "+i+": '"+o+"'"):e.push(o.trim()));}return e.length>0&&(t?s="["+e.join(" | ")+"]":s=e.join(`
`)),s}getTextAndFormat(){return this.rows}}class Qs{constructor(t,e,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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Me(s),this.nonDisplayedMemory=new Me(s),this.lastOutputScreen=new Me(s),this.currRollUpRow=this.displayedMemory.rows[pt-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[pt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null;}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t;}setPAC(t){this.writeScreen.setPAC(t);}setBkgData(t){this.writeScreen.setBkgData(t);}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),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=t);}insertChars(t){for(let s=0;s<t.length;s++)this.writeScreen.insertChar(t[s]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(true)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(true)),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(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t);}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:true});}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(true);}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(true);}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 t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText());}this.outputDataUpdate(true);}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t);}ccMIDROW(t){const e={flash:false};if(e.underline=t%2===1,e.italics=t>=46,e.italics)e.foreground="white";else {const s=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s];}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e);}outputDataUpdate(t=false){const e=this.logger.time;e!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=e:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e),this.lastOutputScreen.copy(this.displayedMemory));}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t));}}class Zs{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Ra(),this.logger=void 0;const i=this.logger=new Ea;this.channels=[null,new Qs(t,e,i),new Qs(t+1,s,i)];}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e);}addData(t,e){this.logger.time=t;for(let s=0;s<e.length;s+=2){const i=e[s]&127,n=e[s+1]&127;let o=false,a=null;if(i===0&&n===0)continue;this.logger.log(3,()=>"["+kt([e[s],e[s+1]])+"] -> ("+kt([i,n])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(ba(i,n,l)){ie(null,null,l),this.logger.log(3,()=>"Repeated command ("+kt([i,n])+") is dropped");continue}ie(i,n,this.cmdHistory),o=this.parseCmd(i,n),o||(o=this.parseMidrow(i,n)),o||(o=this.parsePAC(i,n)),o||(o=this.parseBackgroundAttributes(i,n));}else ie(null,null,l);if(!o&&(a=this.parseChars(i,n),a)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?");}!o&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+kt([i,n])+" orig: "+kt([e[s],e[s+1]]));}}parseCmd(t,e){const s=(t===20||t===28||t===21||t===29)&&e>=32&&e<=47,i=(t===23||t===31)&&e>=33&&e<=35;if(!(s||i))return  false;const n=t===20||t===21||t===23?1:2,o=this.channels[n];return t===20||t===21||t===28||t===29?e===32?o.ccRCL():e===33?o.ccBS():e===34?o.ccAOF():e===35?o.ccAON():e===36?o.ccDER():e===37?o.ccRU(2):e===38?o.ccRU(3):e===39?o.ccRU(4):e===40?o.ccFON():e===41?o.ccRDC():e===42?o.ccTR():e===43?o.ccRTD():e===44?o.ccEDM():e===45?o.ccCR():e===46?o.ccENM():e===47&&o.ccEOC():o.ccTO(e-32),this.currentChannel=n,true}parseMidrow(t,e){let s=0;if((t===17||t===25)&&e>=32&&e<=47){if(t===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),false;const i=this.channels[s];return i?(i.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+kt([t,e])+")"),true):false}return  false}parsePAC(t,e){let s;const i=(t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127,n=(t===16||t===24)&&e>=64&&e<=95;if(!(i||n))return  false;const o=t<=23?1:2;e>=64&&e<=95?s=o===1?pa[t]:ya[t]:s=o===1?xa[t]:Ta[t];const a=this.channels[o];return a?(a.setPAC(this.interpretPAC(s,e)),this.currentChannel=o,true):false}interpretPAC(t,e){let s;const i={color:null,italics:false,indent:null,underline:false,row:t};return e>95?s=e-96:s=e-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=true,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(t,e){let s,i=null,n=null;if(t>=25?(s=2,n=t-8):(s=1,n=t),n>=17&&n<=19){let o;n===17?o=e+80:n===18?o=e+112:o=e+144,this.logger.log(2,()=>"Special char '"+qi(o)+"' in channel "+s),i=[o];}else t>=32&&t<=127&&(i=e===0?[t]:[t,e]);return i&&this.logger.log(3,()=>"Char codes =  "+kt(i).join(",")),i}parseBackgroundAttributes(t,e){const s=(t===16||t===24)&&e>=32&&e<=47,i=(t===23||t===31)&&e>=45&&e<=47;if(!(s||i))return  false;let n;const o={};t===16||t===24?(n=Math.floor((e-32)/2),o.background=Sa[n],e%2===1&&(o.background=o.background+"_semi")):e===45?o.background="transparent":(o.foreground="black",e===47&&(o.underline=true));const a=t<=23?1:2;return this.channels[a].setBkgData(o),true}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset();}ie(null,null,this.cmdHistory);}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t);}}}function ie(r,t,e){e.a=r,e.b=t;}function ba(r,t,e){return e.a===r&&e.b===t}function Ra(){return {a:null,b:null}}class ne{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e;}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null);}newCue(t,e,s){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName);}reset(){this.cueRanges=[],this.startTime=null;}}var ds=(function(){if(Kt!=null&&Kt.VTTCue)return self.VTTCue;const r=["","lr","rl"],t=["start","middle","end","left","right"];function e(a,l){if(typeof l!="string"||!Array.isArray(a))return  false;const c=l.toLowerCase();return ~a.indexOf(c)?c:false}function s(a){return e(r,a)}function i(a){return e(t,a)}function n(a,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const u in h)a[u]=h[u];}return a}function o(a,l,c){const h=this,u={enumerable:true};h.hasBeenReset=false;let d="",f=false,g=a,m=l,p=c,y=null,A="",T=true,R="auto",E="start",I=50,v="middle",C=50,P="middle";Object.defineProperty(h,"id",n({},u,{get:function(){return d},set:function(L){d=""+L;}})),Object.defineProperty(h,"pauseOnExit",n({},u,{get:function(){return f},set:function(L){f=!!L;}})),Object.defineProperty(h,"startTime",n({},u,{get:function(){return g},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");g=L,this.hasBeenReset=true;}})),Object.defineProperty(h,"endTime",n({},u,{get:function(){return m},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");m=L,this.hasBeenReset=true;}})),Object.defineProperty(h,"text",n({},u,{get:function(){return p},set:function(L){p=""+L,this.hasBeenReset=true;}})),Object.defineProperty(h,"region",n({},u,{get:function(){return y},set:function(L){y=L,this.hasBeenReset=true;}})),Object.defineProperty(h,"vertical",n({},u,{get:function(){return A},set:function(L){const _=s(L);if(_===false)throw new SyntaxError("An invalid or illegal string was specified.");A=_,this.hasBeenReset=true;}})),Object.defineProperty(h,"snapToLines",n({},u,{get:function(){return T},set:function(L){T=!!L,this.hasBeenReset=true;}})),Object.defineProperty(h,"line",n({},u,{get:function(){return R},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");R=L,this.hasBeenReset=true;}})),Object.defineProperty(h,"lineAlign",n({},u,{get:function(){return E},set:function(L){const _=i(L);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");E=_,this.hasBeenReset=true;}})),Object.defineProperty(h,"position",n({},u,{get:function(){return I},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");I=L,this.hasBeenReset=true;}})),Object.defineProperty(h,"positionAlign",n({},u,{get:function(){return v},set:function(L){const _=i(L);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");v=_,this.hasBeenReset=true;}})),Object.defineProperty(h,"size",n({},u,{get:function(){return C},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");C=L,this.hasBeenReset=true;}})),Object.defineProperty(h,"align",n({},u,{get:function(){return P},set:function(L){const _=i(L);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");P=_,this.hasBeenReset=true;}})),h.displayState=void 0;}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})();class La{decode(t,e){if(!t)return "";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Xi(r){function t(s,i,n,o){return (s|0)*3600+(i|0)*60+(n|0)+parseFloat(o||0)}const e=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return e?parseFloat(e[2])>59?t(e[2],e[3],0,e[4]):t(e[1],e[2],e[3],e[4]):null}class Ia{constructor(){this.values=Object.create(null);}set(t,e){!this.get(t)&&e!==""&&(this.values[t]=e);}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i<s.length;++i)if(e===s[i]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10));}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),true}return  false}}function Qi(r,t,e,s){const i=s?r.split(s):[r];for(const n in i){if(typeof i[n]!="string")continue;const o=i[n].split(e);if(o.length!==2)continue;const a=o[0],l=o[1];t(a,l);}}const Qe=new ds(0,0,""),re=Qe.align==="middle"?"middle":"center";function wa(r,t,e){const s=r;function i(){const a=Xi(r);if(a===null)throw new Error("Malformed timestamp: "+s);return r=r.replace(/^[^\sa-zA-Z-]+/,""),a}function n(a,l){const c=new Ia;Qi(a,function(d,f){let g;switch(d){case "region":for(let m=e.length-1;m>=0;m--)if(e[m].id===f){c.set(d,e[m].region);break}break;case "vertical":c.alt(d,f,["rl","lr"]);break;case "line":g=f.split(","),c.integer(d,g[0]),c.percent(d,g[0])&&c.set("snapToLines",false),c.alt(d,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",re,"end"]);break;case "position":g=f.split(","),c.percent(d,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",re,"end","line-left","line-right","auto"]);break;case "size":c.percent(d,f);break;case "align":c.alt(d,f,["start",re,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");h==="auto"&&Qe.line===-1&&(h=-1),l.line=h,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",true),l.size=c.get("size",100),l.align=c.get("align",re);let u=c.get("position","auto");u==="auto"&&Qe.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u;}function o(){r=r.replace(/^\s+/,"");}if(o(),t.startTime=i(),o(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);r=r.slice(3),o(),t.endTime=i(),o(),n(r,t);}function Zi(r){return r.replace(/<br(?: \/)?>/gi,`
`)}class Da{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new La,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0;}parse(t){const e=this;t&&(e.buffer+=e.decoder.decode(t,{stream:true}));function s(){let n=e.buffer,o=0;for(n=Zi(n);o<n.length&&n[o]!=="\r"&&n[o]!==`
`;)++o;const a=n.slice(0,o);return n[o]==="\r"&&++o,n[o]===`
`&&++o,e.buffer=n.slice(o),a}function i(n){Qi(n,function(o,a){},/:/);}try{let n="";if(e.state==="INITIAL"){if(!/\r\n|\n/.test(e.buffer))return this;n=s();const a=n.match(/^(ï»¿)?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");e.state="HEADER";}let o=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(o?o=!1:n=s(),e.state){case "HEADER":/:/.test(n)?i(n):n||(e.state="ID");continue;case "NOTE":n||(e.state="ID");continue;case "ID":if(/^NOTE($|[ \t])/.test(n)){e.state="NOTE";break}if(!n)continue;if(e.cue=new ds(0,0,""),e.state="CUE",n.indexOf("-->")===-1){e.cue.id=n;continue}case "CUE":if(!e.cue){e.state="BADCUE";continue}try{wa(n,e.cue,e.regionList);}catch{e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case "CUETEXT":{const a=n.indexOf("-->")!==-1;if(!n||a&&(o=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(e.cue===null)continue;e.cue.text&&(e.cue.text+=`
`),e.cue.text+=n;}continue;case "BADCUE":n||(e.state="ID");}}}catch{e.state==="CUETEXT"&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state=e.state==="INITIAL"?"BADWEBVTT":"BADCUE";}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=`

`,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e);}return t.onflush&&t.onflush(),this}}const Ca=/\r\n|\n\r|\n|\r/g,Ne=function(t,e,s=0){return t.slice(s,s+e.length)===e},_a=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!$(e)||!$(s)||!$(i)||!$(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=60*1e3*i,e+=3600*1e3*n,e},Ue=function(t){let e=5381,s=t.length;for(;s;)e=e*33^t.charCodeAt(--s);return (e>>>0).toString()};function fs(r,t,e){return Ue(r.toString())+Ue(t.toString())+Ue(e)}const ka=function(t,e,s){let i=t[e],n=t[i.prevCC];if(!n||!n.new&&i.new){t.ccOffset=t.presentationOffset=i.start,i.new=false;return}for(;(o=n)!=null&&o.new;){var o;t.ccOffset+=i.start-n.start,i.new=false,i=n,n=t[i.prevCC];}t.presentationOffset=s;};function Pa(r,t,e,s,i,n,o){const a=new Da,l=At(new Uint8Array(r)).trim().replace(Ca,`
`).split(`
`),c=[],h=t?jo(t.baseTime,t.timescale):0;let u="00:00.000",d=0,f=0,g,m=true;a.oncue=function(p){const y=e[s];let A=e.ccOffset;const T=(d-h)/9e4;if(y!=null&&y.new&&(f!==void 0?A=e.ccOffset=y.start:ka(e,s,T)),T){if(!t){g=new Error("Missing initPTS for VTT MPEGTS");return}A=T-e.presentationOffset;}const R=p.endTime-p.startTime,E=ft((p.startTime+A-f)*9e4,i*9e4)/9e4;p.startTime=Math.max(E,0),p.endTime=Math.max(E+R,0);const I=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(I)),p.id||(p.id=fs(p.startTime,p.endTime,I)),p.endTime>0&&c.push(p);},a.onparsingerror=function(p){g=p;},a.onflush=function(){if(g){o(g);return}n(c);},l.forEach(p=>{if(m)if(Ne(p,"X-TIMESTAMP-MAP=")){m=false,p.slice(16).split(",").forEach(y=>{Ne(y,"LOCAL:")?u=y.slice(6):Ne(y,"MPEGTS:")&&(d=parseInt(y.slice(7)));});try{f=_a(u)/1e3;}catch(y){g=y;}return}else p===""&&(m=false);a.parse(p+`
`);}),a.flush();}const Be="stpp.ttml.im1t",Ji=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,tn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Fa={left:"start",center:"center",right:"end",start:"start",end:"end"};function Js(r,t,e,s){const i=K(new Uint8Array(r),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const n=i.map(a=>At(a)),o=qo(t.baseTime,1,t.timescale);try{n.forEach(a=>e(Oa(a,o)));}catch(a){s(a);}}function Oa(r,t){const i=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(n).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||n[d],u),{}),a=i.getAttribute("xml:space")!=="preserve",l=ti($e(i,"styling","style")),c=ti($e(i,"layout","region")),h=$e(i,"body","[begin]");return [].map.call(h,u=>{const d=en(u,a);if(!d||!u.hasAttribute("begin"))return null;const f=Ke(u.getAttribute("begin"),o),g=Ke(u.getAttribute("dur"),o);let m=Ke(u.getAttribute("end"),o);if(f===null)throw ei(u);if(m===null){if(g===null)throw ei(u);m=f+g;}const p=new ds(f-t,m-t,d);p.id=fs(p.startTime,p.endTime,p.text);const y=c[u.getAttribute("region")],A=l[u.getAttribute("style")],T=Ma(y,A,l),{textAlign:R}=T;if(R){const E=Fa[R];E&&(p.lineAlign=E),p.align=R;}return ct(p,T),p}).filter(u=>u!==null)}function $e(r,t,e){const s=r.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(e)):[]}function ti(r){return r.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function en(r,t){return [].slice.call(r.childNodes).reduce((e,s,i)=>{var n;return s.nodeName==="br"&&i?e+`
`:(n=s.childNodes)!=null&&n.length?en(s,t):t?e+s.textContent.trim().replace(/\s+/g," "):e+s.textContent},"")}function Ma(r,t,e){const s="http://www.w3.org/ns/ttml#styling";let i=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return o&&e.hasOwnProperty(o)&&(i=e[o]),n.reduce((a,l)=>{const c=Ge(t,s,l)||Ge(r,s,l)||Ge(i,s,l);return c&&(a[l]=c),a},{})}function Ge(r,t,e){return r&&r.hasAttributeNS(t,e)?r.getAttributeNS(t,e):null}function ei(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Ke(r,t){if(!r)return null;let e=Xi(r);return e===null&&(Ji.test(r)?e=Na(r,t):tn.test(r)&&(e=Ua(r,t))),e}function Na(r,t){const e=Ji.exec(r),s=(e[4]|0)+(e[5]|0)/t.subFrameRate;return (e[1]|0)*3600+(e[2]|0)*60+(e[3]|0)+s/t.frameRate}function Ua(r,t){const e=tn.exec(r),s=Number(e[1]);switch(e[2]){case "h":return s*3600;case "m":return s*60;case "ms":return s*1e3;case "f":return s/t.frameRate;case "t":return s/t.tickRate}return s}class Ba{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=true,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=ii(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.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}},t.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(x.FRAG_LOADING,this.onFragLoading,this),t.on(x.FRAG_LOADED,this.onFragLoaded,this),t.on(x.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(x.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(x.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(x.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this);}destroy(){const{hls:t}=this;t.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(x.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(x.FRAG_LOADING,this.onFragLoading,this),t.off(x.FRAG_LOADED,this.onFragLoaded,this),t.off(x.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(x.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(x.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(x.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0;}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new ne(this,"textTrack1"),e=new ne(this,"textTrack2"),s=new ne(this,"textTrack3"),i=new ne(this,"textTrack4");this.cea608Parser1=new Zs(1,t,e),this.cea608Parser2=new Zs(3,s,i);}}addCues(t,e,s,i,n){let o=false;for(let a=n.length;a--;){const l=n[a],c=$a(l[0],l[1],e,s);if(c>=0&&(l[0]=Math.min(l[0],e),l[1]=Math.max(l[1],s),o=true,c/(s-e)>.5))return}if(o||n.push([e,s]),this.config.renderTextTracksNatively){const a=this.captionsTracks[t];this.Cues.newCue(a,e,s,i);}else {const a=this.Cues.newCue(null,e,s,i);this.hls.trigger(x.CUES_PARSED,{type:"captions",cues:a,track:t});}}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:n}){const{unparsedVttFrags:o}=this;s==="main"&&(this.initPTS[e.cc]={baseTime:i,timescale:n}),o.length&&(this.unparsedVttFrags=[],o.forEach(a=>{this.onFragLoaded(x.FRAG_LOADED,a);}));}getExistingTrack(t,e){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const n=s.textTracks[i];if(si(n,{name:t,lang:e}))return n}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t);}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,media:i}=this,{label:n,languageCode:o}=e[t],a=this.getExistingTrack(n,o);if(a)s[t]=a,qt(s[t]),kr(s[t],i);else {const l=this.createTextTrack("captions",n,o);l&&(l[t]=true,s[t]=l);}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s=e.label,i={_id:t,label:s,kind:"captions",default:e.media?!!e.media.default:false,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(x.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]});}createTextTrack(t,e,s){const i=this.media;if(i)return i.addTextTrack(t,e,s)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks();}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach(e=>{qt(t[e]),delete t[e];}),this.nonNativeCaptionsTracks={};}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ii(),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:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let s=0;s<e.length;s++)qt(e[s]);}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[],i=s.some(n=>n.textCodec===Be);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(zi(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const o=this.media,a=o?ce(o.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(a){let u=null;for(let d=0;d<a.length;d++)if(a[d]&&si(a[d],l)){u=a[d],a[d]=null;break}u&&(h=u);}if(h)qt(h);else {const u=sn(l);h=this.createTextTrack(u,l.name,l.lang),h&&(h.mode="disabled");}h&&this.textTracks.push(h);}),a!=null&&a.length){const l=a.filter(c=>c!==null).map(c=>c.label);l.length&&b.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);}}else if(this.tracks.length){const o=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(x.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o});}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const n=`textTrack${i[1]}`,o=this.captionsProperties[n];o&&(o.label=s.name,s.lang&&(o.languageCode=s.lang),o.media=s);});}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return e?.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===W.MAIN){var s,i;const{cea608Parser1:n,cea608Parser2:o,lastSn:a}=this,{cc:l,sn:c}=e.frag,h=(s=(i=e.part)==null?void 0:i.index)!=null?s:-1;n&&o&&(c!==a+1||c===a&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),o.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h;}}onFragLoaded(t,e){const{frag:s,payload:i}=e;if(s.type===W.SUBTITLE)if(i.byteLength){const n=s.decryptdata,o="stats"in e;if(n==null||!n.encrypted||o){const a=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:true},this.prevCC=s.cc),a&&a.textCodec===Be?this._parseIMSC1(s,i):this._parseVTTs(e);}}else this.hls.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:false,frag:s,error:new Error("Empty subtitle payload")});}_parseIMSC1(t,e){const s=this.hls;Js(e,this.initPTS[t.cc],i=>{this._appendCues(i,t.level),s.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:true,frag:t});},i=>{b.log(`Failed to parse IMSC1: ${i}`),s.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:false,frag:t,error:i});});}_parseVTTs(t){var e;const{frag:s,payload:i}=t,{initPTS:n,unparsedVttFrags:o}=this,a=n.length-1;if(!n[s.cc]&&a===-1){o.push(t);return}const l=this.hls,c=(e=s.initSegment)!=null&&e.data?gt(s.initSegment.data,new Uint8Array(i)):i;Pa(c,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),l.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:true,frag:s});},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?o.push(t):this._fallbackToIMSC1(s,i),b.log(`Failed to parse VTT cue: ${h}`),!(u&&a>s.cc)&&l.trigger(x.SUBTITLE_FRAG_PROCESSED,{success:false,frag:s,error:h});});}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||Js(e,this.initPTS[t.cc],()=>{s.textCodec=Be,this._parseIMSC1(t,e);},()=>{s.textCodec="wvtt";});}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||i.mode==="disabled")return;t.forEach(n=>Ei(i,n));}else {const i=this.tracks[e];if(!i)return;const n=i.default?"default":"subtitles"+e;s.trigger(x.CUES_PARSED,{type:"subtitles",cues:t,track:n});}}onFragDecrypted(t,e){const{frag:s}=e;s.type===W.SUBTITLE&&this.onFragLoaded(x.FRAG_LOADED,e);}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={};}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:i}=this;if(!this.enabled||!s||!i)return;const{frag:n,samples:o}=e;if(!(n.type===W.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let a=0;a<o.length;a++){const l=o[a].bytes;if(l){const c=this.extractCea608Data(l);s.addData(o[a].pts,c[0]),i.addData(o[a].pts,c[1]);}}}onBufferFlushing(t,{startOffset:e,endOffset:s,endOffsetSubtitles:i,type:n}){const{media:o}=this;if(!(!o||o.currentTime<s)){if(!n||n==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(l=>Is(a[l],e,s));}if(this.config.renderTextTracksNatively&&e===0&&i!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(l=>Is(a[l],e,i));}}}extractCea608Data(t){const e=[[],[]],s=t[0]&31;let i=2;for(let n=0;n<s;n++){const o=t[i++],a=127&t[i++],l=127&t[i++];if(a===0&&l===0)continue;if((4&o)!==0){const h=3&o;(h===0||h===1)&&(e[h].push(a),e[h].push(l));}}return e}}function sn(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function si(r,t){return !!r&&r.kind===sn(t)&&Xe(t,r)}function $a(r,t,e,s){return Math.min(t,s)-Math.max(r,e)}function ii(){return {ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:true}}}class gs{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners();}setStreamController(t){this.streamController=t;}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null;}registerListeners(){const{hls:t}=this;t.on(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(x.MANIFEST_PARSED,this.onManifestParsed,this),t.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(x.BUFFER_CODECS,this.onBufferCodecs,this),t.on(x.MEDIA_DETACHING,this.onMediaDetaching,this);}unregisterListener(){const{hls:t}=this;t.off(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(x.MANIFEST_PARSED,this.onManifestParsed,this),t.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(x.BUFFER_CODECS,this.onBufferCodecs,this),t.off(x.MEDIA_DETACHING,this.onMediaDetaching,this);}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width});}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize();}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping();}onLevelsUpdated(t,e){this.timer&&$(this.autoLevelCapping)&&this.detectPlayerSize();}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping();}onMediaDetaching(){this.stopCapping();}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&b.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping;}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return  -1;const s=e.filter((i,n)=>this.isLevelAllowed(i)&&n<=t);return this.clientRect=null,gs.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 t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,!e.width&&!e.height&&(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0);}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio;}catch{}return t}isLevelAllowed(t){return !this.restrictedLevels.some(s=>t.bitrate===s.bitrate&&t.width===s.width&&t.height===s.height)}static getMaxLevelByMediaSize(t,e,s){if(!(t!=null&&t.length))return  -1;const i=(a,l)=>l?a.width!==l.width||a.height!==l.height:true;let n=t.length-1;const o=Math.max(e,s);for(let a=0;a<t.length;a+=1){const l=t[a];if((l.width>=o||l.height>=o)&&i(l,t[a+1])){n=a;break}}return n}}class Ga{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=false,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners();}setStreamController(t){this.streamController=t;}registerListeners(){this.hls.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this);}unregisterListeners(){this.hls.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this);}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=false,this.media=null;}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=true),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod);}}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const n=i-this.lastTime,o=s-this.lastDroppedFrames,a=e-this.lastDecodedFrames,l=1e3*o/n,c=this.hls;if(c.trigger(x.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:s}),l>0&&o>c.config.fpsDroppedMonitoringThreshold*a){let h=c.currentLevel;b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h)&&(h=h-1,c.trigger(x.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch());}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=e;}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames);}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount);}}const oe="[eme]";class Gt{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Gt.CDMCleanupPromise?[Gt.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=b.debug.bind(b,oe),this.log=b.log.bind(b,oe),this.warn=b.warn.bind(b,oe),this.error=b.error.bind(b,oe),this.hls=t,this.config=t.config,this.registerListeners();}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null;}registerListeners(){this.hls.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(x.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(x.MANIFEST_LOADED,this.onManifestLoaded,this);}unregisterListeners(){this.hls.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(x.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(x.MANIFEST_LOADED,this.onManifestLoaded,this);}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,i=e[t];if(i)return i.licenseUrl;if(t===J.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`);}attemptKeySystemAccess(t){const e=this.hls.levels,s=(o,a,l)=>!!o&&l.indexOf(o)===a,i=e.map(o=>o.audioCodec).filter(s),n=e.map(o=>o.videoCodec).filter(s);return i.length+n.length===0&&n.push("avc1.42e01e"),new Promise((o,a)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,i,n).then(u=>o({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof dt?a(u):a(new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:u,fatal:true},u.message));});};l(t);})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return di===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(t,e)}getMediaKeysPromise(t,e,s){const i=Jn(t,e,s,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t];let o=n?.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(i)}`),o=this.requestMediaKeySystemAccess(t,i);const a=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${t}": ${l}`);}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),a.mediaKeys=l.createMediaKeys().then(h=>(this.log(`Media-keys created for "${t}"`),c.then(u=>u?this.setMediaKeysServerCertificate(h,t,u):h))),a.mediaKeys.catch(h=>{this.error(`Failed to create media-keys for "${t}"}: ${h}`);}),a.mediaKeys})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${St.hexDump(t.keyId||[])}`);const i=s.createSession(),n={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),i=this.getKeyIdString(e),n="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,n,e.pssh,"expired");}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t);}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return St.hexDump(t.keyId)}updateKeySession(t,e){var s;const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${St.hexDump(((s=t.decryptdata)==null?void 0:s.keyId)||[])}
      } (data length: ${e&&e.byteLength})`),i.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise((e,s)=>{const i=Ie(this.config),n=t.map(Ss).filter(o=>!!o&&i.indexOf(o)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:o})=>{const a=Es(o);a?e(a):s(new Error(`Unable to find format for key-system "${o}"`));}).catch(s)})}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),i=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${i}`);let n=this.keyIdToKeySessionPromise[s];return n||(n=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(e).then(({keySystem:o,mediaKeys:a})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(o,a).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:o,mediaKeys:a,decryptdata:e});return this.generateRequestWithPreferredKeySession(l,"cenc",e.pssh,"playlist-key")}))),n.catch(o=>this.handleError(o))),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof dt?this.hls.trigger(x.ERROR,t.data):this.hls.trigger(x.ERROR,{type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:t,fatal:true}));}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const i=Ss(t.keyFormat),n=i?[i]:Ie(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=Ie(this.config)),t.length===0)throw new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:true},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:s}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),s===null)return;let i,n;if(e==="sinf"&&this.config.drmSystems[J.FAIRPLAY]){const h=st(new Uint8Array(s));try{const u=is(JSON.parse(h).sinf),d=yi(new Uint8Array(u));if(!d)return;i=d.subarray(8,24),n=J.FAIRPLAY;}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else {const h=Lr(s);if(h===null)return;h.version===0&&h.systemId===ui.WIDEVINE&&h.data&&(i=h.data.subarray(8,24)),n=Zn(h.systemId);}if(!n||!i)return;const o=St.hexDump(i),{keyIdToKeySessionPromise:a,mediaKeySessions:l}=this;let c=a[o];for(let h=0;h<l.length;h++){const u=l[h],d=u.decryptdata;if(d.pssh||!d.keyId)continue;const f=St.hexDump(d.keyId);if(o===f||d.uri.replace(/-/g,"").indexOf(o)!==-1){c=a[f],delete a[f],d.pssh=new Uint8Array(s),d.keyId=i,c=a[o]=c.then(()=>this.generateRequestWithPreferredKeySession(u,e,s,"encrypted-event-key-match"));break}}c||(c=a[o]=this.getKeySystemSelectionPromise([n]).then(({keySystem:h,mediaKeys:u})=>{var d;this.throwIfDestroyed();const f=new xe("ISO-23001-7",o,(d=Es(h))!=null?d:"");return f.pssh=new Uint8Array(s),f.keyId=i,this.attemptSetMediaKeys(h,u).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:h,mediaKeys:u});return this.generateRequestWithPreferredKeySession(g,e,s,"encrypted-event-no-match")})})),c.catch(h=>this.handleError(h));}_onWaitingForKey(t){this.log(`"${t.type}" event`);}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1);})}generateRequestWithPreferredKeySession(t,e,s,i){var n,o;const a=(n=this.config.drmSystems)==null||(o=n[t.keySystem])==null?void 0:o.generateRequest;if(a)try{const g=a.call(this.hls,e,s,t);if(!g)throw new Error("Invalid response from configured generateRequest filter");e=g.initDataType,s=t.decryptdata.pssh=g.initData?new Uint8Array(g.initData):null;}catch(g){var l;if(this.warn(g.message),(l=this.hls)!=null&&l.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t);const c=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${i}": ${c} (init data type: ${e} length: ${s?s.byteLength:null})`);const h=new Yi,u=t._onmessage=g=>{const m=t.mediaKeysSession;if(!m){h.emit("error",new Error("invalid state"));return}const{messageType:p,message:y}=g;this.log(`"${p}" message event for session "${m.sessionId}" message size: ${y.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(t,y).catch(A=>{this.handleError(A),h.emit("error",A);}):p==="license-release"?t.keySystem===J.FAIRPLAY&&(this.updateKeySession(t,He("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${p}"`);},d=t._onkeystatuseschange=g=>{if(!t.mediaKeysSession){h.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(t);const p=t.keyStatus;h.emit("keyStatus",p),p==="expired"&&(this.warn(`${t.keySystem} expired for key ${c}`),this.renewKeySession(t));};t.mediaKeysSession.addEventListener("message",u),t.mediaKeysSession.addEventListener("keystatuseschange",d);const f=new Promise((g,m)=>{h.on("error",m),h.on("keyStatus",p=>{p.startsWith("usable")?g():p==="output-restricted"?m(new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:false},"HDCP level output restricted")):p==="internal-error"?m(new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:true},`key status changed to "${p}"`)):p==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`);});});return t.mediaKeysSession.generateRequest(e,s).then(()=>{var g;this.log(`Request generated for key-session "${(g=t.mediaKeysSession)==null?void 0:g.sessionId}" keyId: ${c}`);}).catch(g=>{throw new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:g,fatal:false},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>{throw h.removeAllListeners(),this.removeSession(t),g}).then(()=>(h.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${St.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${St.hexDump(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e;});}fetchServerCertificate(t){const e=this.config,s=e.loader,i=new s(e),n=this.getServerCertificateUrl(t);return n?(this.log(`Fetching server certificate for "${t}"`),new Promise((o,a)=>{const l={responseType:"arraybuffer",url:n},c=e.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,m)=>{o(d.data);},onError:(d,f,g,m)=>{a(new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:g,response:ut({url:l.url,data:void 0},d)},`"${t}" certificate request failed (${n}). Status: ${d.code} (${d.text})`));},onTimeout:(d,f,g)=>{a(new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:g,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${n})`));},onAbort:(d,f,g)=>{a(new Error("aborted"));}};i.load(l,h,u);})):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise((i,n)=>{t.setServerCertificate(s).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${s?.byteLength}) on "${e}"`),i(t);}).catch(o=>{n(new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:true},o.message));});})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(s=>this.updateKeySession(t,new Uint8Array(s)).catch(i=>{throw new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:true},i.message)}))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=new DOMParser().parseFromString(s,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0){let h;for(let u=0,d=n.length;u<d;u++){var o,a;h=n[u];const f=(o=h.querySelector("name"))==null?void 0:o.textContent,g=(a=h.querySelector("value"))==null?void 0:a.textContent;f&&g&&t.setRequestHeader(f,g);}}const l=i.querySelector("Challenge"),c=l?.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return He(atob(c))}setupLicenseXHR(t,e,s,i){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,e,s,i)}).catch(o=>{if(!s.decryptdata)throw o;return t.open("POST",e,true),n.call(this.hls,t,e,s,i)}).then(o=>(t.readyState||t.open("POST",e,true),{xhr:t,licenseChallenge:o||i})):(t.open("POST",e,true),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise((i,n)=>{const o=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${o}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(a.readyState===4)if(a.status===200){this._requestLicenseFailureCount=0;let l=a.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,a,o,t);}catch(h){this.error(h);}i(l);}else {const l=s.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||a.status>=400&&a.status<500)n(new dt({type:H.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:true,networkDetails:a,response:{url:o,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${o}). Status: ${a.status} (${a.statusText})`));else {const h=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(t,e).then(i,n);}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,o,t,e).then(({xhr:l,licenseChallenge:c})=>{t.keySystem==J.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c);});})}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey);}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},xe.clearKeyUriToKeyIdMap();const s=e.length;Gt.CDMCleanupPromise=Promise.all(e.map(i=>this.removeSession(i)).concat(t?.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}`);}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0);}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}`);});}onManifestLoading(){this.keyFormatPromise=null;}onManifestLoaded(t,{sessionKeys:e}){if(!(!e||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=e.reduce((i,n)=>(i.indexOf(n.keyFormat)===-1&&i.push(n.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s);}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);return i>-1&&this.mediaKeySessions.splice(i,1),e.remove().catch(n=>{this.log(`Could not remove session: ${n}`);}).then(()=>e.close()).catch(n=>{this.log(`Could not close session: ${n}`);})}}}Gt.CDMCleanupPromise=void 0;class dt extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error;}}var at;(function(r){r.MANIFEST="m",r.AUDIO="a",r.VIDEO="v",r.MUXED="av",r.INIT="i",r.CAPTION="c",r.TIMED_TEXT="tt",r.KEY="k",r.OTHER="o";})(at||(at={}));var Ze;(function(r){r.DASH="d",r.HLS="h",r.SMOOTH="s",r.OTHER="o";})(Ze||(Ze={}));var Pt;(function(r){r.OBJECT="CMCD-Object",r.REQUEST="CMCD-Request",r.SESSION="CMCD-Session",r.STATUS="CMCD-Status";})(Pt||(Pt={}));const Ka={[Pt.OBJECT]:["br","d","ot","tb"],[Pt.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Pt.SESSION]:["cid","pr","sf","sid","st","v"],[Pt.STATUS]:["bs","rtp"]};class Ht{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map(s=>s instanceof Ht?s:new Ht(s))),this.value=t,this.params=e;}}class nn{constructor(t){this.description=void 0,this.description=t;}}const Va="Dict";function Ha(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function Wa(r,t,e,s){return new Error(`failed to ${r} "${Ha(t)}" as ${e}`,{cause:s})}const ni="Bare Item",Ya="Boolean",za="Byte Sequence",qa="Decimal",ja="Integer";function Xa(r){return r<-999999999999999||999999999999999<r}const Qa=/[\x00-\x1f\x7f]+/,Za="Token",Ja="Key";function bt(r,t,e){return Wa("serialize",r,t,e)}function tl(r){if(typeof r!="boolean")throw bt(r,Ya);return r?"?1":"?0"}function el(r){return btoa(String.fromCharCode(...r))}function sl(r){if(ArrayBuffer.isView(r)===false)throw bt(r,za);return `:${el(r)}:`}function rn(r){if(Xa(r))throw bt(r,ja);return r.toString()}function il(r){return `@${rn(r.getTime()/1e3)}`}function on(r,t){if(r<0)return -on(-r,t);const e=Math.pow(10,t);if(Math.abs(r*e%1-.5)<Number.EPSILON){const i=Math.floor(r*e);return (i%2===0?i:i+1)/e}else return Math.round(r*e)/e}function nl(r){const t=on(r,3);if(Math.floor(Math.abs(t)).toString().length>12)throw bt(r,qa);const e=t.toString();return e.includes(".")?e:`${e}.0`}const rl="String";function ol(r){if(Qa.test(r))throw bt(r,rl);return `"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function al(r){return r.description||r.toString().slice(7,-1)}function ri(r){const t=al(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===false)throw bt(t,Za);return t}function Je(r){switch(typeof r){case "number":if(!$(r))throw bt(r,ni);return Number.isInteger(r)?rn(r):nl(r);case "string":return ol(r);case "symbol":return ri(r);case "boolean":return tl(r);case "object":if(r instanceof Date)return il(r);if(r instanceof Uint8Array)return sl(r);if(r instanceof nn)return ri(r);default:throw bt(r,ni)}}function ts(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===false)throw bt(r,Ja);return r}function ms(r){return r==null?"":Object.entries(r).map(([t,e])=>e===true?`;${ts(t)}`:`;${ts(t)}=${Je(e)}`).join("")}function an(r){return r instanceof Ht?`${Je(r.value)}${ms(r.params)}`:Je(r)}function ll(r){return `(${r.value.map(an).join(" ")})${ms(r.params)}`}function cl(r,t={whitespace:true}){if(typeof r!="object")throw bt(r,Va);const e=r instanceof Map?r.entries():Object.entries(r),s=t!=null&&t.whitespace?" ":"";return Array.from(e).map(([i,n])=>{n instanceof Ht||(n=new Ht(n));let o=ts(i);return n.value===true?o+=ms(n.params):(o+="=",Array.isArray(n.value)?o+=ll(n):o+=an(n)),o}).join(`,${s}`)}function hl(r,t){return cl(r,t)}const ul=r=>r==="ot"||r==="sf"||r==="st",dl=r=>typeof r=="number"?$(r):r!=null&&r!==""&&r!==false;function fl(r,t){const e=new URL(r),s=new URL(t);if(e.origin!==s.origin)return r;const i=e.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;i[0]===n[0];)i.shift(),n.shift();for(;n.length;)n.shift(),i.unshift("..");return i.join("/")}function gl(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch{let e=new Date().getTime();return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(i=="x"?n:n&3|8).toString(16)})}}}const me=r=>Math.round(r),ml=(r,t)=>(t!=null&&t.baseUrl&&(r=fl(r,t.baseUrl)),encodeURIComponent(r)),ae=r=>me(r/100)*100,pl={br:me,d:me,bl:ae,dl:ae,mtp:ae,nor:ml,rtp:ae,tb:me};function xl(r,t){const e={};if(r==null||typeof r!="object")return e;const s=Object.keys(r).sort(),i=ct({},pl,t?.formatters),n=t?.filter;return s.forEach(o=>{if(n!=null&&n(o))return;let a=r[o];const l=i[o];l&&(a=l(a,t)),!(o==="v"&&a===1)&&(o=="pr"&&a===1||dl(a)&&(ul(o)&&typeof a=="string"&&(a=new nn(a)),e[o]=a));}),e}function ln(r,t={}){return r?hl(xl(r,t),ct({whitespace:false},t)):""}function yl(r,t={}){if(!r)return {};const e=Object.entries(r),s=Object.entries(Ka).concat(Object.entries(t?.customHeaderMap||{})),i=e.reduce((n,o)=>{var a;const[c,h]=o,u=((a=s.find(d=>d[1].includes(c)))==null?void 0:a[0])||Pt.REQUEST;return (n[u])!=null||(n[u]={}),n[u][c]=h,n},{});return Object.entries(i).reduce((n,[o,a])=>(n[o]=ln(a,t),n),{})}function Tl(r,t,e){return ct(r,yl(t,e))}const Sl="CMCD";function El(r,t={}){if(!r)return "";const e=ln(r,t);return `${Sl}=${encodeURIComponent(e)}`}const oi=/CMCD=[^&#]+/;function vl(r,t,e){const s=El(t,e);if(!s)return r;if(oi.test(r))return r.replace(oi,s);const i=r.includes("?")?"&":"?";return `${r}${i}${s}`}class Al{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=false,this.includeKeys=void 0,this.initialized=false,this.starved=false,this.buffering=true,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=true),this.buffering=true;},this.onPlaying=()=>{this.initialized||(this.initialized=true),this.buffering=false;},this.applyPlaylistData=i=>{try{this.apply(i,{ot:at.MANIFEST,su:!this.initialized});}catch(n){b.warn("Could not generate manifest CMCD data.",n);}},this.applyFragmentData=i=>{try{const n=i.frag,o=this.hls.levels[n.level],a=this.getObjectType(n),l={d:n.duration*1e3,ot:a};(a===at.VIDEO||a===at.AUDIO||a==at.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(a)/1e3,l.bl=this.getBufferLength(a)),this.apply(i,l);}catch(n){b.warn("Could not generate segment CMCD data.",n);}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;s!=null&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||gl(),this.cid=s.contentId,this.useHeaders=s.useHeaders===true,this.includeKeys=s.includeKeys,this.registerListeners());}registerListeners(){const t=this.hls;t.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(x.MEDIA_DETACHED,this.onMediaDetached,this),t.on(x.BUFFER_CREATED,this.onBufferCreated,this);}unregisterListeners(){const t=this.hls;t.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(x.MEDIA_DETACHED,this.onMediaDetached,this),t.off(x.BUFFER_CREATED,this.onBufferCreated,this);}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null;}onMediaAttached(t,e){this.media=e.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(t,e){var s,i;this.audioBuffer=(s=e.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=e.tracks.video)==null?void 0:i.buffer;}createData(){var t;return {v:1,sf:Ze.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){ct(e,this.createData());const s=e.ot===at.INIT||e.ot===at.VIDEO||e.ot===at.MUXED;this.starved&&s&&(e.bs=true,e.su=true,this.starved=false),e.su==null&&(e.su=this.buffering);const{includeKeys:i}=this;i&&(e=Object.keys(e).reduce((n,o)=>(i.includes(o)&&(n[o]=e[o]),n),{})),this.useHeaders?(t.headers||(t.headers={}),Tl(t.headers,e)):t.url=vl(t.url,e);}getObjectType(t){const{type:e}=t;if(e==="subtitle")return at.TIMED_TEXT;if(t.sn==="initSegment")return at.INIT;if(e==="audio")return at.AUDIO;if(e==="main")return this.hls.audioTracks.length?at.VIDEO:at.MUXED}getTopBandwidth(t){let e=0,s;const i=this.hls;if(t===at.AUDIO)s=i.audioTracks;else {const n=i.maxAutoLevel,o=n>-1?n+1:i.levels.length;s=i.levels.slice(0,o);}for(const n of s)n.bitrate>e&&(e=n.bitrate);return e>0?e:NaN}getBufferLength(t){const e=this.hls.media,s=t===at.AUDIO?this.audioBuffer:this.videoBuffer;return !s||!e?NaN:nt.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,o,a){e(n),this.loader.load(n,o,a);}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,o,a){e(n),this.loader.load(n,o,a);}}}}const bl=3e5;class Rl{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=false,this.enabled=true,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=b.log.bind(b,"[content-steering]:"),this.registerListeners();}registerListeners(){const t=this.hls;t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(x.MANIFEST_PARSED,this.onManifestParsed,this),t.on(x.ERROR,this.onError,this);}unregisterListeners(){const t=this.hls;t&&(t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(x.MANIFEST_PARSED,this.onManifestParsed,this),t.off(x.ERROR,this.onError,this));}startLoad(){if(this.started=true,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri);}}stopLoad(){this.started=false,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(t){const e=this.levels;e&&(this.levels=e.filter(s=>s!==t));}onManifestLoading(){this.stopLoad(),this.enabled=true,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null;}onManifestLoaded(t,e){const{contentSteering:s}=e;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad());}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks;}onError(t,e){const{errorAction:s}=e;if(s?.action===rt.SendAlternateToPenaltyBox&&s.flags===mt.MoveAllAlternatesMatchingHost){const i=this.levels;let n=this.pathwayPriority,o=this.pathwayId;if(e.context){const{groupId:a,pathwayId:l,type:c}=e.context;a&&i?o=this.getPathwayForGroupId(a,c,o):l&&(o=l);}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!n&&i&&(n=i.reduce((a,l)=>(a.indexOf(l.pathwayId)===-1&&a.push(l.pathwayId),a),[])),n&&n.length>1&&(this.updatePathwayPriority(n),s.resolved=this.pathwayId!==o),s.resolved||b.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${o} levels: ${i&&i.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`);}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s;}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){this.pathwayPriority=t;let e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(n=>{i-s[n]>bl&&delete s[n];});for(let n=0;n<t.length;n++){const o=t[n];if(o in s)continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(e=this.getLevelsForPathway(o),e.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Vr(e),this.hls.trigger(x.LEVELS_UPDATED,{levels:e});const c=this.hls.levels[a];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<i.length;n++)if(e===wt.AUDIO_TRACK&&i[n].hasAudioGroup(t)||e===wt.SUBTITLE_TRACK&&i[n].hasSubtitleGroup(t))return i[n].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},i={};t.forEach(n=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=n;if(e.some(h=>h.pathwayId===o))return;const c=this.getLevelsForPathway(a).map(h=>{const u=new Qt(h.attrs);u["PATHWAY-ID"]=o;const d=u.AUDIO&&`${u.AUDIO}_clone_${o}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${o}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);const g=cn(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Te({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let p=1;p<h.audioGroups.length;p++)m.addGroupId("audio",`${h.audioGroups[p]}_clone_${o}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)m.addGroupId("text",`${h.subtitleGroups[p]}_clone_${o}`);return m});e.push(...c),ai(this.audioTracks,s,l,o),ai(this.subtitleTracks,i,l,o);});}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;this.loader&&this.loader.destroy(),this.loader=new s(e);let i;try{i=new self.URL(t);}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest URI: ${t}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h);}const n={responseType:"json",url:i.href},o=e.steeringManifestLoadPolicy.default,a=o.errorRetry||o.timeoutRetry||{},l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=h.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":y}=g;if(m)try{this.uri=new self.URL(m,i).href;}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),p&&this.clonePathways(p);const A={steeringManifest:g,url:i.toString()};this.hls.trigger(x.STEERING_MANIFEST_LOADED,A),y&&this.updatePathwayPriority(y);},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=false,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){const m=this.loader;if(typeof m?.getResponseHeader=="function"){const p=m.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3);}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g);},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url);}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(n,l,c);}scheduleRefresh(t,e=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(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3);},e);}}function ai(r,t,e,s){r&&Object.keys(t).forEach(i=>{const n=r.filter(o=>o.groupId===i).map(o=>{const a=ct({},o);return a.details=void 0,a.attrs=new Qt(a.attrs),a.url=a.attrs.URI=cn(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),a.groupId=a.attrs["GROUP-ID"]=t[i],a.attrs["PATHWAY-ID"]=s,a});r.push(...n);});}function cn(r,t,e,s){const{HOST:i,PARAMS:n,[e]:o}=s;let a;t&&(a=o?.[t],a&&(r=a));const l=new self.URL(r);return i&&!a&&(l.host=i),n&&Object.keys(n).sort().forEach(c=>{c&&l.searchParams.set(c,n[c]);}),l.href}const Ll=/^age:\s*[\d.]+\s*$/im;class Il{constructor(t){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=t&&t.xhrSetup||null,this.stats=new qn,this.retryDelay=0;}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null;}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=true,t.abort()));}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader);}load(t,e,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal();}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=false;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return n(s,e.url)}).catch(o=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",e.url,true),n(s,e.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t);}).catch(o=>{this.callbacks.onError({code:s.status,text:o.message},e,s,i);}):this.openAndSendXhr(s,e,t);}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,true);const i=e.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:o}=s.loadPolicy;if(i)for(const a in i)t.setRequestHeader(a,i[a]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&$(n)?n:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send();}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,n=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const o=e.status,a=e.responseType!=="text";if(o>=200&&o<300&&(a&&e.response||e.responseText!==null)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=a?e.response:e.responseText,c=e.responseType==="arraybuffer"?l.byteLength:l.length;if(s.loaded=s.total=c,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first),!this.callbacks)return;const h=this.callbacks.onProgress;if(h&&h(s,t,l,e),!this.callbacks)return;const u={url:e.responseURL,data:l,code:o};this.callbacks.onSuccess(u,s,t,e);}else {const l=n.loadPolicy.errorRetry,c=s.retry,h={url:t.url,data:void 0,code:o};Ee(l,c,false,h)?this.retry(l):(b.error(`${o} while loading ${t.url}`),this.callbacks.onError({code:o,text:e.statusText},t,e,s));}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,e=this.stats.retry;if(Ee(t,e,true))this.retry(t);else {var s;b.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(t){const{context:e,stats:s}=this;this.retryDelay=os(t,s.retry),s.retry++,b.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e?.url}, retrying ${s.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total);}getCacheAge(){let t=null;if(this.loader&&Ll.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null;}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const wl=/\s/,Dl={newCue(r,t,e,s){const i=[];let n,o,a,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(n=s.rows[d],a=true,l=0,c="",!n.isEmpty()){var u;for(let m=0;m<n.chars.length;m++)wl.test(n.chars[m].uchar)&&a?l++:(c+=n.chars[m].uchar,a=false);n.cueStartTime=t,t===e&&(e+=1e-4),l>=16?l--:l++;const f=Zi(c.trim()),g=fs(t,e,f);r!=null&&(u=r.cues)!=null&&u.getCueById(g)||(o=new h(t,e,f),o.id=g,o.line=d+1,o.align="left",o.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(o));}return r&&i.length&&(i.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>Ei(r,d))),i}},Cl={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null};ut(ut({autoStartLoad:true,startPosition:-1,defaultAudioCodec:void 0,debug:false,capLevelOnFPSDrop:false,capLevelToPlayerSize:false,ignoreDevicePixelRatio:false,preferManagedMediaSource:true,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:false,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:true,workerPath:null,enableSoftwareAES:true,startLevel:void 0,startFragPrefetch:false,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Il,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:ao,bufferController:fa,capLevelController:gs,errorController:jr,fpsController:Ga,stretchShortVideoTrack:false,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:true,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:false,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:false,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:di,testBandwidth:true,progressive:false,lowLatencyMode:true,cmcd:void 0,enableDateRangeMetadataCues:true,enableEmsgMetadataCues:true,enableID3MetadataCues:true,useMediaCapabilities:true,certLoadPolicy:{default:Cl},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},_l()),{},{subtitleStreamController:ca,subtitleTrackController:ua,timelineController:Ba,audioStreamController:aa,audioTrackController:la,emeController:Gt,cmcdController:Al,contentSteeringController:Rl});function _l(){return {cueHandler:Dl,enableWebVTT:true,enableIMSC1:true,enableCEA708Captions:true,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:true}}function kl(r,t$1){r.component(e=>{let{value:s$1=null,subtitles:i=null,label:n,i18n:o,dispatch_blob:a=()=>Promise.resolve(),interactive:l=false,editable:c=true,trim_region_settings:h={},waveform_settings:u,waveform_options:d,mode:f=void 0,loop:g,handle_reset_value:m=()=>{},playback_position:p$1=void 0,onstop:y,onplay:A,onpause:T,onedit:R,onload:E}=t$1;s$1?.url;let I,v,C=false,L=0,_=0,D=false,q=true,V=d.show_recording_waveform&&!s$1?.is_stream;const j=async(U,N)=>{f="";R?.();};let G=true,z;function tt(U){U.push(`<audio${attr_class("standard-player svelte-1ffmt2w",void 0,{hidden:V})} controls${attr("autoplay",u.autoplay,true)} preload="metadata"></audio> `),s$1===null?(U.push("<!--[-->"),p(U,{size:"small",children:N=>{t(N);},$$slots:{default:true}})):(U.push("<!--[!-->"),V?(U.push("<!--[-->"),U.push(`<div class="component-wrapper svelte-1ffmt2w"${attr("data-testid",n?"waveform-"+n:"unlabelled-audio")}><div class="waveform-container svelte-1ffmt2w"><div id="waveform" class="svelte-1ffmt2w"${attr_style("",{height:"58px"})}></div></div> <div class="timestamps svelte-1ffmt2w"><time id="time" class="svelte-1ffmt2w">0:00</time> <div>`),f==="edit"&&_>0?(U.push("<!--[-->"),U.push(`<time id="trim-duration" class="svelte-1ffmt2w">${escape_html(y$2(_))}</time>`)):U.push("<!--[!-->"),U.push('<!--]--> <time id="duration" class="svelte-1ffmt2w">0:00</time></div></div> <div class="subtitle-display svelte-1ffmt2w" data-testid="subtitle-display"></div> '),Mn(U,{container:I,waveform:v,playing:C,audio_duration:L,i18n:o,interactive:l,handle_trim_audio:j,show_redo:l,handle_reset_value:m,waveform_options:d,trim_region_settings:h,editable:c,show_subtitles:i!==null,get mode(){return f},set mode(N){f=N,G=false;},get trimDuration(){return _},set trimDuration(N){_=N,G=false;},get show_volume_slider(){return D},set show_volume_slider(N){D=N,G=false;},get subtitles_toggle(){return q},set subtitles_toggle(N){q=N,G=false;}}),U.push("<!----></div>")):U.push("<!--[!-->"),U.push("<!--]-->")),U.push("<!--]-->");}do G=true,z=e.copy(),tt(z);while(!G);e.subsume(z),bind_props(t$1,{mode:f,playback_position:p$1});});}function Pl(r,t$1){r.component(e=>{let{value:s$1=null,subtitles:i=null,label:n,show_label:o=true,buttons:a=[],on_custom_button_click:l$1=null,i18n:c,waveform_settings:h={},waveform_options:u$1={show_recording_waveform:true},editable:d=true,loop:f,display_icon_button_wrapper_top_corner:g=false,minimal:m=false,playback_position:p$1=void 0,onchange:y$2,onplay:A,onpause:T,onstop:R,onshare:E,onerror:I}=t$1,v=true,C;function P(L){k$1(L,{show_label:o,Icon:t,float:false,label:n||c("audio.audio")}),L.push("<!----> "),s$1!==null?(L.push("<!--[-->"),m?(L.push("<!--[-->"),Z(L,{value:s$1,label:n||c("audio.audio"),loop:f})):(L.push("<!--[!-->"),y(L,{display_top_corner:g,buttons:a,on_custom_button_click:l$1,children:_=>{a.some(D=>typeof D=="string"&&D==="download")?(_.push("<!--[-->"),u(_,{href:s$1.is_stream?s$1.url?.replace("playlist.m3u8","playlist-file"):s$1.url,download:s$1.orig_name||s$1.path,children:D=>{w$1(D,{Icon:l,label:c("common.download")});},$$slots:{default:true}})):_.push("<!--[!-->"),_.push("<!--]--> "),a.some(D=>typeof D=="string"&&D==="share")?(_.push("<!--[-->"),y$1(_,{i18n:c,onerror:I,onshare:E,formatter:async D=>!D||!D.url?"":`<audio controls src="${await w$2(D.url)}"></audio>`,value:s$1})):_.push("<!--[!-->"),_.push("<!--]-->");}}),L.push("<!----> "),kl(L,{value:s$1,subtitles:Array.isArray(i)?i:i?.url,label:n,i18n:c,waveform_settings:h,waveform_options:u$1,editable:d,loop:f,onpause:T,onplay:A,onstop:R,onload:()=>{},get playback_position(){return p$1},set playback_position(_){p$1=_,v=false;}}),L.push("<!---->")),L.push("<!--]-->")):(L.push("<!--[!-->"),p(L,{size:"small",children:_=>{t(_);},$$slots:{default:true}})),L.push("<!--]-->");}do v=true,C=e.copy(),P(C);while(!v);e.subsume(C),bind_props(t$1,{playback_position:p$1});});}const tc=Object.freeze(Object.defineProperty({__proto__:null,default:Pl},Symbol.toStringTag,{value:"Module"}));

export { kl as A, Pl as S, tc as a };
//# sourceMappingURL=StaticAudio-DNyI0JWU.js.map
