diff --git a/Dockerfile b/Dockerfile index ede344a..b790c55 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,6 +15,7 @@ COPY packages/notify/package.json packages/notify/ COPY packages/playlists/package.json packages/playlists/ COPY packages/payments/package.json packages/payments/ COPY packages/queue/package.json packages/queue/ +COPY packages/radio/package.json packages/radio/ COPY packages/sports/package.json packages/sports/ RUN bun install --frozen-lockfile || bun install diff --git a/README.md b/README.md index e3b1bea..04e5e78 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ packages/queue BullMQ queues, schedules and the fan-out workers. packages/notify Web push (VAPID) and email (Resend). packages/auth Magic link, passkeys, sessions. packages/payments CoinPay checkout, webhook verification, entitlements. +packages/playlists A reader's own M3U line: import, probe, proxy, share. +packages/radio A reader's own SiriusXM: email+code sign-in, lineups, HLS proxy. ``` ## How reminders scale @@ -95,3 +97,32 @@ proxy forwarding to a closed socket while the container reports healthy. Secrets belong on the service and in the logicsrc vault, not in a committed `.env`. + +## Radio (SiriusXM) + +A reader connects their own SiriusXM subscription in settings — the email on the +account and the code SiriusXM sends to it, the way the SiriusXM app signs in — +and the sports and news lineups play on `/radio` and on a fixture's page. The +session is sealed with the playlist key and every byte is fetched by the server +as that reader; the browser never sees a SiriusXM address or a bearer. The player +is `@profullstack/player` with its audio bar, bundled to `vendor-player.js` and +fetched on the first press of Play. + +Knobs, all read at request time: + +- `SIRIUSXM` — `0` turns the rail off. Defaults to on for the tipoffwatch brand + and off for any other `BRAND`. +- `SIRIUSXM_PROXY_URL` — the residential exit for every SiriusXM call. Falls back + to `SPORTS_PROXY_URL`. Not optional in production: SiriusXM answers a + datacenter address with 403 and pins a session to the IP that authenticated it. +- `SIRIUSXM_PROXIES` — a pool of single-IP proxies (`host:port:user:pass` lines + or full URLs, comma or newline separated). Each reader is hashed to one and + keeps it, so login, refresh and playback all leave through the same address. + Set this when a rotating endpoint starts breaking streams mid-segment. +- `SIRIUSXM_DEVICE_GRANT` — a `DEVICE_GRANT` cookie value pasted from a browser + session, for the rare case SiriusXM refuses to start a sign-in without one. + The sign-in is tried without it first. + +The pending-code state between "send code" and "verify" lives in the web +process's memory for ten minutes, which is right for one web replica and would +need Redis for more. diff --git a/apps/web/build-client.js b/apps/web/build-client.js index 287fb91..51e097c 100644 --- a/apps/web/build-client.js +++ b/apps/web/build-client.js @@ -1,3 +1,5 @@ +import { dirname } from 'node:path'; + /** * Bundles the browser helpers into public/ as globals. * @@ -12,8 +14,46 @@ const BUNDLES = [ ['webauthn-entry.js', 'vendor-webauthn.js'], ['player-entry.js', 'vendor-mpegts.js'], + // The house player with its control bar, for radio. A third bundle rather than + // a second entry in the second: a reader pressing Play on a channel row must + // not download hls.js, and one pressing Play on a station must not download + // the transport stream demuxer. + ['radio-entry.js', 'vendor-player.js'], ]; +/* + * The player's stylesheet ships beside its script, copied out of the package so + * a version bump is one place. Fetched by app.js with the bundle, never linked + * by the Layout: it styles a bar that most pages never draw. + */ +const PLAYER_CSS = [ + new URL('../../node_modules/@profullstack/player/dist/player.css', import.meta.url), + new URL('./node_modules/@profullstack/player/dist/player.css', import.meta.url), +]; + +/* + * What the radio bundle leaves out. + * + * The player loads its engines on demand, and a bundler with no code splitting + * answers a dynamic import by inlining it -- so the first build of this bundle + * carried hls.js AND the transport stream demuxer, 900KB for a page that only + * ever plays HLS. mpegts.js is marked external (the import stays a bare + * specifier that is never reached for an HLS source), and hls.js is swapped for + * its light build, which drops subtitles, DRM and alternate audio tracks. A + * radio station has none of those. + */ +const hlsLight = { + name: 'hls-light', + setup(build) { + // Resolved from the importer, not from here: hls.js is the player's own + // dependency and Bun's isolated linker does not hoist it to this package. + build.onResolve({ filter: /^hls\.js$/ }, (args) => ({ + path: Bun.resolveSync('hls.js/dist/hls.light.mjs', dirname(args.importer)), + })); + }, +}; +const RADIO_ONLY = { external: ['mpegts.js'], plugins: [hlsLight] }; + for (const [entry, name] of BUNDLES) { const out = await Bun.build({ entrypoints: [new URL(`./src/client/${entry}`, import.meta.url).pathname], @@ -21,6 +61,7 @@ for (const [entry, name] of BUNDLES) { naming: name, minify: true, target: 'browser', + ...(entry === 'radio-entry.js' ? RADIO_ONLY : {}), }); if (!out.success) { for (const l of out.logs) console.error(l); @@ -28,3 +69,11 @@ for (const [entry, name] of BUNDLES) { } console.log(`[build] ${name}`); } + +for (const candidate of PLAYER_CSS) { + const file = Bun.file(candidate.pathname); + if (!(await file.exists())) continue; + await Bun.write(new URL('./public/vendor-player.css', import.meta.url).pathname, file); + console.log('[build] vendor-player.css'); + break; +} diff --git a/apps/web/package.json b/apps/web/package.json index 7eed11c..bf70d40 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -9,7 +9,7 @@ "build:client": "bun build-client.js" }, "dependencies": { - "@profullstack/player": "0.3.1", + "@profullstack/player": "0.6.0", "@simplewebauthn/browser": "^13.2.0", "@tipoff/auth": "workspace:*", "@tipoff/config": "workspace:*", @@ -18,6 +18,7 @@ "@tipoff/payments": "workspace:*", "@tipoff/playlists": "workspace:*", "@tipoff/queue": "workspace:*", + "@tipoff/radio": "workspace:*", "@tipoff/sports": "workspace:*", "hono": "^4.10.3", "mpegts.js": "1.8.2" diff --git a/apps/web/public/app.js b/apps/web/public/app.js index 99a52b6..c3a171c 100644 --- a/apps/web/public/app.js +++ b/apps/web/public/app.js @@ -720,6 +720,7 @@ function initNavigation() { initMarketTabs(); initOwnChannelActions(); initInlinePlayer(); + initRadio(); initPush(); initPasskeys(); initPlaylistReveal(); @@ -758,6 +759,7 @@ reportTimezone(); initMarketTabs(); initOwnChannelActions(); initInlinePlayer(); +initRadio(); initPush(); initPasskeys(); // Before initFollowForms: it must be able to cancel a submit that handler would @@ -1486,3 +1488,232 @@ function initPlayerSection(section) { // iOS and on a back/forward navigation. window.addEventListener('pagehide', teardown); } + +/* ------------------------------------------------------------------ radio -- */ + +/** + * The SiriusXM sections: the lineup on /radio and the lookup on an event page. + * + * Same shape as initPlayerSection, and the same rules, because the reasons are + * the same. One station at a time -- a SiriusXM account is one subscription and + * the second stream is what gets it flagged -- so the teardown chains into + * `__tipoffStopPlayer` with the video players, and a client-side navigation or a + * press on a TV channel stops the radio too. The bundle is fetched on the first + * press, never on load. + * + * The station plays through the house player's own bar (it has volume, mute + * and a LIVE badge of its own), so the button on the row only ever says Play + * here or Stop. + */ +const RADIO_QUALITY_KEY = 'tw.radio.quality'; + +function radioQuality() { + try { + const v = localStorage.getItem(RADIO_QUALITY_KEY); + return ['256', '128', '64', '32'].includes(v) ? v : '256'; + } catch { + return '256'; + } +} + +function loadRadioBundle(section) { + if (window.__tipoffRadio) return Promise.resolve(window.__tipoffRadio); + if (window.__tipoffRadioLoading) return window.__tipoffRadioLoading; + // The stylesheet first, and not awaited: a bar drawn a frame before its CSS + // arrives is a bar, and a bar that never gets its CSS because the link + // failed is still a bar with buttons on it. + const css = section.dataset.radioCss; + if (css && !document.querySelector(`link[href="${css}"]`)) { + const link = document.createElement('link'); + link.rel = 'stylesheet'; + link.href = css; + document.head.append(link); + } + window.__tipoffRadioLoading = new Promise((resolve, reject) => { + const el = document.createElement('script'); + el.src = section.dataset.radioSrc; + el.onload = () => + window.__tipoffRadio ? resolve(window.__tipoffRadio) : reject(new Error('no player')); + el.onerror = () => { + window.__tipoffRadioLoading = null; + reject(new Error('could not load the player')); + }; + document.head.append(el); + }); + return window.__tipoffRadioLoading; +} + +/** Can this browser push HLS audio into Media Source? Asked without the bundle, for the same reason canTransmux is. */ +function canPlayRadio() { + try { + return ( + typeof MediaSource !== 'undefined' && + MediaSource.isTypeSupported('audio/mp4; codecs="mp4a.40.2"') + ); + } catch { + return false; + } +} + +function initRadio(root = document) { + for (const section of root.querySelectorAll('[data-radio-src]')) initRadioSection(section); + for (const select of root.querySelectorAll('select[data-radio-quality]')) { + select.value = radioQuality(); + select.addEventListener('change', () => { + try { + localStorage.setItem(RADIO_QUALITY_KEY, select.value); + } catch { + // A browser that refuses storage still gets the stream it asked for, + // just not next time. + } + }); + } +} + +function initRadioSection(section) { + if (!section || section.dataset.radio) return; + section.dataset.radio = '1'; + + let stop = null; + let stage = null; + let generation = 0; + let playing = null; + + const teardown = () => { + if (stop) stop(); + stop = null; + stage?.remove(); + stage = null; + if (playing) { + playing.dataset.playing = ''; + playing.textContent = 'Play here'; + playing = null; + } + }; + const previousStop = window.__tipoffStopPlayer; + window.__tipoffStopPlayer = () => { + previousStop?.(); + teardown(); + }; + window.addEventListener('pagehide', teardown); + + const message = (text, error) => { + section.querySelector('.player-error')?.remove(); + if (!text) return; + const p = document.createElement('p'); + p.className = error ? 'feedback error player-error' : 'feedback player-error'; + p.textContent = text; + section.prepend(p); + }; + + const fail = (text) => { + teardown(); + message(text, true); + }; + + const wire = (scope) => { + const buttons = [...scope.querySelectorAll('button[data-radio-play]')]; + if (!canPlayRadio()) { + // Nothing to offer instead: SiriusXM streams only play with the bearer, + // and there is no app link that could carry it. + for (const b of buttons) b.closest('li')?.remove(); + if (buttons.length) { + message( + 'This browser cannot play SiriusXM streams here. Chrome, Firefox, Edge or an Android or TV browser can.', + true, + ); + } + return; + } + for (const button of buttons) { + if (button.dataset.wired) continue; + button.dataset.wired = '1'; + button.disabled = false; + button.addEventListener('click', async () => { + message(null); + if (button.dataset.playing) { + generation += 1; + teardown(); + return; + } + generation += 1; + const mine = generation; + // Whatever else is playing -- a station in this section, a TV channel in + // another -- goes first. One stream per reader is the rule everywhere. + window.__tipoffStopPlayer?.(); + + button.disabled = true; + button.textContent = 'Starting…'; + let player; + try { + player = await loadRadioBundle(section); + } catch { + button.disabled = false; + button.textContent = 'Play here'; + fail('The player could not be loaded. Reload the page and try again.'); + return; + } + if (mine !== generation) { + button.disabled = false; + button.textContent = 'Play here'; + return; + } + button.disabled = false; + if (!player.supported()) { + fail('This browser cannot play SiriusXM streams here.'); + return; + } + + const separator = button.dataset.radioPlay.includes('?') ? '&' : '?'; + const src = `${button.dataset.radioPlay}${separator}quality=${radioQuality()}`; + stage = document.createElement('div'); + stage.className = 'player-stage audio'; + button.closest('li')?.after(stage); + playing = button; + button.dataset.playing = '1'; + button.textContent = 'Stop'; + stop = player.play(stage, src, { + title: button.dataset.title, + artwork: button.dataset.artwork || undefined, + onError: fail, + onNotice: (text) => message(text, false), + onStop: () => { + generation += 1; + teardown(); + }, + }); + }); + } + }; + + wire(section); + + /* + * The event page asks only when told to. Searching SiriusXM is an upstream + * call on the reader's own session, and most visits to a fixture do not want + * radio for it. The answer arrives as HTML rendered by the same component as + * the lineup page, so there is one row template and it is on the server. + */ + const find = section.querySelector('button[data-radio-find-button]'); + const results = section.querySelector('[data-radio-results]'); + if (find && results && section.dataset.radioFind) { + find.addEventListener('click', async () => { + find.disabled = true; + find.textContent = 'Looking…'; + try { + const res = await fetch(section.dataset.radioFind, { + headers: { accept: 'text/html', 'x-requested-with': 'fetch' }, + }); + const html = await res.text(); + if (!res.ok) throw new Error(html.slice(0, 200) || String(res.status)); + results.innerHTML = html; + wire(results); + find.closest('p')?.remove(); + } catch (err) { + find.disabled = false; + find.textContent = 'Find this game on SiriusXM'; + message(err?.message || 'SiriusXM did not answer. Try again in a moment.', true); + } + }); + } +} diff --git a/apps/web/public/styles.css b/apps/web/public/styles.css index 97c773a..99ca9db 100644 --- a/apps/web/public/styles.css +++ b/apps/web/public/styles.css @@ -2504,3 +2504,79 @@ ul.group-grid .meta { .kind-count.kind-series strong { color: var(--accent); } + +/* ===================================================================== radio == + A reader's own SiriusXM. Rows reuse the channel list; what is new is the + art, the number, and a stage that is a bar rather than a picture. */ +.radio-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.6rem 1rem; + margin: 0.8rem 0 1rem; +} +.radio-tabs { + display: flex; + gap: 0.25rem; +} +.radio-tabs a { + padding: 0.3rem 0.8rem; + border: 1px solid var(--line); + border-radius: 999px; + text-decoration: none; +} +.radio-tabs a.active { + border-color: var(--accent); + color: var(--accent); +} +.radio-search { + display: flex; + gap: 0.35rem; + flex: 1 1 14rem; +} +.radio-search input { + flex: 1; + min-width: 0; +} +.radio-quality { + display: flex; + align-items: center; + gap: 0.4rem; +} +.radio-channel { + align-items: center; +} +.radio-art { + width: 48px; + height: 48px; + flex: none; + border-radius: 6px; + object-fit: cover; + background: var(--line); +} +.radio-art-empty { + display: inline-block; +} +.radio-number { + font-family: var(--mono); + font-size: 0.7rem; + color: var(--muted); + margin-right: 0.5rem; +} +.radio-desc { + display: block; +} +.radio-otp { + font-size: 1.4rem; + letter-spacing: 0.3em; + max-width: 12rem; +} + +/* The bar, inserted after the row that started it. No aspect ratio: there is + no picture to hold a place for, and a 16:9 black box over a radio station + reads as a stream that never arrived. */ +.player-stage.audio { + aspect-ratio: auto; + background: none; + overflow: visible; +} diff --git a/apps/web/public/vendor-mpegts.js b/apps/web/public/vendor-mpegts.js index f2104f5..d31369c 100644 --- a/apps/web/public/vendor-mpegts.js +++ b/apps/web/public/vendor-mpegts.js @@ -1,3 +1,3 @@ -var ci=Object.create;var{getPrototypeOf:hi,defineProperty:Dt,getOwnPropertyNames:fi}=Object;var pi=Object.prototype.hasOwnProperty;function mi(_e){return this[_e]}var gi,yi,vi=(_e,Ae,Me)=>{var le=_e!=null&&typeof _e==="object";if(le){var Q=Ae?gi??=new WeakMap:yi??=new WeakMap,D=Q.get(_e);if(D)return D}Me=_e!=null?ci(hi(_e)):{};let X=Ae||!_e||!_e.__esModule?Dt(Me,"default",{value:_e,enumerable:!0}):Me;if(_e&&typeof _e==="object"||typeof _e==="function"){for(let P of fi(_e))if(!pi.call(X,P))Dt(X,P,{get:mi.bind(_e,P),enumerable:!0})}if(le)Q.set(_e,X);return X};var Si=(_e,Ae)=>()=>(Ae||_e((Ae={exports:{}}).exports,Ae),Ae.exports);var Mt=Si(function(et,lt){/*! For license information please see mpegts.js.LICENSE.txt */(function(_e,Ae){typeof et=="object"&&typeof lt=="object"?lt.exports=Ae():typeof define=="function"&&define.amd?define([],Ae):typeof et=="object"?et.mpegts=Ae():_e.mpegts=Ae()})(et,function(){return function(){var _e={964:function(le,Q,D){le.exports=function(){function X(V){return typeof V=="function"}var P=Array.isArray?Array.isArray:function(V){return Object.prototype.toString.call(V)==="[object Array]"},_=0,S=void 0,R=void 0,v=function(V,Y){G[_]=V,G[_+1]=Y,(_+=2)===2&&(R?R(m):u())},I=typeof window<"u"?window:void 0,b=I||{},k=b.MutationObserver||b.WebKitMutationObserver,w=typeof self>"u"&&typeof process<"u"&&{}.toString.call(process)==="[object process]",O=typeof Uint8ClampedArray<"u"&&typeof importScripts<"u"&&typeof MessageChannel<"u";function A(){var V=setTimeout;return function(){return V(m,1)}}var G=Array(1000);function m(){for(var V=0;V<_;V+=2)(0,G[V])(G[V+1]),G[V]=void 0,G[V+1]=void 0;_=0}var N,x,K,M,u=void 0;function h(V,Y){var ie=this,oe=new this.constructor(W);oe[E]===void 0&&j(oe);var ue=ie._state;if(ue){var Ee=arguments[ue-1];v(function(){return c(ue,oe,Ee,ie._result)})}else ke(ie,oe,V,Y);return oe}function p(V){if(V&&typeof V=="object"&&V.constructor===this)return V;var Y=new this(W);return te(Y,V),Y}u=w?function(){return process.nextTick(m)}:k?(x=0,K=new k(m),M=document.createTextNode(""),K.observe(M,{characterData:!0}),function(){M.data=x=++x%2}):O?((N=new MessageChannel).port1.onmessage=m,function(){return N.port2.postMessage(0)}):I===void 0?function(){try{var V=Function("return this")().require("vertx");return(S=V.runOnLoop||V.runOnContext)!==void 0?function(){S(m)}:A()}catch(Y){return A()}}():A();var E=Math.random().toString(36).substring(2);function W(){}var z=void 0,se=1,de=2;function me(V,Y,ie){Y.constructor===V.constructor&&ie===h&&Y.constructor.resolve===p?function(oe,ue){ue._state===se?Re(oe,ue._result):ue._state===de?J(oe,ue._result):ke(ue,void 0,function(Ee){return te(oe,Ee)},function(Ee){return J(oe,Ee)})}(V,Y):ie===void 0?Re(V,Y):X(ie)?function(oe,ue,Ee){v(function(Pe){var Ue=!1,je=function(Fe,Xe,nt,Ne){try{Fe.call(Xe,nt,Ne)}catch(Qe){return Qe}}(Ee,ue,function(Fe){Ue||(Ue=!0,ue!==Fe?te(Pe,Fe):Re(Pe,Fe))},function(Fe){Ue||(Ue=!0,J(Pe,Fe))},Pe._label);!Ue&&je&&(Ue=!0,J(Pe,je))},oe)}(V,Y,ie):Re(V,Y)}function te(V,Y){if(V===Y)J(V,TypeError("You cannot resolve a promise with itself"));else if(ue=typeof(oe=Y),oe===null||ue!=="object"&&ue!=="function")Re(V,Y);else{var ie=void 0;try{ie=Y.then}catch(Ee){return void J(V,Ee)}me(V,Y,ie)}var oe,ue}function ee(V){V._onerror&&V._onerror(V._result),L(V)}function Re(V,Y){V._state===z&&(V._result=Y,V._state=se,V._subscribers.length!==0&&v(L,V))}function J(V,Y){V._state===z&&(V._state=de,V._result=Y,v(ee,V))}function ke(V,Y,ie,oe){var ue=V._subscribers,Ee=ue.length;V._onerror=null,ue[Ee]=Y,ue[Ee+se]=ie,ue[Ee+de]=oe,Ee===0&&V._state&&v(L,V)}function L(V){var{_subscribers:Y,_state:ie}=V;if(Y.length!==0){for(var oe=void 0,ue=void 0,Ee=V._result,Pe=0;Pe0&&h.length>M&&!h.warned){h.warned=!0;var E=Error("Possible EventEmitter memory leak detected. "+h.length+" "+String(N)+" listeners added. Use emitter.setMaxListeners() to increase limit");E.name="MaxListenersExceededWarning",E.emitter=m,E.type=N,E.count=h.length,p=E,console&&console.warn&&console.warn(p)}return m}function b(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function k(m,N,x){var K={fired:!1,wrapFn:void 0,target:m,type:N,listener:x},M=b.bind(K);return M.listener=x,K.wrapFn=M,M}function w(m,N,x){var K=m._events;if(K===void 0)return[];var M=K[N];return M===void 0?[]:typeof M=="function"?x?[M.listener||M]:[M]:x?function(u){for(var h=Array(u.length),p=0;p0&&(u=N[0]),u instanceof Error)throw u;var h=Error("Unhandled error."+(u?" ("+u.message+")":""));throw h.context=u,h}var p=M[m];if(p===void 0)return!1;if(typeof p=="function")X(p,this,N);else{var E=p.length,W=A(p,E);for(x=0;x=0;u--)if(x[u]===N||x[u].listener===N){h=x[u].listener,M=u;break}if(M<0)return this;M===0?x.shift():function(p,E){for(;E+1=0;K--)this.removeListener(m,N[K]);return this},_.prototype.listeners=function(m){return w(this,m,!0)},_.prototype.rawListeners=function(m){return w(this,m,!1)},_.listenerCount=function(m,N){return typeof m.listenerCount=="function"?m.listenerCount(N):O.call(m,N)},_.prototype.listenerCount=O,_.prototype.eventNames=function(){return this._eventsCount>0?Q(this._events):[]}},955:function(le,Q,D){D.r(Q);var X=function(){function P(){this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.refFrames=null,this.chromaFormat=null,this.sarNum=null,this.sarDen=null,this.metadata=null,this.segments=null,this.segmentCount=null,this.hasKeyframesIndex=null,this.keyframesIndex=null}return P.prototype.isComplete=function(){var _=this.hasAudio===!1||this.hasAudio===!0&&this.audioCodec!=null&&this.audioSampleRate!=null&&this.audioChannelCount!=null,S=this.hasVideo===!1||this.hasVideo===!0&&this.videoCodec!=null&&this.width!=null&&this.height!=null&&this.fps!=null&&this.profile!=null&&this.level!=null&&this.refFrames!=null&&this.chromaFormat!=null&&this.sarNum!=null&&this.sarDen!=null;return this.mimeType!=null&&_&&S},P.prototype.isSeekable=function(){return this.hasKeyframesIndex===!0},P.prototype.getNearestKeyframe=function(_){if(this.keyframesIndex==null)return null;var S=this.keyframesIndex,R=this._search(S.times,_);return{index:R,milliseconds:S.times[R],fileposition:S.filepositions[R]}},P.prototype._search=function(_,S){var R=0,v=_.length-1,I=0,b=0,k=v;for(S<_[0]&&(R=0,b=k+1);b<=k;){if((I=b+Math.floor((k-b)/2))===v||S>=_[I]&&S<_[I+1]){R=I;break}_[I]0&&v[0].originalDts=I[w].dts&&vI[k].lastSample.originalDts&&v=I[k].lastSample.originalDts&&(k===I.length-1||k0&&(w=this._searchNearestSegmentBefore(b.originalBeginDts)+1),this._lastAppendLocation=w,this._list.splice(w,0,b)},R.prototype.getLastSegmentBefore=function(v){var I=this._searchNearestSegmentBefore(v);return I>=0?this._list[I]:null},R.prototype.getLastSampleBefore=function(v){var I=this.getLastSegmentBefore(v);return I!=null?I.lastSample:null},R.prototype.getLastSyncPointBefore=function(v){for(var I=this._searchNearestSegmentBefore(v),b=this._list[I].syncPoints;b.length===0&&I>0;)I--,b=this._list[I].syncPoints;return b.length>0?b[b.length-1]:null},R}()},346:function(le,Q,D){D.r(Q);var X=D(7),P=D.n(X),_=D(856),S=D(994),R=D(403),v=D(867),I=function(){function b(k){this.TAG="MSEController",this._config=k,this._emitter=new(P()),this._config.isLive&&this._config.autoCleanupSourceBuffer==null&&(this._config.autoCleanupSourceBuffer=!0),this.e={onSourceOpen:this._onSourceOpen.bind(this),onSourceEnded:this._onSourceEnded.bind(this),onSourceClose:this._onSourceClose.bind(this),onStartStreaming:this._onStartStreaming.bind(this),onEndStreaming:this._onEndStreaming.bind(this),onQualityChange:this._onQualityChange.bind(this),onSourceBufferError:this._onSourceBufferError.bind(this),onSourceBufferUpdateEnd:this._onSourceBufferUpdateEnd.bind(this)},this._useManagedMediaSource=typeof self.ManagedMediaSource=="function"&&typeof self.MediaSource!="function",this._mediaSource=null,this._mediaSourceObjectURL=null,this._mediaElementProxy=null,this._isBufferFull=!1,this._hasPendingEos=!1,this._requireSetMediaDuration=!1,this._pendingMediaDuration=0,this._pendingSourceBufferInit=[],this._mimeTypes={video:null,audio:null},this._sourceBuffers={video:null,audio:null},this._lastInitSegments={video:null,audio:null},this._pendingSegments={video:[],audio:[]},this._pendingRemoveRanges={video:[],audio:[]}}return b.prototype.destroy=function(){this._mediaSource&&this.shutdown(),this._mediaSourceObjectURL&&this.revokeObjectURL(),this.e=null,this._emitter.removeAllListeners(),this._emitter=null},b.prototype.on=function(k,w){this._emitter.addListener(k,w)},b.prototype.off=function(k,w){this._emitter.removeListener(k,w)},b.prototype.initialize=function(k){if(this._mediaSource)throw new v.IllegalStateException("MediaSource has been attached to an HTMLMediaElement!");this._useManagedMediaSource&&_.default.v(this.TAG,"Using ManagedMediaSource");var w=this._mediaSource=this._useManagedMediaSource?new self.ManagedMediaSource:new self.MediaSource;w.addEventListener("sourceopen",this.e.onSourceOpen),w.addEventListener("sourceended",this.e.onSourceEnded),w.addEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(w.addEventListener("startstreaming",this.e.onStartStreaming),w.addEventListener("endstreaming",this.e.onEndStreaming),w.addEventListener("qualitychange",this.e.onQualityChange)),this._mediaElementProxy=k},b.prototype.shutdown=function(){if(this._mediaSource){var k=this._mediaSource;for(var w in this._sourceBuffers){var O=this._pendingSegments[w];O.splice(0,O.length),this._pendingSegments[w]=null,this._pendingRemoveRanges[w]=null,this._lastInitSegments[w]=null;var A=this._sourceBuffers[w];if(A){if(k.readyState!=="closed"){try{k.removeSourceBuffer(A)}catch(G){_.default.e(this.TAG,G.message)}A.removeEventListener("error",this.e.onSourceBufferError),A.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)}this._mimeTypes[w]=null,this._sourceBuffers[w]=null}}if(k.readyState==="open")try{k.endOfStream()}catch(G){_.default.e(this.TAG,G.message)}this._mediaElementProxy=null,k.removeEventListener("sourceopen",this.e.onSourceOpen),k.removeEventListener("sourceended",this.e.onSourceEnded),k.removeEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(k.removeEventListener("startstreaming",this.e.onStartStreaming),k.removeEventListener("endstreaming",this.e.onEndStreaming),k.removeEventListener("qualitychange",this.e.onQualityChange)),this._pendingSourceBufferInit=[],this._isBufferFull=!1,this._mediaSource=null}},b.prototype.isManagedMediaSource=function(){return this._useManagedMediaSource},b.prototype.getObject=function(){if(!this._mediaSource)throw new v.IllegalStateException("MediaSource has not been initialized yet!");return this._mediaSource},b.prototype.getHandle=function(){if(!this._mediaSource)throw new v.IllegalStateException("MediaSource has not been initialized yet!");return this._mediaSource.handle},b.prototype.getObjectURL=function(){if(!this._mediaSource)throw new v.IllegalStateException("MediaSource has not been initialized yet!");return this._mediaSourceObjectURL==null&&(this._mediaSourceObjectURL=URL.createObjectURL(this._mediaSource)),this._mediaSourceObjectURL},b.prototype.revokeObjectURL=function(){this._mediaSourceObjectURL&&(URL.revokeObjectURL(this._mediaSourceObjectURL),this._mediaSourceObjectURL=null)},b.prototype.appendInitSegment=function(k,w){if(w===void 0&&(w=void 0),!this._mediaSource||this._mediaSource.readyState!=="open"||this._mediaSource.streaming===!1)return this._pendingSourceBufferInit.push(k),void this._pendingSegments[k.type].push(k);var O=k,A="".concat(O.container);O.codec&&O.codec.length>0&&(O.codec==="opus"&&S.default.safari&&(O.codec="Opus"),A+=";codecs=".concat(O.codec));var G=!1;if(_.default.v(this.TAG,"Received Initialization Segment, mimeType: "+A),this._lastInitSegments[O.type]=O,A!==this._mimeTypes[O.type]){if(this._mimeTypes[O.type])_.default.v(this.TAG,"Notice: ".concat(O.type," mimeType changed, origin: ").concat(this._mimeTypes[O.type],", target: ").concat(A));else{G=!0;try{var m=this._sourceBuffers[O.type]=this._mediaSource.addSourceBuffer(A);m.addEventListener("error",this.e.onSourceBufferError),m.addEventListener("updateend",this.e.onSourceBufferUpdateEnd)}catch(N){return _.default.e(this.TAG,N.message),void this._emitter.emit(R.default.ERROR,{code:N.code,msg:N.message})}}this._mimeTypes[O.type]=A}w||this._pendingSegments[O.type].push(O),G||this._sourceBuffers[O.type]&&!this._sourceBuffers[O.type].updating&&this._doAppendSegments(),S.default.safari&&O.container==="audio/mpeg"&&O.mediaDuration>0&&(this._requireSetMediaDuration=!0,this._pendingMediaDuration=O.mediaDuration/1000,this._updateMediaSourceDuration())},b.prototype.appendMediaSegment=function(k){var w=k;this._pendingSegments[w.type].push(w),this._config.autoCleanupSourceBuffer&&this._needCleanupSourceBuffer()&&this._doCleanupSourceBuffer();var O=this._sourceBuffers[w.type];!O||O.updating||this._hasPendingRemoveRanges()||this._doAppendSegments()},b.prototype.flush=function(){for(var k in this._sourceBuffers)if(this._sourceBuffers[k]){var w=this._sourceBuffers[k];if(this._mediaSource.readyState==="open")try{w.abort()}catch(x){_.default.e(this.TAG,x.message)}var O=this._pendingSegments[k];if(O.splice(0,O.length),this._mediaSource.readyState!=="closed"){for(var A=0;A=1&&k-A.start(0)>=this._config.autoCleanupMaxBackwardDuration)return!0}}return!1},b.prototype._doCleanupSourceBuffer=function(){var k=this._mediaElementProxy.getCurrentTime();for(var w in this._sourceBuffers){var O=this._sourceBuffers[w];if(O){for(var A=O.buffered,G=!1,m=0;m=this._config.autoCleanupMaxBackwardDuration){G=!0;var K=k-this._config.autoCleanupMinBackwardDuration;this._pendingRemoveRanges[w].push({start:N,end:K})}}else x0&&(isNaN(w)||O>w)&&(_.default.v(this.TAG,"Update MediaSource duration from ".concat(w," to ").concat(O)),this._mediaSource.duration=O),this._requireSetMediaDuration=!1,this._pendingMediaDuration=0}},b.prototype._doRemoveRanges=function(){for(var k in this._pendingRemoveRanges)if(this._sourceBuffers[k]&&!this._sourceBuffers[k].updating)for(var w=this._sourceBuffers[k],O=this._pendingRemoveRanges[k];O.length&&!w.updating;){var A=O.shift();w.remove(A.start,A.end)}},b.prototype._doAppendSegments=function(){var k=this._pendingSegments;for(var w in k)if(this._sourceBuffers[w]&&!this._sourceBuffers[w].updating&&this._mediaSource.streaming!==!1&&k[w].length>0){var O=k[w].shift();if(typeof O.timestampOffset=="number"&&isFinite(O.timestampOffset)){var A=this._sourceBuffers[w].timestampOffset,G=O.timestampOffset/1000;Math.abs(A-G)>0.1&&(_.default.v(this.TAG,"Update MPEG audio timestampOffset from ".concat(A," to ").concat(G)),this._sourceBuffers[w].timestampOffset=G),delete O.timestampOffset}if(!O.data||O.data.byteLength===0)continue;try{this._sourceBuffers[w].appendBuffer(O.data),this._isBufferFull=!1}catch(m){this._pendingSegments[w].unshift(O),m.code===22?(this._isBufferFull||this._emitter.emit(R.default.BUFFER_FULL),this._isBufferFull=!0):(_.default.e(this.TAG,m.message),this._emitter.emit(R.default.ERROR,{code:m.code,msg:m.message}))}}},b.prototype._onSourceOpen=function(){if(_.default.v(this.TAG,"MediaSource onSourceOpen"),this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._pendingSourceBufferInit.length>0)for(var k=this._pendingSourceBufferInit;k.length;){var w=k.shift();this.appendInitSegment(w,!0)}this._hasPendingSegments()&&this._doAppendSegments(),this._emitter.emit(R.default.SOURCE_OPEN)},b.prototype._onStartStreaming=function(){_.default.v(this.TAG,"ManagedMediaSource onStartStreaming"),this._emitter.emit(R.default.START_STREAMING)},b.prototype._onEndStreaming=function(){_.default.v(this.TAG,"ManagedMediaSource onEndStreaming"),this._emitter.emit(R.default.END_STREAMING)},b.prototype._onQualityChange=function(){_.default.v(this.TAG,"ManagedMediaSource onQualityChange")},b.prototype._onSourceEnded=function(){_.default.v(this.TAG,"MediaSource onSourceEnded")},b.prototype._onSourceClose=function(){_.default.v(this.TAG,"MediaSource onSourceClose"),this._mediaSource&&this.e!=null&&(this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._mediaSource.removeEventListener("sourceended",this.e.onSourceEnded),this._mediaSource.removeEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(this._mediaSource.removeEventListener("startstreaming",this.e.onStartStreaming),this._mediaSource.removeEventListener("endstreaming",this.e.onEndStreaming),this._mediaSource.removeEventListener("qualitychange",this.e.onQualityChange)))},b.prototype._hasPendingSegments=function(){var k=this._pendingSegments;return k.video.length>0||k.audio.length>0},b.prototype._hasPendingRemoveRanges=function(){var k=this._pendingRemoveRanges;return k.video.length>0||k.audio.length>0},b.prototype._onSourceBufferUpdateEnd=function(){this._requireSetMediaDuration?this._updateMediaSourceDuration():this._hasPendingRemoveRanges()?this._doRemoveRanges():this._hasPendingSegments()?this._doAppendSegments():this._hasPendingEos&&this.endOfStream(),this._emitter.emit(R.default.UPDATE_END)},b.prototype._onSourceBufferError=function(k){_.default.e(this.TAG,"SourceBuffer Error: ".concat(k))},b}();Q.default=I},527:function(le,Q,D){D.r(Q);var X=D(7),P=D.n(X),_=D(861),S=D.n(_),R=D(856),v=D(947),I=D(886),b=D(726),k=(D(137),D(955)),w=function(){function O(A,G){if(this.TAG="Transmuxer",this._emitter=new(P()),G.enableWorker&&typeof Worker<"u")try{this._worker=S()(137),this._workerDestroying=!1,this._worker.addEventListener("message",this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:"init",param:[A,G]}),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this)},v.default.registerListener(this.e.onLoggingConfigChanged),this._worker.postMessage({cmd:"logging_config",param:v.default.getConfig()})}catch(N){R.default.e(this.TAG,"Error while initialize transmuxing worker, fallback to inline transmuxing"),this._worker=null,this._controller=new I.default(A,G)}else this._controller=new I.default(A,G);if(this._controller){var m=this._controller;m.on(b.default.IO_ERROR,this._onIOError.bind(this)),m.on(b.default.DEMUX_ERROR,this._onDemuxError.bind(this)),m.on(b.default.INIT_SEGMENT,this._onInitSegment.bind(this)),m.on(b.default.MEDIA_SEGMENT,this._onMediaSegment.bind(this)),m.on(b.default.LOADING_COMPLETE,this._onLoadingComplete.bind(this)),m.on(b.default.RECOVERED_EARLY_EOF,this._onRecoveredEarlyEof.bind(this)),m.on(b.default.MEDIA_INFO,this._onMediaInfo.bind(this)),m.on(b.default.METADATA_ARRIVED,this._onMetaDataArrived.bind(this)),m.on(b.default.SCRIPTDATA_ARRIVED,this._onScriptDataArrived.bind(this)),m.on(b.default.TIMED_ID3_METADATA_ARRIVED,this._onTimedID3MetadataArrived.bind(this)),m.on(b.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,this._onSynchronousKLVMetadataArrived.bind(this)),m.on(b.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,this._onAsynchronousKLVMetadataArrived.bind(this)),m.on(b.default.SMPTE2038_METADATA_ARRIVED,this._onSMPTE2038MetadataArrived.bind(this)),m.on(b.default.SEI_ARRIVED,this._onSEIArrived.bind(this)),m.on(b.default.SCTE35_METADATA_ARRIVED,this._onSCTE35MetadataArrived.bind(this)),m.on(b.default.PES_PRIVATE_DATA_DESCRIPTOR,this._onPESPrivateDataDescriptor.bind(this)),m.on(b.default.PES_PRIVATE_DATA_ARRIVED,this._onPESPrivateDataArrived.bind(this)),m.on(b.default.STATISTICS_INFO,this._onStatisticsInfo.bind(this)),m.on(b.default.RECOMMEND_SEEKPOINT,this._onRecommendSeekpoint.bind(this))}}return O.prototype.destroy=function(){this._worker?this._workerDestroying||(this._workerDestroying=!0,this._worker.postMessage({cmd:"destroy"}),v.default.removeListener(this.e.onLoggingConfigChanged),this.e=null):(this._controller.destroy(),this._controller=null),this._emitter.removeAllListeners(),this._emitter=null},O.prototype.on=function(A,G){this._emitter.addListener(A,G)},O.prototype.off=function(A,G){this._emitter.removeListener(A,G)},O.prototype.hasWorker=function(){return this._worker!=null},O.prototype.open=function(){this._worker?this._worker.postMessage({cmd:"start"}):this._controller.start()},O.prototype.close=function(){this._worker?this._worker.postMessage({cmd:"stop"}):this._controller.stop()},O.prototype.seek=function(A){this._worker?this._worker.postMessage({cmd:"seek",param:A}):this._controller.seek(A)},O.prototype.pause=function(){this._worker?this._worker.postMessage({cmd:"pause"}):this._controller.pause()},O.prototype.resume=function(){this._worker?this._worker.postMessage({cmd:"resume"}):this._controller.resume()},O.prototype._onInitSegment=function(A,G){var m=this;Promise.resolve().then(function(){m._emitter.emit(b.default.INIT_SEGMENT,A,G)})},O.prototype._onMediaSegment=function(A,G){var m=this;Promise.resolve().then(function(){m._emitter.emit(b.default.MEDIA_SEGMENT,A,G)})},O.prototype._onLoadingComplete=function(){var A=this;Promise.resolve().then(function(){A._emitter.emit(b.default.LOADING_COMPLETE)})},O.prototype._onRecoveredEarlyEof=function(){var A=this;Promise.resolve().then(function(){A._emitter.emit(b.default.RECOVERED_EARLY_EOF)})},O.prototype._onMediaInfo=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.MEDIA_INFO,A)})},O.prototype._onMetaDataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.METADATA_ARRIVED,A)})},O.prototype._onScriptDataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SCRIPTDATA_ARRIVED,A)})},O.prototype._onTimedID3MetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.TIMED_ID3_METADATA_ARRIVED,A)})},O.prototype._onPGSSubtitleArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.PGS_SUBTITLE_ARRIVED,A)})},O.prototype._onSynchronousKLVMetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,A)})},O.prototype._onAsynchronousKLVMetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,A)})},O.prototype._onSMPTE2038MetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SMPTE2038_METADATA_ARRIVED,A)})},O.prototype._onSEIArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SEI_ARRIVED,A)})},O.prototype._onSCTE35MetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SCTE35_METADATA_ARRIVED,A)})},O.prototype._onPESPrivateDataDescriptor=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.PES_PRIVATE_DATA_DESCRIPTOR,A)})},O.prototype._onPESPrivateDataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.PES_PRIVATE_DATA_ARRIVED,A)})},O.prototype._onStatisticsInfo=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.STATISTICS_INFO,A)})},O.prototype._onIOError=function(A,G){var m=this;Promise.resolve().then(function(){m._emitter.emit(b.default.IO_ERROR,A,G)})},O.prototype._onDemuxError=function(A,G){var m=this;Promise.resolve().then(function(){m._emitter.emit(b.default.DEMUX_ERROR,A,G)})},O.prototype._onRecommendSeekpoint=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.RECOMMEND_SEEKPOINT,A)})},O.prototype._onLoggingConfigChanged=function(A){this._worker&&this._worker.postMessage({cmd:"logging_config",param:A})},O.prototype._onWorkerMessage=function(A){var G=A.data,m=G.data;if(G.msg==="destroyed"||this._workerDestroying)return this._workerDestroying=!1,this._worker.terminate(),void(this._worker=null);switch(G.msg){case b.default.INIT_SEGMENT:case b.default.MEDIA_SEGMENT:this._emitter.emit(G.msg,m.type,m.data);break;case b.default.LOADING_COMPLETE:case b.default.RECOVERED_EARLY_EOF:this._emitter.emit(G.msg);break;case b.default.MEDIA_INFO:Object.setPrototypeOf(m,k.default.prototype),this._emitter.emit(G.msg,m);break;case b.default.METADATA_ARRIVED:case b.default.SCRIPTDATA_ARRIVED:case b.default.TIMED_ID3_METADATA_ARRIVED:case b.default.PGS_SUBTITLE_ARRIVED:case b.default.SYNCHRONOUS_KLV_METADATA_ARRIVED:case b.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED:case b.default.SMPTE2038_METADATA_ARRIVED:case b.default.SCTE35_METADATA_ARRIVED:case b.default.SEI_ARRIVED:case b.default.PES_PRIVATE_DATA_DESCRIPTOR:case b.default.PES_PRIVATE_DATA_ARRIVED:case b.default.STATISTICS_INFO:this._emitter.emit(G.msg,m);break;case b.default.IO_ERROR:case b.default.DEMUX_ERROR:this._emitter.emit(G.msg,m.type,m.info);break;case b.default.RECOMMEND_SEEKPOINT:this._emitter.emit(G.msg,m);break;case"logcat_callback":R.default.emitter.emit("log",m.type,m.logcat)}},O}();Q.default=w},886:function(le,Q,D){D.r(Q),D.d(Q,{default:function(){return li}});var X=D(7),P=D.n(X),_=D(856),S=D(994),R=D(955);function v(n,i,t){var e=n;if(i+t=128){i.push(String.fromCharCode(65535&o)),e+=2;continue}}else if(t[e]<240){if(v(t,e,2)&&(o=(15&t[e])<<12|(63&t[e+1])<<6|63&t[e+2])>=2048&&(63488&o)!=55296){i.push(String.fromCharCode(65535&o)),e+=3;continue}}else if(t[e]<248){var o;if(v(t,e,3)&&(o=(7&t[e])<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])>65536&&o<1114112){o-=65536,i.push(String.fromCharCode(o>>>10|55296)),i.push(String.fromCharCode(1023&o|56320)),e+=4;continue}}i.push(String.fromCharCode(65533)),++e}return i.join("")},k=D(867),w=(I=new ArrayBuffer(2),new DataView(I).setInt16(0,256,!0),new Int16Array(I)[0]===256),O=function(){function n(){}return n.parseScriptData=function(i,t,e){var a={};try{var o=n.parseValue(i,t,e),r=n.parseValue(i,t+o.size,e-o.size);a[o.data]=r.data}catch(s){_.default.e("AMF",s.toString())}return a},n.parseObject=function(i,t,e){if(e<3)throw new k.IllegalStateException("Data not enough when parse ScriptDataObject");var a=n.parseString(i,t,e),o=n.parseValue(i,t+a.size,e-a.size),r=o.objectEnd;return{data:{name:a.data,value:o.data},size:a.size+o.size,objectEnd:r}},n.parseVariable=function(i,t,e){return n.parseObject(i,t,e)},n.parseString=function(i,t,e){if(e<2)throw new k.IllegalStateException("Data not enough when parse String");var a=new DataView(i,t,e).getUint16(0,!w);return{data:a>0?b(new Uint8Array(i,t+2,a)):"",size:2+a}},n.parseLongString=function(i,t,e){if(e<4)throw new k.IllegalStateException("Data not enough when parse LongString");var a=new DataView(i,t,e).getUint32(0,!w);return{data:a>0?b(new Uint8Array(i,t+4,a)):"",size:4+a}},n.parseDate=function(i,t,e){if(e<10)throw new k.IllegalStateException("Data size invalid when parse Date");var a=new DataView(i,t,e),o=a.getFloat64(0,!w),r=a.getInt16(8,!w);return{data:new Date(o+=60*r*1000),size:10}},n.parseValue=function(i,t,e){if(e<1)throw new k.IllegalStateException("Data not enough when parse Value");var a,o=new DataView(i,t,e),r=1,s=o.getUint8(0),d=!1;try{switch(s){case 0:a=o.getFloat64(1,!w),r+=8;break;case 1:a=!!o.getUint8(1),r+=1;break;case 2:var l=n.parseString(i,t+1,e-1);a=l.data,r+=l.size;break;case 3:a={};var y=0;for((16777215&o.getUint32(e-4,!w))==9&&(y=3);r32)throw new k.InvalidArgumentException("ExpGolomb: readBits() bits exceeded max 32bits!");if(i<=this._current_word_bits_left){var t=this._current_word>>>32-i;return this._current_word<<=i,this._current_word_bits_left-=i,t}var e=this._current_word_bits_left?this._current_word:0;e>>>=32-this._current_word_bits_left;var a=i-this._current_word_bits_left;this._fillCurrentWord();var o=Math.min(a,this._current_word_bits_left),r=this._current_word>>>32-o;return this._current_word<<=o,this._current_word_bits_left-=o,e<>>i)return this._current_word<<=i,this._current_word_bits_left-=i,i;return this._fillCurrentWord(),i+this._skipLeadingZero()},n.prototype.readUEG=function(){var i=this._skipLeadingZero();return this.readBits(i+1)-1},n.prototype.readSEG=function(){var i=this.readUEG();return 1&i?i+1>>>1:-1*(i>>>1)},n}(),G=function(){function n(){}return n._ebsp2rbsp=function(i){for(var t=i,e=t.byteLength,a=new Uint8Array(e),o=0,r=0;r=2&&t[r]===3&&t[r-1]===0&&t[r-2]===0||(a[o]=t[r],o++);return new Uint8Array(a.buffer,0,o)},n.parseSPS=function(i){for(var t=i.subarray(1,4),e="avc1.",a=0;a<3;a++){var o=t[a].toString(16);o.length<2&&(o="0"+o),e+=o}var r=n._ebsp2rbsp(i),s=new A(r);s.readByte();var d=s.readByte();s.readByte();var l=s.readByte();s.readUEG();var y=n.getProfileString(d),f=n.getLevelString(l),g=1,T=420,B=8,F=8;if((d===100||d===110||d===122||d===244||d===44||d===83||d===86||d===118||d===128||d===138||d===144)&&((g=s.readUEG())===3&&s.readBits(1),g<=3&&(T=[0,420,422,444][g]),B=s.readUEG()+8,F=s.readUEG()+8,s.readBits(1),s.readBool()))for(var q=g!==3?8:12,Z=0;Z0&&ye<16?(Ce=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ye-1],we=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ye-1]):ye===255&&(Ce=s.readByte()<<8|s.readByte(),we=s.readByte()<<8|s.readByte())}if(s.readBool()&&s.readBool(),s.readBool()&&(s.readBits(4),s.readBool()&&s.readBits(24)),s.readBool()&&(s.readUEG(),s.readUEG()),s.readBool()){var Oe=s.readBits(32),Ve=s.readBits(32);pe=s.readBool(),Te=(be=Ve)/(Be=2*Oe)}}var xe=1;Ce===1&&we===1||(xe=Ce/we);var Ge=0,Le=0;g===0?(Ge=1,Le=2-ae):(Ge=g===3?1:2,Le=(g===1?2:1)*(2-ae));var He=16*(ve+1),qe=16*(ne+1)*(2-ae);He-=(ge+ce)*Ge,qe-=(De+Se)*Le;var tt=Math.ceil(He*xe);return s.destroy(),s=null,{codec_mimetype:e,profile_idc:d,level_idc:l,profile_string:y,level_string:f,chroma_format_idc:g,bit_depth:B,bit_depth_luma:B,bit_depth_chroma:F,ref_frames:he,chroma_format:T,chroma_format_string:n.getChromaFormatString(T),frame_rate:{fixed:pe,fps:Te,fps_den:Be,fps_num:be},sar_ratio:{width:Ce,height:we},codec_size:{width:He,height:qe},present_size:{width:tt,height:qe}}},n._skipScalingList=function(i,t){for(var e=8,a=8,o=0;o=2&&t[r]===3&&t[r-1]===0&&t[r-2]===0||(a[o]=t[r],o++);return new Uint8Array(a.buffer,0,o)},n.parseVPS=function(i){var t=n._ebsp2rbsp(i),e=new A(t);return e.readByte(),e.readByte(),e.readBits(4),e.readBits(2),e.readBits(6),{num_temporal_layers:e.readBits(3)+1,temporal_id_nested:e.readBool()}},n.parseSPS=function(i){var t=n._ebsp2rbsp(i),e=new A(t);e.readByte(),e.readByte();for(var a=0,o=0,r=0,s=0,d=(e.readBits(4),e.readBits(3)),l=(e.readBool(),e.readBits(2)),y=e.readBool(),f=e.readBits(5),g=e.readByte(),T=e.readByte(),B=e.readByte(),F=e.readByte(),q=e.readByte(),Z=e.readByte(),U=e.readByte(),H=e.readByte(),he=e.readByte(),ve=e.readByte(),ne=e.readByte(),ae=[],ge=[],ce=0;ce0)for(ce=d;ce<8;ce++)e.readBits(2);for(ce=0;ce1&&e.readSEG(),ce=0;ce0&&Ze<=16?($e=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][Ze-1],Je=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][Ze-1]):Ze===255&&($e=e.readBits(16),Je=e.readBits(16))}if(e.readBool()&&e.readBool(),e.readBool()&&(e.readBits(3),e.readBool(),e.readBool()&&(e.readByte(),e.readByte(),e.readByte())),e.readBool()&&(e.readUEG(),e.readUEG()),e.readBool(),e.readBool(),e.readBool(),e.readBool()&&(e.readUEG(),e.readUEG(),e.readUEG(),e.readUEG()),e.readBool()&&(at=e.readBits(32),rt=e.readBits(32),e.readBool()&&e.readUEG(),e.readBool())){var ot,st,it=!1;for(ot=e.readBool(),st=e.readBool(),(ot||st)&&((it=e.readBool())&&(e.readByte(),e.readBits(5),e.readBool(),e.readBits(5)),e.readBits(4),e.readBits(4),it&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)),ce=0;ce<=d;ce++){var bt=e.readBool();Et=bt;var At=!0,dt=1;bt||(At=e.readBool());var Rt=!1;if(At?e.readUEG():Rt=e.readBool(),Rt||(dt=e.readUEG()+1),ot){for(Le=0;Le>3),r=!!(4&i[e]),s=!!(2&i[e]);i[e],e+=1,r&&(e+=1);var d=Number.POSITIVE_INFINITY;if(s){d=0;for(var l=0;;l++){var y=i[e++];if(d|=(127&y)<<7*l,!(128&y))break}}console.log(o),o===1?t=h(h({},n.parseSeuqneceHeader(i.subarray(e,e+d))),{sequence_header_data:i.subarray(a,e+d)}):(o==3&&t||o==6&&t)&&(t=n.parseOBUFrameHeader(i.subarray(e,e+d),0,0,t)),e+=d}return t},n.parseSeuqneceHeader=function(i){var t=new A(i),e=t.readBits(3),a=(t.readBool(),t.readBool()),o=!0,r=0,s=1,d=void 0,l=[];if(a)l.push({operating_point_idc:0,level:t.readBits(5),tier:0});else{if(t.readBool()){var y=t.readBits(32),f=t.readBits(32),g=t.readBool();if(g){for(var T=0;t.readBits(1)===0;)T+=1;T>=32||t.readBits(T)}r=f,s=y,o=g,t.readBool()&&(t.readBits(5),t.readBits(32),d=t.readBits(5),t.readBits(5))}for(var B=t.readBool(),F=t.readBits(5),q=0;q<=F;q++){var Z=t.readBits(12),U=t.readBits(5),H=U>7?t.readBits(1):0;l.push({operating_point_idc:Z,level:U,tier:H}),B&&t.readBool()&&t.readBits(4)}}var he=l[0],ve=he.level,ne=he.tier,ae=t.readBits(4),ge=t.readBits(4),ce=t.readBits(ae+1)+1,De=t.readBits(ge+1)+1,Se=!1;a||(Se=t.readBool()),Se&&(t.readBits(4),t.readBits(4)),t.readBool(),t.readBool(),t.readBool();var Ce=!1,we=2,Te=2,pe=0;a||(t.readBool(),t.readBool(),t.readBool(),t.readBool(),(Ce=t.readBool())&&(t.readBool(),t.readBool()),Te=(we=t.readBool()?2:t.readBits(1))?t.readBool()?2:t.readBits(1):2,pe=Ce?t.readBits(3)+1:0);var be=t.readBool(),Be=(t.readBool(),t.readBool(),t.readBool()),ye=8;ye=e===2&&Be?t.readBool()?12:10:Be?10:8;var Oe=!1;e!==1&&(Oe=t.readBool()),t.readBool()&&(t.readBits(8),t.readBits(8),t.readBits(8));var Ve=1,xe=1;return Oe?(t.readBits(1),Ve=1,xe=1):(t.readBits(1),e==0?(Ve=1,xe=1):e==1?(Ve=0,xe=0):ye==12?t.readBits(1)&&t.readBits(1):(Ve=1,xe=0),Ve&&xe&&t.readBits(2),t.readBits(1)),t.readBool(),t.destroy(),t=null,{codec_mimetype:"av01.".concat(e,".").concat(n.getLevelString(ve,ne),".").concat(ye.toString(10).padStart(2,"0")),level:ve,tier:ne,level_string:n.getLevelString(ve,ne),profile_idc:e,profile_string:"".concat(e),bit_depth:ye,ref_frames:1,chroma_format:n.getChromaFormat(Oe,Ve,xe),chroma_format_string:n.getChromaFormatString(Oe,Ve,xe),sequence_header:{frame_id_numbers_present_flag:Se,additional_frame_id_length_minus_1:void 0,delta_frame_id_length_minus_2:void 0,reduced_still_picture_header:a,decoder_model_info_present_flag:!1,operating_points:l,buffer_removal_time_length_minus_1:d,equal_picture_interval:o,seq_force_screen_content_tools:we,seq_force_integer_mv:Te,enable_order_hint:Ce,order_hint_bits:pe,enable_superres:be,frame_width_bit:ae+1,frame_height_bit:ge+1,max_frame_width:ce,max_frame_height:De},keyframe:void 0,frame_rate:{fixed:o,fps:r/s,fps_den:s,fps_num:r}}},n.parseOBUFrameHeader=function(i,t,e,a){var o=a.sequence_header,r=new A(i),s=(o.max_frame_width,o.max_frame_height,0);o.frame_id_numbers_present_flag&&(s=o.additional_frame_id_length_minus_1+o.delta_frame_id_length_minus_2+3);var d=0,l=!0,y=!0,f=!1;if(!o.reduced_still_picture_header){if(r.readBool())return a;l=(d=r.readBits(2))===2||d===0,(y=r.readBool())&&o.decoder_model_info_present_flag&&o.equal_picture_interval,y&&r.readBool(),f=!!(d===3||d===0&&y)||r.readBool()}a.keyframe=l,r.readBool();var g=o.seq_force_screen_content_tools;o.seq_force_screen_content_tools===2&&(g=r.readBits(1)),g&&(o.seq_force_integer_mv,o.seq_force_integer_mv==2&&r.readBits(1)),o.frame_id_numbers_present_flag&&r.readBits(s);var T;if(T=d==3||!o.reduced_still_picture_header&&r.readBool(),r.readBits(o.order_hint_bits),l||f||r.readBits(3),o.decoder_model_info_present_flag&&r.readBool()){for(var B=0;B<=o.operating_points_cnt_minus_1;B++)if(o.operating_points[B].decoder_model_present_for_this_op[B]){var F=o.operating_points[B].operating_point_idc;(F===0||F>>t&1&&F>>e+8&1)&&r.readBits(o.buffer_removal_time_length_minus_1+1)}}var q=255;if(d===3||d==0&&y||(q=r.readBits(8)),(l||q!==255)&&f&&o.enable_order_hint)for(var Z=0;Z<8;Z++)r.readBits(o.order_hint_bits);if(l){var U=n.frameSizeAndRenderSize(r,T,o);a.codec_size={width:U.FrameWidth,height:U.FrameHeight},a.present_size={width:U.RenderWidth,height:U.RenderHeight},a.sar_ratio={width:U.RenderWidth/U.FrameWidth,height:U.RenderHeight/U.FrameHeight}}return r.destroy(),r=null,a},n.frameSizeAndRenderSize=function(i,t,e){var{max_frame_width:a,max_frame_height:o}=e;t&&(a=i.readBits(e.frame_width_bit)+1,o=i.readBits(e.frame_height_bit)+1);var r=!1;e.enable_superres&&(r=i.readBool());var s=8;r&&(s=i.readBits(3)+9);var d=a;a=Math.floor((8*d+s/2)/s);var l=d,y=o;if(i.readBool()){var f=i.readBits(16)+1,g=i.readBits(16)+1;l=i.readBits(f)+1,y=i.readBits(g)+1}return{UpscaledWidth:d,FrameWidth:a,FrameHeight:o,RenderWidth:l,RenderHeight:y}},n.getLevelString=function(i,t){return"".concat(i.toString(10).padStart(2,"0")).concat(t===0?"M":"H")},n.getChromaFormat=function(i,t,e){return i?0:t===0&&e===0?3:t===1&&e===0?2:t===1&&e===1?1:Number.NaN},n.getChromaFormatString=function(i,t,e){return i?"4:0:0":t===0&&e===0?"4:4:4":t===1&&e===0?"4:2:2":t===1&&e===1?"4:2:0":"Unknown"},n}(),E=function(){};function W(n,i,t){if(!n||n.byteLength<2)return null;var e=1;t==="h265"&&(e=2);var a=function(y){for(var f=y,g=f.byteLength,T=new Uint8Array(g),B=0,F=0;F=2&&f[F]===3&&f[F-1]===0&&f[F-2]===0||(T[B]=f[F],B++);return new Uint8Array(T.buffer,0,B)}(n.subarray(e)),o=0;if(o===a.byteLength-1&&a[o]===128)return null;for(var r=0;o=a.byteLength)return null;r+=a[o++];for(var s=0;o=a.byteLength)return null;if(s+=a[o++],o+s>a.byteLength)return null;var d=new E;d.type=r,d.size=s;var l=a.subarray(o,o+s);return r===5&&s>=16&&(d.uuid=l.subarray(0,16),d.user_data=l.subarray(16)),i!==void 0&&(d.pts=i),d}var z,se=function(){function n(i,t){this.TAG="FLVDemuxer",this._config=t,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._onSeiArrived=null,this._dataOffset=i.dataOffset,this._firstParse=!0,this._dispatch=!1,this._hasAudio=i.hasAudioTrack,this._hasVideo=i.hasVideoTrack,this._hasAudioFlagOverrided=!1,this._hasVideoFlagOverrided=!1,this._audioInitialMetadataDispatched=!1,this._videoInitialMetadataDispatched=!1,this._mediaInfo=new R.default,this._mediaInfo.hasAudio=this._hasAudio,this._mediaInfo.hasVideo=this._hasVideo,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._naluLengthSize=4,this._timestampBase=0,this._timescale=1000,this._duration=0,this._durationOverrided=!1,this._referenceFrameRate={fixed:!0,fps:23.976,fps_num:23976,fps_den:1000},this._flvSoundRateTable=[5500,11025,22050,44100,48000],this._mpegSamplingRates=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],this._mpegAudioV10SampleRateTable=[44100,48000,32000,0],this._mpegAudioV20SampleRateTable=[22050,24000,16000,0],this._mpegAudioV25SampleRateTable=[11025,12000,8000,0],this._mpegAudioL1BitRateTable=[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1],this._mpegAudioL2BitRateTable=[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],this._mpegAudioL3BitRateTable=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],this._videoTrack={type:"video",id:1,sequenceNumber:0,samples:[],length:0},this._audioTrack={type:"audio",id:2,sequenceNumber:0,samples:[],length:0},this._littleEndian=function(){var e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]===256}()}return n.prototype.destroy=function(){this._mediaInfo=null,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._videoTrack=null,this._audioTrack=null,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._onSeiArrived=null},n.probe=function(i){var t=new Uint8Array(i);if(t.byteLength<9)return{needMoreData:!0};var e={match:!1};if(t[0]!==70||t[1]!==76||t[2]!==86||t[3]!==1)return e;var a,o=(4&t[4])>>>2!=0,r=!!(1&t[4]),s=(a=t)[5]<<24|a[6]<<16|a[7]<<8|a[8];return s<9?e:{match:!0,consumed:s,dataOffset:s,hasAudioTrack:o,hasVideoTrack:r}},n.prototype.bindDataSource=function(i){return i.onDataArrival=this.parseChunks.bind(this),this},Object.defineProperty(n.prototype,"onTrackMetadata",{get:function(){return this._onTrackMetadata},set:function(i){this._onTrackMetadata=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onMediaInfo",{get:function(){return this._onMediaInfo},set:function(i){this._onMediaInfo=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onMetaDataArrived",{get:function(){return this._onMetaDataArrived},set:function(i){this._onMetaDataArrived=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onScriptDataArrived",{get:function(){return this._onScriptDataArrived},set:function(i){this._onScriptDataArrived=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onSeiArrived",{get:function(){return this._onSeiArrived},set:function(i){this._onSeiArrived=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onError",{get:function(){return this._onError},set:function(i){this._onError=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onDataAvailable",{get:function(){return this._onDataAvailable},set:function(i){this._onDataAvailable=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"timestampBase",{get:function(){return this._timestampBase},set:function(i){this._timestampBase=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"overridedDuration",{get:function(){return this._duration},set:function(i){this._durationOverrided=!0,this._duration=i,this._mediaInfo.duration=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"overridedHasAudio",{set:function(i){this._hasAudioFlagOverrided=!0,this._hasAudio=i,this._mediaInfo.hasAudio=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"overridedHasVideo",{set:function(i){this._hasVideoFlagOverrided=!0,this._hasVideo=i,this._mediaInfo.hasVideo=i},enumerable:!1,configurable:!0}),n.prototype.resetMediaInfo=function(){this._mediaInfo=new R.default},n.prototype._isInitialMetadataDispatched=function(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!(this._hasAudio||!this._hasVideo)&&this._videoInitialMetadataDispatched},n.prototype.parseChunks=function(i,t){if(!(this._onError&&this._onMediaInfo&&this._onTrackMetadata&&this._onDataAvailable))throw new k.IllegalStateException("Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var e=0,a=this._littleEndian;if(t===0){if(!(i.byteLength>13))return 0;e=n.probe(i).dataOffset}for(this._firstParse&&(this._firstParse=!1,t+e!==this._dataOffset&&_.default.w(this.TAG,"First time parsing but chunk byteStart invalid!"),(o=new DataView(i,e)).getUint32(0,!a)!==0&&_.default.w(this.TAG,"PrevTagSize0 !== 0 !!!"),e+=4);ei.byteLength)break;var r=o.getUint8(0),s=16777215&o.getUint32(0,!a);if(e+11+s+4>i.byteLength)break;if(r===8||r===9||r===18){var d=o.getUint8(4),l=o.getUint8(5),y=o.getUint8(6)|l<<8|d<<16|o.getUint8(7)<<24;16777215&o.getUint32(7,!a)&&_.default.w(this.TAG,"Meet tag which has StreamID != 0!");var f=e+11;switch(r){case 8:this._parseAudioData(i,f,s,y);break;case 9:this._parseVideoData(i,f,s,y,t+e);break;case 18:this._parseScriptData(i,f,s)}var g=o.getUint32(11+s,!a);g!==11+s&&_.default.w(this.TAG,"Invalid PrevTagSize ".concat(g)),e+=11+s+4}else _.default.w(this.TAG,"Unsupported tag type ".concat(r,", skipped")),e+=11+s+4}return this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack),e},n.prototype._parseScriptData=function(i,t,e){var a=O.parseScriptData(i,t,e);if(a.hasOwnProperty("onMetaData")){if(a.onMetaData==null||typeof a.onMetaData!="object")return void _.default.w(this.TAG,"Invalid onMetaData structure!");this._metadata&&_.default.w(this.TAG,"Found another onMetaData tag!"),this._metadata=a;var o=this._metadata.onMetaData;if(this._onMetaDataArrived&&this._onMetaDataArrived(Object.assign({},o)),typeof o.hasAudio=="boolean"&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=o.hasAudio,this._mediaInfo.hasAudio=this._hasAudio),typeof o.hasVideo=="boolean"&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=o.hasVideo,this._mediaInfo.hasVideo=this._hasVideo),typeof o.audiodatarate=="number"&&(this._mediaInfo.audioDataRate=o.audiodatarate),typeof o.videodatarate=="number"&&(this._mediaInfo.videoDataRate=o.videodatarate),typeof o.width=="number"&&(this._mediaInfo.width=o.width),typeof o.height=="number"&&(this._mediaInfo.height=o.height),typeof o.duration=="number"){if(!this._durationOverrided){var r=Math.floor(o.duration*this._timescale);this._duration=r,this._mediaInfo.duration=r}}else this._mediaInfo.duration=0;if(typeof o.framerate=="number"){var s=Math.floor(1000*o.framerate);if(s>0){var d=s/1000;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=d,this._referenceFrameRate.fps_num=s,this._referenceFrameRate.fps_den=1000,this._mediaInfo.fps=d}}if(typeof o.keyframes=="object"){this._mediaInfo.hasKeyframesIndex=!0;var l=o.keyframes;this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(l),o.keyframes=null}else this._mediaInfo.hasKeyframesIndex=!1;this._dispatch=!1,this._mediaInfo.metadata=o,_.default.v(this.TAG,"Parsed onMetaData"),this._mediaInfo.isComplete()&&this._onMediaInfo(this._mediaInfo)}Object.keys(a).length>0&&this._onScriptDataArrived&&this._onScriptDataArrived(Object.assign({},a))},n.prototype._parseSEIPayload=function(i,t,e){var a=W(i,t,e);a&&typeof this._onSeiArrived=="function"&&this._onSeiArrived(a)},n.prototype._parseKeyframesIndex=function(i){for(var t=[],e=[],a=1;a>>4;if(r!==9)if(r===2||r===3||r===10){var s=0,d=(12&o)>>>2;if(d>=0&&d<=4){s=this._flvSoundRateTable[d];var l=(2&o)>>>1,y=1&o,f=this._audioMetadata,g=this._audioTrack;if(f||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(f=this._audioMetadata={}).type="audio",f.id=g.id,f.timescale=this._timescale,f.duration=this._duration,f.audioSampleRate=s,f.channelCount=y===0?1:2),r===10){var T=this._parseAACAudioData(i,t+1,e-1);if(T==null)return;if(T.packetType===0){if(f.config){if(u(T.data.config,f.config))return;_.default.w(this.TAG,"AudioSpecificConfig has been changed, re-generate initialization segment")}var B=T.data;f.audioSampleRate=B.samplingRate,f.channelCount=B.channelCount,f.codec=B.codec,f.originalCodec=B.originalCodec,f.config=B.config,f.refSampleDuration=1024/f.audioSampleRate*f.timescale,_.default.v(this.TAG,"Parsed AudioSpecificConfig"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",f),(U=this._mediaInfo).audioCodec=f.originalCodec,U.audioSampleRate=f.audioSampleRate,U.audioChannelCount=f.channelCount,U.hasVideo?U.videoCodec!=null&&(U.mimeType='video/x-flv; codecs="'+U.videoCodec+","+U.audioCodec+'"'):U.mimeType='video/x-flv; codecs="'+U.audioCodec+'"',U.isComplete()&&this._onMediaInfo(U)}else if(T.packetType===1){var F=this._timestampBase+a,q={unit:T.data,length:T.data.byteLength,dts:F,pts:F};g.samples.push(q),g.length+=T.data.length}else _.default.e(this.TAG,"Flv: Unsupported AAC data type ".concat(T.packetType))}else if(r===2){if(!f.codec){if((B=this._parseMP3AudioData(i,t+1,e-1,!0))==null)return;f.audioSampleRate=B.samplingRate,f.channelCount=B.channelCount,f.codec=B.codec,f.originalCodec=B.originalCodec,f.refSampleDuration=1152/f.audioSampleRate*f.timescale,_.default.v(this.TAG,"Parsed MPEG Audio Frame Header"),this._audioInitialMetadataDispatched=!0,this._onTrackMetadata("audio",f),(U=this._mediaInfo).audioCodec=f.codec,U.audioSampleRate=f.audioSampleRate,U.audioChannelCount=f.channelCount,U.audioDataRate=B.bitRate,U.hasVideo?U.videoCodec!=null&&(U.mimeType='video/x-flv; codecs="'+U.videoCodec+","+U.audioCodec+'"'):U.mimeType='video/x-flv; codecs="'+U.audioCodec+'"',U.isComplete()&&this._onMediaInfo(U)}if((H=this._parseMP3AudioData(i,t+1,e-1,!1))==null)return;F=this._timestampBase+a;var Z={unit:H,length:H.byteLength,dts:F,pts:F};g.samples.push(Z),g.length+=H.length}else if(r===3){var U;f.codec||(f.audioSampleRate=s,f.sampleSize=8*(l+1),f.littleEndian=!0,f.codec="ipcm",f.originalCodec="ipcm",this._audioInitialMetadataDispatched=!0,this._onTrackMetadata("audio",f),(U=this._mediaInfo).audioCodec=f.codec,U.audioSampleRate=f.audioSampleRate,U.audioChannelCount=f.channelCount,U.audioDataRate=f.sampleSize*f.audioSampleRate,U.hasVideo?U.videoCodec!=null&&(U.mimeType='video/x-flv; codecs="'+U.videoCodec+","+U.audioCodec+'"'):U.mimeType='video/x-flv; codecs="'+U.audioCodec+'"',U.isComplete()&&this._onMediaInfo(U));var H=new Uint8Array(i,t+1,e-1),he=(F=this._timestampBase+a,{unit:H,length:H.byteLength,dts:F,pts:F});g.samples.push(he),g.length+=H.length}}else this._onError(m.default.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+d)}else this._onError(m.default.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+r);else{if(e<=5)return void _.default.w(this.TAG,"Flv: Invalid audio packet, missing AudioFourCC in Ehnanced FLV payload!");var ve=15&o,ne=String.fromCharCode.apply(String,new Uint8Array(i,t,e).slice(1,5));switch(ne){case"Opus":this._parseOpusAudioPacket(i,t+5,e-5,a,ve);break;case"fLaC":this._parseFlacAudioPacket(i,t+5,e-5,a,ve);break;default:this._onError(m.default.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec: "+ne)}}}},n.prototype._parseAACAudioData=function(i,t,e){if(!(e<=1)){var a={},o=new Uint8Array(i,t,e);return a.packetType=o[0],o[0]===0?a.data=this._parseAACAudioSpecificConfig(i,t+1,e-1):a.data=o.subarray(1),a}_.default.w(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!")},n.prototype._parseAACAudioSpecificConfig=function(i,t,e){var a,o,r=new Uint8Array(i,t,e),s=null,d=0,l=null;if(d=a=r[0]>>>3,(o=(7&r[0])<<1|r[1]>>>7)<0||o>=this._mpegSamplingRates.length)this._onError(m.default.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var y=this._mpegSamplingRates[o],f=(120&r[1])>>>3;if(!(f<0||f>=8)){d===5&&(l=(7&r[1])<<1|r[2]>>>7,r[2]);var g=self.navigator.userAgent.toLowerCase();return g.indexOf("firefox")!==-1?o>=6?(d=5,s=[,,,,],l=o-3):(d=2,s=[,,],l=o):g.indexOf("android")!==-1?(d=2,s=[,,],l=o):(d=5,l=o,s=[,,,,],o>=6?l=o-3:f===1&&(d=2,s=[,,],l=o)),s[0]=d<<3,s[0]|=(15&o)>>>1,s[1]=(15&o)<<7,s[1]|=(15&f)<<3,d===5&&(s[1]|=(15&l)>>>1,s[2]=(1&l)<<7,s[2]|=8,s[3]=0),{config:s,samplingRate:y,channelCount:f,codec:"mp4a.40."+d,originalCodec:"mp4a.40."+a}}this._onError(m.default.FORMAT_ERROR,"Flv: AAC invalid channel configuration")}},n.prototype._parseMP3AudioData=function(i,t,e,a){if(!(e<4)){this._littleEndian;var o=new Uint8Array(i,t,e),r=null;if(a){if(o[0]!==255)return;var s=o[1]>>>3&3,d=(6&o[1])>>1,l=(240&o[2])>>>4,y=(12&o[2])>>>2,f=3&~(o[3]>>>6)?2:1,g=0,T=0;switch(s){case 0:g=this._mpegAudioV25SampleRateTable[y];break;case 2:g=this._mpegAudioV20SampleRateTable[y];break;case 3:g=this._mpegAudioV10SampleRateTable[y]}switch(d){case 1:l>>16&255,B[2]=r.byteLength>>>8&255,B[3]=r.byteLength>>>0&255;var F={config:B,channelCount:g,samplingFrequence:f,sampleSize:T,codec:"flac",originalCodec:"flac"};if(a.config){if(u(F.config,a.config))return;_.default.w(this.TAG,"FlacSequenceHeader has been changed, re-generate initialization segment")}a.audioSampleRate=F.samplingFrequence,a.channelCount=F.channelCount,a.sampleSize=F.sampleSize,a.codec=F.codec,a.originalCodec=F.originalCodec,a.config=F.config,a.refSampleDuration=y!=null?1000*y/F.samplingFrequence:null,_.default.v(this.TAG,"Parsed FlacSequenceHeader"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",a);var q=this._mediaInfo;q.audioCodec=a.originalCodec,q.audioSampleRate=a.audioSampleRate,q.audioChannelCount=a.channelCount,q.hasVideo?q.videoCodec!=null&&(q.mimeType='video/x-flv; codecs="'+q.videoCodec+","+q.audioCodec+'"'):q.mimeType='video/x-flv; codecs="'+q.audioCodec+'"',q.isComplete()&&this._onMediaInfo(q)},n.prototype._parseFlacAudioData=function(i,t,e,a){var o=this._audioTrack,r=new Uint8Array(i,t,e),s=this._timestampBase+a,d={unit:r,length:r.byteLength,dts:s,pts:s};o.samples.push(d),o.length+=r.length},n.prototype._parseVideoData=function(i,t,e,a,o){if(e<=1)_.default.w(this.TAG,"Flv: Invalid video packet, missing VideoData payload!");else if(this._hasVideoFlagOverrided!==!0||this._hasVideo!==!1){var r=new Uint8Array(i,t,e)[0],s=(112&r)>>>4;if(128&r){var d=15&r,l=String.fromCharCode.apply(String,new Uint8Array(i,t,e).slice(1,5));if(l==="hvc1")this._parseEnhancedHEVCVideoPacket(i,t+5,e-5,a,o,s,d);else{if(l!=="av01")return void this._onError(m.default.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(l));this._parseEnhancedAV1VideoPacket(i,t+5,e-5,a,o,s,d)}}else{var y=15&r;if(y===7)this._parseAVCVideoPacket(i,t+1,e-1,a,o,s);else{if(y!==12)return void this._onError(m.default.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(y));this._parseHEVCVideoPacket(i,t+1,e-1,a,o,s)}}}},n.prototype._parseAVCVideoPacket=function(i,t,e,a,o,r){if(e<4)_.default.w(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var s=this._littleEndian,d=new DataView(i,t,e),l=d.getUint8(0),y=(16777215&d.getUint32(0,!s))<<8>>8;if(l===0)this._parseAVCDecoderConfigurationRecord(i,t+4,e-4);else if(l===1)this._parseAVCVideoData(i,t+4,e-4,a,o,r,y);else if(l!==2)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(l))}},n.prototype._parseHEVCVideoPacket=function(i,t,e,a,o,r){if(e<4)_.default.w(this.TAG,"Flv: Invalid HEVC packet, missing HEVCPacketType or/and CompositionTime");else{var s=this._littleEndian,d=new DataView(i,t,e),l=d.getUint8(0),y=(16777215&d.getUint32(0,!s))<<8>>8;if(l===0)this._parseHEVCDecoderConfigurationRecord(i,t+4,e-4);else if(l===1)this._parseHEVCVideoData(i,t+4,e-4,a,o,r,y);else if(l!==2)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(l))}},n.prototype._parseEnhancedHEVCVideoPacket=function(i,t,e,a,o,r,s){var d=this._littleEndian,l=new DataView(i,t,e);if(s===0)this._parseHEVCDecoderConfigurationRecord(i,t,e);else if(s===1){var y=(4294967040&l.getUint32(0,!d))>>8;this._parseHEVCVideoData(i,t+3,e-3,a,o,r,y)}else if(s===3)this._parseHEVCVideoData(i,t,e,a,o,r,0);else if(s!==2)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(s))},n.prototype._parseEnhancedAV1VideoPacket=function(i,t,e,a,o,r,s){if(this._littleEndian,new DataView(i,t,e),s===0)this._parseAV1CodecConfigurationRecord(i,t,e);else if(s===1)this._parseAV1VideoData(i,t,e,a,o,r,0);else{if(s===5)return void this._onError(m.default.FORMAT_ERROR,"Flv: Not Supported MP2T AV1 video packet type ".concat(s));if(s!==2)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(s))}},n.prototype._parseAVCDecoderConfigurationRecord=function(i,t,e){if(e<7)_.default.w(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");else{var a=this._videoMetadata,o=this._videoTrack,r=this._littleEndian,s=new DataView(i,t,e);if(a){if(a.avcc!==void 0){var d=new Uint8Array(i,t,e);if(u(d,a.avcc))return;_.default.w(this.TAG,"AVCDecoderConfigurationRecord has been changed, re-generate initialization segment")}}else this._hasVideo===!1&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),(a=this._videoMetadata={}).type="video",a.id=o.id,a.timescale=this._timescale,a.duration=this._duration;var l=s.getUint8(0),y=s.getUint8(1);if(s.getUint8(2),s.getUint8(3),l===1&&y!==0)if(this._naluLengthSize=1+(3&s.getUint8(4)),this._naluLengthSize===3||this._naluLengthSize===4){var f=31&s.getUint8(5);if(f!==0){f>1&&_.default.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ".concat(f));for(var g=6,T=0;T1&&_.default.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ".concat(ge)),g++,T=0;T=e){_.default.w(this.TAG,"Malformed Nalu near timestamp ".concat(B,", offset = ").concat(g,", dataSize = ").concat(e));break}var q=l.getUint32(g,!d);if(T===3&&(q>>>=8),q>e-T)return void _.default.w(this.TAG,"Malformed Nalus near timestamp ".concat(B,", NaluSize > DataSize!"));var Z=31&l.getUint8(g+T);Z===5&&(F=!0);var U=new Uint8Array(i,t+g,T+q),H={type:Z,data:U};y.push(H),f+=U.byteLength,Z===6&&this._parseSEIPayload(U.subarray(T),B+s,"h264"),g+=T+q}if(y.length){var he=this._videoTrack,ve={units:y,length:f,isKeyframe:F,dts:B,cts:s,pts:B+s};F&&(ve.fileposition=o),he.samples.push(ve),he.length+=f}},n.prototype._parseHEVCVideoData=function(i,t,e,a,o,r,s){for(var d=this._littleEndian,l=new DataView(i,t,e),y=[],f=0,g=0,T=this._naluLengthSize,B=this._timestampBase+a,F=r===1;g=e){_.default.w(this.TAG,"Malformed Nalu near timestamp ".concat(B,", offset = ").concat(g,", dataSize = ").concat(e));break}var q=l.getUint32(g,!d);if(T===3&&(q>>>=8),q>e-T)return void _.default.w(this.TAG,"Malformed Nalus near timestamp ".concat(B,", NaluSize > DataSize!"));var Z=l.getUint8(g+T)>>1&63;Z!==19&&Z!==20&&Z!==21||(F=!0);var U=new Uint8Array(i,t+g,T+q),H={type:Z,data:U};y.push(H),f+=U.byteLength,Z!==39&&Z!==40||this._parseSEIPayload(U.subarray(T),B+s,"h265"),g+=T+q}if(y.length){var he=this._videoTrack,ve={units:y,length:f,isKeyframe:F,dts:B,cts:s,pts:B+s};F&&(ve.fileposition=o),he.samples.push(ve),he.length+=f}},n.prototype._parseAV1VideoData=function(i,t,e,a,o,r,s){this._littleEndian,new DataView(i,t,e);var d,l=[],y=this._timestampBase+a,f=r===1;if(f){var g=this._videoMetadata,T=p.parseOBUs(new Uint8Array(i,t,e),g.extra);if(T==null)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid AV1 VideoData");console.log(T),g.codecWidth=T.codec_size.width,g.codecHeight=T.codec_size.height,g.presentWidth=T.present_size.width,g.presentHeight=T.present_size.height,g.sarRatio=T.sar_ratio;var B=this._mediaInfo;B.width=g.codecWidth,B.height=g.codecHeight,B.sarNum=g.sarRatio.width,B.sarDen=g.sarRatio.height,_.default.v(this.TAG,"Parsed AV1DecoderConfigurationRecord"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._videoInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("video",g)}if(d=e,l.push({unitType:0,data:new Uint8Array(i,t+0,e)}),l.length){var F=this._videoTrack,q={units:l,length:d,isKeyframe:f,dts:y,cts:s,pts:y+s};f&&(q.fileposition=o),F.samples.push(q),F.length+=d}},n}(),de=se,me=function(){function n(){}return n.prototype.destroy=function(){this.onError=null,this.onMediaInfo=null,this.onMetaDataArrived=null,this.onTrackMetadata=null,this.onDataAvailable=null,this.onTimedID3Metadata=null,this.onPGSSubtitleData=null,this.onSynchronousKLVMetadata=null,this.onAsynchronousKLVMetadata=null,this.onSMPTE2038Metadata=null,this.onSEI=null,this.onSCTE35Metadata=null,this.onPESPrivateData=null,this.onPESPrivateDataDescriptor=null},n}(),te=function(){this.program_pmt_pid={}};(function(n){n[n.kMPEG1Audio=3]="kMPEG1Audio",n[n.kMPEG2Audio=4]="kMPEG2Audio",n[n.kPESPrivateData=6]="kPESPrivateData",n[n.kADTSAAC=15]="kADTSAAC",n[n.kLOASAAC=17]="kLOASAAC",n[n.kAC3=129]="kAC3",n[n.kEAC3=135]="kEAC3",n[n.kMetadata=21]="kMetadata",n[n.kSCTE35=134]="kSCTE35",n[n.kPGS=144]="kPGS",n[n.kH264=27]="kH264",n[n.kH265=36]="kH265"})(z||(z={}));var ee,Re=function(){this.pid_stream_type={},this.common_pids={h264:void 0,h265:void 0,av1:void 0,adts_aac:void 0,loas_aac:void 0,opus:void 0,ac3:void 0,eac3:void 0,mp3:void 0},this.pes_private_data_pids={},this.timed_id3_pids={},this.pgs_pids={},this.pgs_langs={},this.synchronous_klv_pids={},this.asynchronous_klv_pids={},this.scte_35_pids={},this.smpte2038_pids={}},J=function(){},ke=function(){},L=function(){this.slices=[],this.total_length=0,this.expected_length=0,this.file_position=0};(function(n){n[n.kUnspecified=0]="kUnspecified",n[n.kSliceNonIDR=1]="kSliceNonIDR",n[n.kSliceDPA=2]="kSliceDPA",n[n.kSliceDPB=3]="kSliceDPB",n[n.kSliceDPC=4]="kSliceDPC",n[n.kSliceIDR=5]="kSliceIDR",n[n.kSliceSEI=6]="kSliceSEI",n[n.kSliceSPS=7]="kSliceSPS",n[n.kSlicePPS=8]="kSlicePPS",n[n.kSliceAUD=9]="kSliceAUD",n[n.kEndOfSequence=10]="kEndOfSequence",n[n.kEndOfStream=11]="kEndOfStream",n[n.kFiller=12]="kFiller",n[n.kSPSExt=13]="kSPSExt",n[n.kReserved0=14]="kReserved0"})(ee||(ee={}));var c,C,j=function(){},fe=function(n){var i=n.data.byteLength;this.type=n.type,this.data=new Uint8Array(4+i),new DataView(this.data.buffer).setUint32(0,i),this.data.set(n.data,4)},re=function(){function n(i){this.TAG="H264AnnexBParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=i,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not find H264 startcode until payload end!")}return n.prototype.findNextStartCodeOffset=function(i){for(var t=i,e=this.data_;;){if(t+3>=e.byteLength)return this.eof_flag_=!0,e.byteLength;var a=e[t+0]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],o=e[t+0]<<16|e[t+1]<<8|e[t+2];if(a===1||o===1)return t;t++}},n.prototype.readNextNaluPayload=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_startcode_offset_,a=31&i[e+=(i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3])==1?4:3],o=(128&i[e])>>>7,r=this.findNextStartCodeOffset(e);if(this.current_startcode_offset_=r,!(a>=ee.kReserved0)&&o===0){var s=i.subarray(e,r);(t=new j).type=a,t.data=s}}return t},n}(),V=function(){function n(i,t,e){var a=8+i.byteLength+1+2+t.byteLength,o=!1;i[3]!==66&&i[3]!==77&&i[3]!==88&&(o=!0,a+=4);var r=this.data=new Uint8Array(a);r[0]=1,r[1]=i[1],r[2]=i[2],r[3]=i[3],r[4]=255,r[5]=225;var s=i.byteLength;r[6]=s>>>8,r[7]=255&s;var d=8;r.set(i,8),r[d+=s]=1;var l=t.byteLength;r[d+1]=l>>>8,r[d+2]=255&l,r.set(t,d+3),d+=3+l,o&&(r[d]=252|e.chroma_format_idc,r[d+1]=248|e.bit_depth_luma-8,r[d+2]=248|e.bit_depth_chroma-8,r[d+3]=0,d+=4)}return n.prototype.getData=function(){return this.data},n}();(function(n){n[n.kNull=0]="kNull",n[n.kAACMain=1]="kAACMain",n[n.kAAC_LC=2]="kAAC_LC",n[n.kAAC_SSR=3]="kAAC_SSR",n[n.kAAC_LTP=4]="kAAC_LTP",n[n.kAAC_SBR=5]="kAAC_SBR",n[n.kAAC_Scalable=6]="kAAC_Scalable",n[n.kLayer1=32]="kLayer1",n[n.kLayer2=33]="kLayer2",n[n.kLayer3=34]="kLayer3"})(c||(c={})),function(n){n[n.k96000Hz=0]="k96000Hz",n[n.k88200Hz=1]="k88200Hz",n[n.k64000Hz=2]="k64000Hz",n[n.k48000Hz=3]="k48000Hz",n[n.k44100Hz=4]="k44100Hz",n[n.k32000Hz=5]="k32000Hz",n[n.k24000Hz=6]="k24000Hz",n[n.k22050Hz=7]="k22050Hz",n[n.k16000Hz=8]="k16000Hz",n[n.k12000Hz=9]="k12000Hz",n[n.k11025Hz=10]="k11025Hz",n[n.k8000Hz=11]="k8000Hz",n[n.k7350Hz=12]="k7350Hz"}(C||(C={}));var Y,ie,oe=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],ue=(Y=function(n,i){return Y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a])},Y(n,i)},function(n,i){if(typeof i!="function"&&i!==null)throw TypeError("Class extends value "+String(i)+" is not a constructor or null");function t(){this.constructor=n}Y(n,i),n.prototype=i===null?Object.create(i):(t.prototype=i.prototype,new t)}),Ee=function(){},Pe=function(n){function i(){return n!==null&&n.apply(this,arguments)||this}return ue(i,n),i}(Ee),Ue=function(){function n(i){this.TAG="AACADTSParser",this.data_=i,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not found ADTS syncword until payload end")}return n.prototype.findNextSyncwordOffset=function(i){for(var t=i,e=this.data_;;){if(t+7>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<8|e[t+1])>>>4==4095)return t;t++}},n.prototype.readNextAACFrame=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_syncword_offset_,a=(8&i[e+1])>>>3,o=(6&i[e+1])>>>1,r=1&i[e+1],s=(192&i[e+2])>>>6,d=(60&i[e+2])>>>2,l=(1&i[e+2])<<2|(192&i[e+3])>>>6,y=(3&i[e+3])<<11|i[e+4]<<3|(224&i[e+5])>>>5;if(i[e+6],e+y>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var f=r===1?7:9,g=y-f;e+=f;var T=this.findNextSyncwordOffset(e+g);if(this.current_syncword_offset_=T,(a===0||a===1)&&o===0){var B=i.subarray(e,e+g);(t=new Ee).audio_object_type=s+1,t.sampling_freq_index=d,t.sampling_frequency=oe[d],t.channel_config=l,t.data=B}}return t},n.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},n.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},n}(),je=function(){function n(i){this.TAG="AACLOASParser",this.data_=i,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not found LOAS syncword until payload end")}return n.prototype.findNextSyncwordOffset=function(i){for(var t=i,e=this.data_;;){if(t+1>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<3|e[t+1]>>>5)==695)return t;t++}},n.prototype.getLATMValue=function(i){for(var t=i.readBits(2),e=0,a=0;a<=t;a++)e<<=8,e|=i.readByte();return e},n.prototype.readNextAACFrame=function(i){for(var t=this.data_,e=null;e==null&&!this.eof_flag_;){var a=this.current_syncword_offset_,o=(31&t[a+1])<<8|t[a+2];if(a+3+o>=this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var r=new A(t.subarray(a+3,a+3+o)),s=null;if(r.readBool()){if(i==null){_.default.w(this.TAG,"StreamMuxConfig Missing"),this.current_syncword_offset_=this.findNextSyncwordOffset(a+3+o),r.destroy();continue}s=i}else{var d=r.readBool();if(d&&r.readBool()){_.default.e(this.TAG,"audioMuxVersionA is Not Supported"),r.destroy();break}if(d&&this.getLATMValue(r),!r.readBool()){_.default.e(this.TAG,"allStreamsSameTimeFraming zero is Not Supported"),r.destroy();break}if(r.readBits(6)!==0){_.default.e(this.TAG,"more than 2 numSubFrames Not Supported"),r.destroy();break}if(r.readBits(4)!==0){_.default.e(this.TAG,"more than 2 numProgram Not Supported"),r.destroy();break}if(r.readBits(3)!==0){_.default.e(this.TAG,"more than 2 numLayer Not Supported"),r.destroy();break}var l=d?this.getLATMValue(r):0,y=r.readBits(5);l-=5;var f=r.readBits(4);l-=4;var g=r.readBits(4);l-=4,r.readBits(3),(l-=3)>0&&r.readBits(l);var T=r.readBits(3);if(T!==0){_.default.e(this.TAG,"frameLengthType = ".concat(T,". Only frameLengthType = 0 Supported")),r.destroy();break}r.readByte();var B=r.readBool();if(B)if(d)this.getLATMValue(r);else{for(var F=0;;){F<<=8;var q=r.readBool();if(F+=r.readByte(),!q)break}console.log(F)}r.readBool()&&r.readByte(),(s=new Pe).audio_object_type=y,s.sampling_freq_index=f,s.sampling_frequency=oe[s.sampling_freq_index],s.channel_config=g,s.other_data_present=B}for(var Z=0;;){var U=r.readByte();if(Z+=U,U!==255)break}for(var H=new Uint8Array(Z),he=0;he=6?(e=5,i=[,,,,],r=a-3):(e=2,i=[,,],r=a):s.indexOf("android")!==-1?(e=2,i=[,,],r=a):(e=5,r=a,i=[,,,,],a>=6?r=a-3:o===1&&(e=2,i=[,,],r=a)),i[0]=e<<3,i[0]|=(15&a)>>>1,i[1]=(15&a)<<7,i[1]|=(15&o)<<3,e===5&&(i[1]|=(15&r)>>>1,i[2]=(1&r)<<7,i[2]|=8,i[3]=0),this.config=i,this.sampling_rate=oe[a],this.channel_count=o,this.codec_mimetype="mp4a.40."+e,this.original_codec_mimetype="mp4a.40."+t},Xe=function(){},nt=function(){};(function(n){n[n.kSpliceNull=0]="kSpliceNull",n[n.kSpliceSchedule=4]="kSpliceSchedule",n[n.kSpliceInsert=5]="kSpliceInsert",n[n.kTimeSignal=6]="kTimeSignal",n[n.kBandwidthReservation=7]="kBandwidthReservation",n[n.kPrivateCommand=255]="kPrivateCommand"})(ie||(ie={}));var Ne,Qe=function(n){var i=n.readBool();return i?(n.readBits(6),{time_specified_flag:i,pts_time:4*n.readBits(31)+n.readBits(2)}):(n.readBits(7),{time_specified_flag:i})},ht=function(n){var i=n.readBool();return n.readBits(6),{auto_return:i,duration:4*n.readBits(31)+n.readBits(2)}},Ot=function(n,i){var t=i.readBits(8);return n?{component_tag:t}:{component_tag:t,splice_time:Qe(i)}},Pt=function(n){return{component_tag:n.readBits(8),utc_splice_time:n.readBits(32)}},xt=function(n){var i=n.readBits(32),t=n.readBool();n.readBits(7);var e={splice_event_id:i,splice_event_cancel_indicator:t};if(t)return e;if(e.out_of_network_indicator=n.readBool(),e.program_splice_flag=n.readBool(),e.duration_flag=n.readBool(),n.readBits(5),e.program_splice_flag)e.utc_splice_time=n.readBits(32);else{e.component_count=n.readBits(8),e.components=[];for(var a=0;a=e.byteLength)return this.eof_flag_=!0,e.byteLength;var a=e[t+0]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],o=e[t+0]<<16|e[t+1]<<8|e[t+2];if(a===1||o===1)return t;t++}},n.prototype.readNextNaluPayload=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_startcode_offset_,a=i[e+=(i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3])==1?4:3]>>1&63,o=(128&i[e])>>>7,r=this.findNextStartCodeOffset(e);if(this.current_startcode_offset_=r,o===0){var s=i.subarray(e,r);(t=new Ht).type=a,t.data=s}}return t},n}(),Wt=function(){function n(i,t,e,a){var o=23+(5+i.byteLength)+(5+t.byteLength)+(5+e.byteLength),r=this.data=new Uint8Array(o);r[0]=1,r[1]=(3&a.general_profile_space)<<6|(a.general_tier_flag?1:0)<<5|31&a.general_profile_idc,r[2]=a.general_profile_compatibility_flags_1,r[3]=a.general_profile_compatibility_flags_2,r[4]=a.general_profile_compatibility_flags_3,r[5]=a.general_profile_compatibility_flags_4,r[6]=a.general_constraint_indicator_flags_1,r[7]=a.general_constraint_indicator_flags_2,r[8]=a.general_constraint_indicator_flags_3,r[9]=a.general_constraint_indicator_flags_4,r[10]=a.general_constraint_indicator_flags_5,r[11]=a.general_constraint_indicator_flags_6,r[12]=a.general_level_idc,r[13]=240|(3840&a.min_spatial_segmentation_idc)>>8,r[14]=255&a.min_spatial_segmentation_idc,r[15]=252|3&a.parallelismType,r[16]=252|3&a.chroma_format_idc,r[17]=248|7&a.bit_depth_luma_minus8,r[18]=248|7&a.bit_depth_chroma_minus8,r[19]=0,r[20]=0,r[21]=(3&a.constant_frame_rate)<<6|(7&a.num_temporal_layers)<<3|(a.temporal_id_nested?1:0)<<2|3,r[22]=3,r[23]=128|Ne.kSliceVPS,r[24]=0,r[25]=1,r[26]=(65280&i.byteLength)>>8,r[27]=255&i.byteLength,r.set(i,28),r[23+(5+i.byteLength)+0]=128|Ne.kSliceSPS,r[23+(5+i.byteLength)+1]=0,r[23+(5+i.byteLength)+2]=1,r[23+(5+i.byteLength)+3]=(65280&t.byteLength)>>8,r[23+(5+i.byteLength)+4]=255&t.byteLength,r.set(t,23+(5+i.byteLength)+5),r[23+(5+i.byteLength+5+t.byteLength)+0]=128|Ne.kSlicePPS,r[23+(5+i.byteLength+5+t.byteLength)+1]=0,r[23+(5+i.byteLength+5+t.byteLength)+2]=1,r[23+(5+i.byteLength+5+t.byteLength)+3]=(65280&e.byteLength)>>8,r[23+(5+i.byteLength+5+t.byteLength)+4]=255&e.byteLength,r.set(e,23+(5+i.byteLength+5+t.byteLength)+5)}return n.prototype.getData=function(){return this.data},n}(),Yt=function(){},Xt=function(){},Qt=function(){},$t=[[64,64,80,80,96,96,112,112,128,128,160,160,192,192,224,224,256,256,320,320,384,384,448,448,512,512,640,640,768,768,896,896,1024,1024,1152,1152,1280,1280],[69,70,87,88,104,105,121,122,139,140,174,175,208,209,243,244,278,279,348,349,417,418,487,488,557,558,696,697,835,836,975,976,1114,1115,1253,1254,1393,1394],[96,96,120,120,144,144,168,168,192,192,240,240,288,288,336,336,384,384,480,480,576,576,672,672,768,768,960,960,1152,1152,1344,1344,1536,1536,1728,1728,1920,1920]],Jt=function(){function n(i){this.TAG="AC3Parser",this.data_=i,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not found AC3 syncword until payload end")}return n.prototype.findNextSyncwordOffset=function(i){for(var t=i,e=this.data_;;){if(t+7>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<8|e[t+1])==2935)return t;t++}},n.prototype.readNextAC3Frame=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_syncword_offset_,a=i[e+4]>>6,o=[48000,44200,33000][a],r=63&i[e+4],s=2*$t[a][r];if(isNaN(s)||e+s>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var d=this.findNextSyncwordOffset(e+s);this.current_syncword_offset_=d;var l=i[e+5]>>3,y=7&i[e+5],f=i[e+6]>>5,g=0;1&f&&f!==1&&(g+=2),4&f&&(g+=2),f===2&&(g+=2);var T=(i[e+6]<<8|i[e+7])>>12-g&1,B=[2,1,2,3,3,4,4,5][f]+T;(t=new Qt).sampling_frequency=o,t.channel_count=B,t.channel_mode=f,t.bit_stream_identification=l,t.low_frequency_effects_channel_on=T,t.bit_stream_mode=y,t.frame_size_code=r,t.data=i.subarray(e,e+s)}return t},n.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},n.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},n}(),Zt=function(n){var i;i=[n.sampling_rate_code<<6|n.bit_stream_identification<<1|n.bit_stream_mode>>2,(3&n.bit_stream_mode)<<6|n.channel_mode<<3|n.low_frequency_effects_channel_on<<2|n.frame_size_code>>4,n.frame_size_code<<4&224],this.config=i,this.sampling_rate=n.sampling_frequency,this.bit_stream_identification=n.bit_stream_identification,this.bit_stream_mode=n.bit_stream_mode,this.low_frequency_effects_channel_on=n.low_frequency_effects_channel_on,this.channel_count=n.channel_count,this.channel_mode=n.channel_mode,this.codec_mimetype="ac-3",this.original_codec_mimetype="ac-3"},ei=function(){},ti=function(){function n(i){this.TAG="EAC3Parser",this.data_=i,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not found AC3 syncword until payload end")}return n.prototype.findNextSyncwordOffset=function(i){for(var t=i,e=this.data_;;){if(t+7>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<8|e[t+1])==2935)return t;t++}},n.prototype.readNextEAC3Frame=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_syncword_offset_,a=new A(i.subarray(e+2)),o=(a.readBits(2),a.readBits(3),a.readBits(11)+1<<1),r=a.readBits(2),s=null,d=null;r===3?(s=[24000,22060,16000][r=a.readBits(2)],d=3):(s=[48000,44100,32000][r],d=a.readBits(2));var l=a.readBits(3),y=a.readBits(1),f=a.readBits(5);if(e+o>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var g=this.findNextSyncwordOffset(e+o);this.current_syncword_offset_=g;var T=[2,1,2,3,3,4,4,5][l]+y;a.destroy(),(t=new ei).sampling_frequency=s,t.channel_count=T,t.channel_mode=l,t.bit_stream_identification=f,t.low_frequency_effects_channel_on=y,t.frame_size=o,t.num_blks=[1,2,3,6][d],t.data=i.subarray(e,e+o)}return t},n.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},n.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},n}(),ii=function(n){var i,t=Math.floor(n.frame_size*n.sampling_frequency/(16*n.num_blks));i=[255&t,248&t,n.sampling_rate_code<<6|n.bit_stream_identification<<1,n.channel_mode<<1|n.low_frequency_effects_channel_on,0],this.config=i,this.sampling_rate=n.sampling_frequency,this.bit_stream_identification=n.bit_stream_identification,this.num_blks=n.num_blks,this.low_frequency_effects_channel_on=n.low_frequency_effects_channel_on,this.channel_count=n.channel_count,this.channel_mode=n.channel_mode,this.codec_mimetype="ec-3",this.original_codec_mimetype="ec-3"},ni=function(){},ai=function(){function n(i){this.TAG="AV1OBUInMpegTsParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=i,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not find AV1 startcode until payload end!")}return n._ebsp2rbsp=function(i){for(var t=i,e=t.byteLength,a=new Uint8Array(e),o=0,r=0;r=2&&t[r]===3&&t[r-1]===0&&t[r-2]===0||(a[o]=t[r],o++);return new Uint8Array(a.buffer,0,o)},n.prototype.findNextStartCodeOffset=function(i){for(var t=i,e=this.data_;;){if(t+2>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<16|e[t+1]<<8|e[t+2])==1)return t;t++}},n.prototype.readNextOBUPayload=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_startcode_offset_+3,a=this.findNextStartCodeOffset(e);this.current_startcode_offset_=a,t=n._ebsp2rbsp(i.subarray(e,a))}return t},n}(),ri=function(){},oi=function(){var n=function(i,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,a){e.__proto__=a}||function(e,a){for(var o in a)Object.prototype.hasOwnProperty.call(a,o)&&(e[o]=a[o])},n(i,t)};return function(i,t){if(typeof t!="function"&&t!==null)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function e(){this.constructor=i}n(i,t),i.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}}(),Ke=function(){return Ke=Object.assign||function(n){for(var i,t=1,e=arguments.length;t=4?(_.default.v("TSDemuxer","ts_packet_size = 192, m2ts mode"),a-=4):o===204&&_.default.v("TSDemuxer","ts_packet_size = 204, RS encoded MPEG2-TS stream"),{match:!0,consumed:0,ts_packet_size:o,sync_offset:a})},i.prototype.bindDataSource=function(t){return t.onDataArrival=this.parseChunks.bind(this),this},i.prototype.resetMediaInfo=function(){this.media_info_=new R.default},i.prototype.parseChunks=function(t,e){if(!(this.onError&&this.onMediaInfo&&this.onTrackMetadata&&this.onDataAvailable))throw new k.IllegalStateException("onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var a=0;for(this.first_parse_&&(this.first_parse_=!1,a=this.sync_offset_);a+this.ts_packet_size_<=t.byteLength;){var o=e+a;this.ts_packet_size_===192&&(a+=4);var r=new Uint8Array(t,a,188),s=r[0];if(s!==71){_.default.e(this.TAG,"sync_byte = ".concat(s,", not 0x47"));break}var d=(64&r[1])>>>6,l=(r[1],(31&r[1])<<8|r[2]),y=(48&r[3])>>>4,f=15&r[3],g=!(!this.pmt_||this.pmt_.pcr_pid!==l),T={},B=4;if(y==2||y==3){var F=r[4];if(F>0&&(g||y==3)&&(T.discontinuity_indicator=(128&r[5])>>>7,T.random_access_indicator=(64&r[5])>>>6,T.elementary_stream_priority_indicator=(32&r[5])>>>5,(16&r[5])>>>4)){var q=300*this.getPcrBase(r)+((1&r[10])<<8|r[11]);this.last_pcr_=q}if(y==2||5+F===188){a+=188,this.ts_packet_size_===204&&(a+=16);continue}B=5+F}if(y==1||y==3){if(l===0||l===this.current_pmt_pid_||this.pmt_!=null&&this.pmt_.pid_stream_type[l]===z.kSCTE35){var Z=188-B;this.handleSectionSlice(t,a+B,Z,{pid:l,file_position:o,payload_unit_start_indicator:d,continuity_conunter:f,random_access_indicator:T.random_access_indicator})}else if(this.pmt_!=null&&this.pmt_.pid_stream_type[l]!=null){Z=188-B;var U=this.pmt_.pid_stream_type[l];l!==this.pmt_.common_pids.h264&&l!==this.pmt_.common_pids.h265&&l!==this.pmt_.common_pids.av1&&l!==this.pmt_.common_pids.adts_aac&&l!==this.pmt_.common_pids.loas_aac&&l!==this.pmt_.common_pids.ac3&&l!==this.pmt_.common_pids.eac3&&l!==this.pmt_.common_pids.opus&&l!==this.pmt_.common_pids.mp3&&this.pmt_.pes_private_data_pids[l]!==!0&&this.pmt_.timed_id3_pids[l]!==!0&&this.pmt_.pgs_pids[l]!==!0&&this.pmt_.synchronous_klv_pids[l]!==!0&&this.pmt_.asynchronous_klv_pids[l]!==!0||this.handlePESSlice(t,a+B,Z,{pid:l,stream_type:U,file_position:o,payload_unit_start_indicator:d,continuity_conunter:f,random_access_indicator:T.random_access_indicator})}}a+=188,this.ts_packet_size_===204&&(a+=16)}return this.dispatchAudioVideoMediaSegment(),a},i.prototype.handleSectionSlice=function(t,e,a,o){var r=new Uint8Array(t,e,a),s=this.section_slice_queues_[o.pid];if(o.payload_unit_start_indicator){var d=r[0];if(s!=null&&s.total_length!==0){var l=new Uint8Array(t,e+1,Math.min(a,d));s.slices.push(l),s.total_length+=l.byteLength,s.total_length===s.expected_length?this.emitSectionSlices(s,o):this.clearSlices(s,o)}for(var y=1+d;y=s.expected_length&&this.clearSlices(s,o),y+=l.byteLength}}else s!=null&&s.total_length!==0&&(l=new Uint8Array(t,e,Math.min(a,s.expected_length-s.total_length)),s.slices.push(l),s.total_length+=l.byteLength,s.total_length===s.expected_length?this.emitSectionSlices(s,o):s.total_length>=s.expected_length&&this.clearSlices(s,o))},i.prototype.handlePESSlice=function(t,e,a,o){var r=new Uint8Array(t,e,a),s=r[0]<<16|r[1]<<8|r[2],d=(r[3],r[4]<<8|r[5]);if(o.payload_unit_start_indicator){if(s!==1)return void _.default.e(this.TAG,"handlePESSlice: packet_start_code_prefix should be 1 but with value ".concat(s));var l=this.pes_slice_queues_[o.pid];l&&(l.expected_length===0||l.expected_length===l.total_length?this.emitPESSlices(l,o):this.clearSlices(l,o)),this.pes_slice_queues_[o.pid]=new L,this.pes_slice_queues_[o.pid].file_position=o.file_position,this.pes_slice_queues_[o.pid].random_access_indicator=o.random_access_indicator}if(this.pes_slice_queues_[o.pid]!=null){var y=this.pes_slice_queues_[o.pid];y.slices.push(r),o.payload_unit_start_indicator&&(y.expected_length=d===0?0:d+6),y.total_length+=r.byteLength,y.expected_length>0&&y.expected_length===y.total_length?this.emitPESSlices(y,o):y.expected_length>0&&y.expected_length>>6,d=e[8],l=void 0,y=void 0;s!==2&&s!==3||(l=this.getTimestamp(e,9),y=s===3?this.getTimestamp(e,14):l);var f=9+d,g=void 0;if(r!==0){if(r<3+d)return void _.default.v(this.TAG,"Malformed PES: PES_packet_length < 3 + PES_header_data_length");g=r-3-d}else g=e.byteLength-f;var T=e.subarray(f,f+g);switch(t.stream_type){case z.kMPEG1Audio:case z.kMPEG2Audio:this.parseMP3Payload(T,l);break;case z.kPESPrivateData:this.pmt_.common_pids.av1===t.pid?this.parseAV1Payload(T,l,y,t.file_position,t.random_access_indicator):this.pmt_.common_pids.opus===t.pid?this.parseOpusPayload(T,l):this.pmt_.common_pids.ac3===t.pid?this.parseAC3Payload(T,l):this.pmt_.common_pids.eac3===t.pid?this.parseEAC3Payload(T,l):this.pmt_.asynchronous_klv_pids[t.pid]?this.parseAsynchronousKLVMetadataPayload(T,t.pid,o):this.pmt_.smpte2038_pids[t.pid]?this.parseSMPTE2038MetadataPayload(T,l,y,t.pid,o):this.parsePESPrivateDataPayload(T,l,y,t.pid,o);break;case z.kADTSAAC:this.parseADTSAACPayload(T,l);break;case z.kLOASAAC:this.parseLOASAACPayload(T,l);break;case z.kAC3:this.parseAC3Payload(T,l);break;case z.kEAC3:this.parseEAC3Payload(T,l);break;case z.kMetadata:this.pmt_.timed_id3_pids[t.pid]?this.parseTimedID3MetadataPayload(T,l,y,t.pid,o):this.pmt_.synchronous_klv_pids[t.pid]&&this.parseSynchronousKLVMetadataPayload(T,l,y,t.pid,o);break;case z.kPGS:this.parsePGSPayload(T,l,y,t.pid,o,this.pmt_.pgs_langs[t.pid]);break;case z.kH264:this.parseH264Payload(T,l,y,t.file_position,t.random_access_indicator);break;case z.kH265:this.parseH265Payload(T,l,y,t.file_position,t.random_access_indicator)}}else o!==188&&o!==191&&o!==240&&o!==241&&o!==255&&o!==242&&o!==248||t.stream_type!==z.kPESPrivateData||(f=6,g=void 0,g=r!==0?r:e.byteLength-f,T=e.subarray(f,f+g),this.parsePESPrivateDataPayload(T,void 0,void 0,t.pid,o));else _.default.e(this.TAG,"parsePES: packet_start_code_prefix should be 1 but with value ".concat(a))},i.prototype.parsePAT=function(t){var e=t[0];if(e===0){var a=(15&t[1])<<8|t[2],o=(t[3],t[4],(62&t[5])>>>1),r=1&t[5],s=t[6],d=(t[7],null);if(r===1&&s===0)(d=new te).version_number=o;else if((d=this.pat_)==null)return;for(var l=a-5-4,y=-1,f=-1,g=8;g<8+l;g+=4){var T=t[g]<<8|t[g+1],B=(31&t[g+2])<<8|t[g+3];T===0?d.network_pid=B:(d.program_pmt_pid[T]=B,y===-1&&(y=T),f===-1&&(f=B))}r===1&&s===0&&(this.pat_==null&&_.default.v(this.TAG,"Parsed first PAT: ".concat(JSON.stringify(d))),this.pat_=d,this.current_program_=y,this.current_pmt_pid_=f)}else _.default.e(this.TAG,"parsePAT: table_id ".concat(e," is not corresponded to PAT!"))},i.prototype.parsePMT=function(t){var e=t[0];if(e===2){var a=(15&t[1])<<8|t[2],o=t[3]<<8|t[4],r=(62&t[5])>>>1,s=1&t[5],d=t[6],l=(t[7],null);if(s===1&&d===0)(l=new Re).program_number=o,l.version_number=r,this.program_pmt_map_[o]=l;else if((l=this.program_pmt_map_[o])==null)return;l.pcr_pid=(31&t[8])<<8|t[9];for(var y=(15&t[10])<<8|t[11],f=12+y,g=a-9-y-4,T=f;T0){for(var H=T+5;H0)for(H=T+5;H0)for(H=T+5;H1&&(_.default.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(s,"ms, PES pts: ").concat(r,"ms")),r=s)}}for(var d,l=new Ue(t),y=null,f=r;(y=l.readNextAACFrame())!=null;){o=1024/y.sampling_frequency*1000;var g={codec:"aac",data:y};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"aac",audio_object_type:y.audio_object_type,sampling_freq_index:y.sampling_freq_index,sampling_frequency:y.sampling_frequency,channel_config:y.channel_config},this.dispatchAudioInitSegment(g)):this.detectAudioMetadataChange(g)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(g)),d=f;var T=Math.floor(f),B={unit:y.data,length:y.data.byteLength,pts:T,dts:T};this.audio_track_.samples.push(B),this.audio_track_.length+=y.data.byteLength,f+=o}l.hasIncompleteData()&&(this.aac_last_incomplete_data_=l.getIncompleteData()),d&&(this.audio_last_sample_pts_=d)}},i.prototype.parseLOASAACPayload=function(t,e){var a;if(!this.has_video_||this.video_init_segment_dispatched_){if(this.aac_last_incomplete_data_){var o=new Uint8Array(t.byteLength+this.aac_last_incomplete_data_.byteLength);o.set(this.aac_last_incomplete_data_,0),o.set(t,this.aac_last_incomplete_data_.byteLength),t=o}var r,s;if(e!=null&&(s=e/this.timescale_),this.audio_metadata_.codec==="aac"){if(e==null&&this.audio_last_sample_pts_!=null)r=1024/this.audio_metadata_.sampling_frequency*1000,s=this.audio_last_sample_pts_+r;else if(e==null)return void _.default.w(this.TAG,"AAC: Unknown pts");if(this.aac_last_incomplete_data_&&this.audio_last_sample_pts_){r=1024/this.audio_metadata_.sampling_frequency*1000;var d=this.audio_last_sample_pts_+r;Math.abs(d-s)>1&&(_.default.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(d,"ms, PES pts: ").concat(s,"ms")),s=d)}}for(var l,y=new je(t),f=null,g=s;(f=y.readNextAACFrame((a=this.loas_previous_frame)!==null&&a!==void 0?a:void 0))!=null;){this.loas_previous_frame=f,r=1024/f.sampling_frequency*1000;var T={codec:"aac",data:f};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"aac",audio_object_type:f.audio_object_type,sampling_freq_index:f.sampling_freq_index,sampling_frequency:f.sampling_frequency,channel_config:f.channel_config},this.dispatchAudioInitSegment(T)):this.detectAudioMetadataChange(T)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(T)),l=g;var B=Math.floor(g),F={unit:f.data,length:f.data.byteLength,pts:B,dts:B};this.audio_track_.samples.push(F),this.audio_track_.length+=f.data.byteLength,g+=r}y.hasIncompleteData()&&(this.aac_last_incomplete_data_=y.getIncompleteData()),l&&(this.audio_last_sample_pts_=l)}},i.prototype.parseAC3Payload=function(t,e){if(!this.has_video_||this.video_init_segment_dispatched_){var a,o;if(e!=null&&(o=e/this.timescale_),this.audio_metadata_.codec==="ac-3"){if(e==null&&this.audio_last_sample_pts_!=null)a=1536/this.audio_metadata_.sampling_frequency*1000,o=this.audio_last_sample_pts_+a;else if(e==null)return void _.default.w(this.TAG,"AC3: Unknown pts")}for(var r,s=new Jt(t),d=null,l=o;(d=s.readNextAC3Frame())!=null;){a=1536/d.sampling_frequency*1000;var y={codec:"ac-3",data:d};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"ac-3",sampling_frequency:d.sampling_frequency,bit_stream_identification:d.bit_stream_identification,bit_stream_mode:d.bit_stream_mode,low_frequency_effects_channel_on:d.low_frequency_effects_channel_on,channel_mode:d.channel_mode},this.dispatchAudioInitSegment(y)):this.detectAudioMetadataChange(y)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(y)),r=l;var f=Math.floor(l),g={unit:d.data,length:d.data.byteLength,pts:f,dts:f};this.audio_track_.samples.push(g),this.audio_track_.length+=d.data.byteLength,l+=a}r&&(this.audio_last_sample_pts_=r)}},i.prototype.parseEAC3Payload=function(t,e){if(!this.has_video_||this.video_init_segment_dispatched_){var a,o;if(e!=null&&(o=e/this.timescale_),this.audio_metadata_.codec==="ec-3"){if(e==null&&this.audio_last_sample_pts_!=null)a=256*this.audio_metadata_.num_blks/this.audio_metadata_.sampling_frequency*1000,o=this.audio_last_sample_pts_+a;else if(e==null)return void _.default.w(this.TAG,"EAC3: Unknown pts")}for(var r,s=new ti(t),d=null,l=o;(d=s.readNextEAC3Frame())!=null;){a=1536/d.sampling_frequency*1000;var y={codec:"ec-3",data:d};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"ec-3",sampling_frequency:d.sampling_frequency,bit_stream_identification:d.bit_stream_identification,low_frequency_effects_channel_on:d.low_frequency_effects_channel_on,num_blks:d.num_blks,channel_mode:d.channel_mode},this.dispatchAudioInitSegment(y)):this.detectAudioMetadataChange(y)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(y)),r=l;var f=Math.floor(l),g={unit:d.data,length:d.data.byteLength,pts:f,dts:f};this.audio_track_.samples.push(g),this.audio_track_.length+=d.data.byteLength,l+=a}r&&(this.audio_last_sample_pts_=r)}},i.prototype.parseOpusPayload=function(t,e){if(!this.has_video_||this.video_init_segment_dispatched_){var a,o;if(e!=null&&(o=e/this.timescale_),this.audio_metadata_.codec==="opus"){if(e==null&&this.audio_last_sample_pts_!=null)a=20,o=this.audio_last_sample_pts_+a;else if(e==null)return void _.default.w(this.TAG,"Opus: Unknown pts")}for(var r,s=o,d=0;d>>3&3,o=(6&t[1])>>1,r=(t[2],(12&t[2])>>>2),s=3&~(t[3]>>>6)?2:1,d=0,l=34;switch(a){case 0:d=[11025,12000,8000,0][r];break;case 2:d=[22050,24000,16000,0][r];break;case 3:d=[44100,48000,32000,0][r]}switch(o){case 1:l=34;break;case 2:l=33;break;case 3:l=32}var y=new Xt;y.object_type=l,y.sample_rate=d,y.channel_count=s,y.data=t;var f={codec:"mp3",data:y};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"mp3",object_type:l,sample_rate:d,channel_count:s},this.dispatchAudioInitSegment(f)):this.detectAudioMetadataChange(f)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(f));var g={unit:t,length:t.byteLength,pts:e/this.timescale_,dts:e/this.timescale_};this.audio_track_.samples.push(g),this.audio_track_.length+=t.byteLength}},i.prototype.detectAudioMetadataChange=function(t){if(t.codec!==this.audio_metadata_.codec)return _.default.v(this.TAG,"Audio: Audio Codecs changed from "+"".concat(this.audio_metadata_.codec," to ").concat(t.codec)),!0;if(t.codec==="aac"&&this.audio_metadata_.codec==="aac"){if((e=t.data).audio_object_type!==this.audio_metadata_.audio_object_type)return _.default.v(this.TAG,"AAC: AudioObjectType changed from "+"".concat(this.audio_metadata_.audio_object_type," to ").concat(e.audio_object_type)),!0;if(e.sampling_freq_index!==this.audio_metadata_.sampling_freq_index)return _.default.v(this.TAG,"AAC: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sampling_freq_index," to ").concat(e.sampling_freq_index)),!0;if(e.channel_config!==this.audio_metadata_.channel_config)return _.default.v(this.TAG,"AAC: Channel configuration changed from "+"".concat(this.audio_metadata_.channel_config," to ").concat(e.channel_config)),!0}else if(t.codec==="ac-3"&&this.audio_metadata_.codec==="ac-3"){var e;if((e=t.data).sampling_frequency!==this.audio_metadata_.sampling_frequency)return _.default.v(this.TAG,"AC3: Sampling Frequency changed from "+"".concat(this.audio_metadata_.sampling_frequency," to ").concat(e.sampling_frequency)),!0;if(e.bit_stream_identification!==this.audio_metadata_.bit_stream_identification)return _.default.v(this.TAG,"AC3: Bit Stream Identification changed from "+"".concat(this.audio_metadata_.bit_stream_identification," to ").concat(e.bit_stream_identification)),!0;if(e.bit_stream_mode!==this.audio_metadata_.bit_stream_mode)return _.default.v(this.TAG,"AC3: BitStream Mode changed from "+"".concat(this.audio_metadata_.bit_stream_mode," to ").concat(e.bit_stream_mode)),!0;if(e.channel_mode!==this.audio_metadata_.channel_mode)return _.default.v(this.TAG,"AC3: Channel Mode changed from "+"".concat(this.audio_metadata_.channel_mode," to ").concat(e.channel_mode)),!0;if(e.low_frequency_effects_channel_on!==this.audio_metadata_.low_frequency_effects_channel_on)return _.default.v(this.TAG,"AC3: Low Frequency Effects Channel On changed from "+"".concat(this.audio_metadata_.low_frequency_effects_channel_on," to ").concat(e.low_frequency_effects_channel_on)),!0}else if(t.codec==="opus"&&this.audio_metadata_.codec==="opus"){if((a=t.meta).sample_rate!==this.audio_metadata_.sample_rate)return _.default.v(this.TAG,"Opus: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sample_rate," to ").concat(a.sample_rate)),!0;if(a.channel_count!==this.audio_metadata_.channel_count)return _.default.v(this.TAG,"Opus: Channel count changed from "+"".concat(this.audio_metadata_.channel_count," to ").concat(a.channel_count)),!0}else if(t.codec==="mp3"&&this.audio_metadata_.codec==="mp3"){var a;if((a=t.data).object_type!==this.audio_metadata_.object_type)return _.default.v(this.TAG,"MP3: AudioObjectType changed from "+"".concat(this.audio_metadata_.object_type," to ").concat(a.object_type)),!0;if(a.sample_rate!==this.audio_metadata_.sample_rate)return _.default.v(this.TAG,"MP3: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sample_rate," to ").concat(a.sample_rate)),!0;if(a.channel_count!==this.audio_metadata_.channel_count)return _.default.v(this.TAG,"MP3: Channel count changed from "+"".concat(this.audio_metadata_.channel_count," to ").concat(a.channel_count)),!0}return!1},i.prototype.dispatchAudioInitSegment=function(t){var e={type:"audio"};if(e.id=this.audio_track_.id,e.timescale=1000,e.duration=this.duration_,this.audio_metadata_.codec==="aac"){var a=t.codec==="aac"?t.data:null,o=new Fe(a);e.audioSampleRate=o.sampling_rate,e.channelCount=o.channel_count,e.codec=o.codec_mimetype,e.originalCodec=o.original_codec_mimetype,e.config=o.config,e.refSampleDuration=1024/e.audioSampleRate*e.timescale}else if(this.audio_metadata_.codec==="ac-3"){var r=t.codec==="ac-3"?t.data:null,s=new Zt(r);e.audioSampleRate=s.sampling_rate,e.channelCount=s.channel_count,e.codec=s.codec_mimetype,e.originalCodec=s.original_codec_mimetype,e.config=s.config,e.refSampleDuration=1536/e.audioSampleRate*e.timescale}else if(this.audio_metadata_.codec==="ec-3"){var d=t.codec==="ec-3"?t.data:null,l=new ii(d);e.audioSampleRate=l.sampling_rate,e.channelCount=l.channel_count,e.codec=l.codec_mimetype,e.originalCodec=l.original_codec_mimetype,e.config=l.config,e.refSampleDuration=256*l.num_blks/e.audioSampleRate*e.timescale}else this.audio_metadata_.codec==="opus"?(e.audioSampleRate=this.audio_metadata_.sample_rate,e.channelCount=this.audio_metadata_.channel_count,e.channelConfigCode=this.audio_metadata_.channel_config_code,e.codec="opus",e.originalCodec="opus",e.config=void 0,e.refSampleDuration=20):this.audio_metadata_.codec==="mp3"&&(e.audioSampleRate=this.audio_metadata_.sample_rate,e.channelCount=this.audio_metadata_.channel_count,e.codec="mp3",e.originalCodec="mp3",e.config=void 0);this.audio_init_segment_dispatched_==0&&_.default.v(this.TAG,"Generated first AudioSpecificConfig for mimeType: ".concat(e.codec)),this.onTrackMetadata("audio",e),this.audio_init_segment_dispatched_=!0,this.video_metadata_changed_=!1;var y=this.media_info_;y.hasAudio=!0,y.audioCodec=e.originalCodec,y.audioSampleRate=e.audioSampleRate,y.audioChannelCount=e.channelCount,y.hasVideo&&y.videoCodec?y.mimeType='video/mp2t; codecs="'.concat(y.videoCodec,",").concat(y.audioCodec,'"'):y.mimeType='video/mp2t; codecs="'.concat(y.audioCodec,'"'),y.isComplete()&&this.onMediaInfo(y)},i.prototype.dispatchPESPrivateDataDescriptor=function(t,e,a){var o=new nt;o.pid=t,o.stream_type=e,o.descriptor=a,this.onPESPrivateDataDescriptor&&this.onPESPrivateDataDescriptor(o)},i.prototype.parsePESPrivateDataPayload=function(t,e,a,o,r){var s=new Xe;if(s.pid=o,s.stream_id=r,s.len=t.byteLength,s.data=t,e!=null){var d=Math.floor(e/this.timescale_);s.pts=d}else s.nearest_pts=this.getNearestTimestampMilliseconds();if(a!=null){var l=Math.floor(a/this.timescale_);s.dts=l}this.onPESPrivateData&&this.onPESPrivateData(s)},i.prototype.parseTimedID3MetadataPayload=function(t,e,a,o,r){var s=new Xe;if(s.pid=o,s.stream_id=r,s.len=t.byteLength,s.data=t,e!=null){var d=Math.floor(e/this.timescale_);s.pts=d}if(a!=null){var l=Math.floor(a/this.timescale_);s.dts=l}this.onTimedID3Metadata&&this.onTimedID3Metadata(s)},i.prototype.parsePGSPayload=function(t,e,a,o,r,s){var d=new ri;if(d.pid=o,d.lang=s,d.stream_id=r,d.len=t.byteLength,d.data=t,e!=null){var l=Math.floor(e/this.timescale_);d.pts=l}if(a!=null){var y=Math.floor(a/this.timescale_);d.dts=y}this.onPGSSubtitleData&&this.onPGSSubtitleData(d)},i.prototype.parseSynchronousKLVMetadataPayload=function(t,e,a,o,r){var s=new ni;if(s.pid=o,s.stream_id=r,s.len=t.byteLength,s.data=t,e!=null){var d=Math.floor(e/this.timescale_);s.pts=d}if(a!=null){var l=Math.floor(a/this.timescale_);s.dts=l}s.access_units=function(y){for(var f=[],g=0;g+5>>24&255,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=255&t,e.set(i,4);var s=8;for(r=0;r>>24&255,i>>>16&255,i>>>8&255,255&i,t>>>24&255,t>>>16&255,t>>>8&255,255&t,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]))},n.trak=function(i){return n.box(n.types.trak,n.tkhd(i),n.mdia(i))},n.tkhd=function(i){var{id:t,duration:e,presentWidth:a,presentHeight:o}=i;return n.box(n.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,0,0,0,0,e>>>24&255,e>>>16&255,e>>>8&255,255&e,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,a>>>8&255,255&a,0,0,o>>>8&255,255&o,0,0]))},n.mdia=function(i){return n.box(n.types.mdia,n.mdhd(i),n.hdlr(i),n.minf(i))},n.mdhd=function(i){var{timescale:t,duration:e}=i;return n.box(n.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,e>>>24&255,e>>>16&255,e>>>8&255,255&e,85,196,0,0]))},n.hdlr=function(i){var t;return t=i.type==="audio"?n.constants.HDLR_AUDIO:n.constants.HDLR_VIDEO,n.box(n.types.hdlr,t)},n.minf=function(i){var t;return t=i.type==="audio"?n.box(n.types.smhd,n.constants.SMHD):n.box(n.types.vmhd,n.constants.VMHD),n.box(n.types.minf,t,n.dinf(),n.stbl(i))},n.dinf=function(){return n.box(n.types.dinf,n.box(n.types.dref,n.constants.DREF))},n.stbl=function(i){return n.box(n.types.stbl,n.stsd(i),n.box(n.types.stts,n.constants.STTS),n.box(n.types.stsc,n.constants.STSC),n.box(n.types.stsz,n.constants.STSZ),n.box(n.types.stco,n.constants.STCO))},n.stsd=function(i){return i.type==="audio"?i.codec==="mp3"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.mp3(i)):i.codec==="ac-3"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.ac3(i)):i.codec==="ec-3"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.ec3(i)):i.codec==="opus"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.Opus(i)):i.codec=="flac"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.fLaC(i)):i.codec=="ipcm"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.ipcm(i)):n.box(n.types.stsd,n.constants.STSD_PREFIX,n.mp4a(i)):i.type==="video"&&i.codec.startsWith("hvc1")?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.hvc1(i)):i.type==="video"&&i.codec.startsWith("av01")?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.av01(i)):n.box(n.types.stsd,n.constants.STSD_PREFIX,n.avc1(i))},n.mp3=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types[".mp3"],a)},n.mp4a=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types.mp4a,a,n.esds(i))},n.ac3=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types["ac-3"],a,n.box(n.types.dac3,new Uint8Array(i.config)))},n.ec3=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types["ec-3"],a,n.box(n.types.dec3,new Uint8Array(i.config)))},n.esds=function(i){var t=i.config||[],e=t.length,a=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).concat([6,1,2]));return n.box(n.types.esds,a)},n.Opus=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types.Opus,a,n.dOps(i))},n.dOps=function(i){var{channelCount:t,channelConfigCode:e,audioSampleRate:a}=i;if(i.config)return n.box(n.types.dOps,i.config);var o=[];switch(e){case 1:case 2:o=[0];break;case 0:o=[255,1,1,0,1];break;case 128:o=[255,2,0,0,1];break;case 3:o=[1,2,1,0,2,1];break;case 4:o=[1,2,2,0,1,2,3];break;case 5:o=[1,3,2,0,4,1,2,3];break;case 6:o=[1,4,2,0,4,1,2,3,5];break;case 7:o=[1,4,2,0,4,1,2,3,5,6];break;case 8:o=[1,5,3,0,6,1,2,3,4,5,7];break;case 130:o=[1,1,2,0,1];break;case 131:o=[1,1,3,0,1,2];break;case 132:o=[1,1,4,0,1,2,3];break;case 133:o=[1,1,5,0,1,2,3,4];break;case 134:o=[1,1,6,0,1,2,3,4,5];break;case 135:o=[1,1,7,0,1,2,3,4,5,6];break;case 136:o=[1,1,8,0,1,2,3,4,5,6,7]}var r=new Uint8Array(pt([0,t,0,0,a>>>24&255,a>>>17&255,a>>>8&255,a>>>0&255,0,0],o,!0));return n.box(n.types.dOps,r)},n.fLaC=function(i){var t=i.channelCount,e=Math.min(i.audioSampleRate,65535),a=i.sampleSize,o=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,a,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types.fLaC,o,n.dfLa(i))},n.dfLa=function(i){var t=new Uint8Array(pt([0,0,0,0],i.config,!0));return n.box(n.types.dfLa,t)},n.ipcm=function(i){var t=i.channelCount,e=Math.min(i.audioSampleRate,65535),a=i.sampleSize,o=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,a,0,0,0,0,e>>>8&255,255&e,0,0]);return i.channelCount===1?n.box(n.types.ipcm,o,n.pcmC(i)):n.box(n.types.ipcm,o,n.chnl(i),n.pcmC(i))},n.chnl=function(i){var t=new Uint8Array([0,0,0,0,1,i.channelCount,0,0,0,0,0,0,0,0]);return n.box(n.types.chnl,t)},n.pcmC=function(i){var t=i.littleEndian?1:0,e=i.sampleSize,a=new Uint8Array([0,0,0,0,t,e]);return n.box(n.types.pcmC,a)},n.avc1=function(i){var{avcc:t,codecWidth:e,codecHeight:a}=i,o=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,e>>>8&255,255&e,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return n.box(n.types.avc1,o,n.box(n.types.avcC,t))},n.hvc1=function(i){var{hvcc:t,codecWidth:e,codecHeight:a}=i,o=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,e>>>8&255,255&e,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return n.box(n.types.hvc1,o,n.box(n.types.hvcC,t))},n.av01=function(i){var t=i.av1c,e=i.codecWidth||192,a=i.codecHeight||108,o=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,e>>>8&255,255&e,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return n.box(n.types.av01,o,n.box(n.types.av1C,t))},n.mvex=function(i){return n.box(n.types.mvex,n.trex(i))},n.trex=function(i){var t=i.id,e=new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return n.box(n.types.trex,e)},n.moof=function(i,t){return n.box(n.types.moof,n.mfhd(i.sequenceNumber),n.traf(i,t))},n.mfhd=function(i){var t=new Uint8Array([0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i]);return n.box(n.types.mfhd,t)},n.traf=function(i,t){var e=i.id,a=n.box(n.types.tfhd,new Uint8Array([0,0,0,0,e>>>24&255,e>>>16&255,e>>>8&255,255&e])),o=n.box(n.types.tfdt,new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t])),r=n.sdtp(i),s=n.trun(i,r.byteLength+16+16+8+16+8+8);return n.box(n.types.traf,a,o,s,r)},n.sdtp=function(i){for(var t=i.samples||[],e=t.length,a=new Uint8Array(4+e),o=0;o>>24&255,a>>>16&255,a>>>8&255,255&a,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0);for(var s=0;s>>24&255,d>>>16&255,d>>>8&255,255&d,l>>>24&255,l>>>16&255,l>>>8&255,255&l,y.isLeading<<2|y.dependsOn,y.isDependedOn<<6|y.hasRedundancy<<4|y.isNonSync,0,0,f>>>24&255,f>>>16&255,f>>>8&255,255&f],12+16*s)}return n.box(n.types.trun,r)},n.mdat=function(i){return n.box(n.types.mdat,i)},n}();mt.init();var We=mt,gt=function(){function n(){}return n.getSilentFrame=function(i,t){if(i==="mp4a.40.2"){if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null},n}(),ze=D(47),yt=function(){function n(i){this.TAG="MP4Remuxer",this._config=i,this._isLive=i.isLive===!0,this._dtsBase=-1,this._dtsBaseInited=!1,this._audioDtsBase=1/0,this._videoDtsBase=1/0,this._audioNextDts=void 0,this._videoNextDts=void 0,this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList=new ze.MediaSegmentInfoList("audio"),this._videoSegmentInfoList=new ze.MediaSegmentInfoList("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!(!S.default.chrome||!(S.default.version.major<50||S.default.version.major===50&&S.default.version.build<2661)),this._fillSilentAfterSeek=S.default.msedge||S.default.msie,this._mp3UseMpegAudio=!S.default.firefox,this._fillAudioTimestampGap=this._config.fixAudioTimestampGap}return n.prototype.destroy=function(){this._dtsBase=-1,this._dtsBaseInited=!1,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList.clear(),this._audioSegmentInfoList=null,this._videoSegmentInfoList.clear(),this._videoSegmentInfoList=null,this._onInitSegment=null,this._onMediaSegment=null},n.prototype.bindDataSource=function(i){return i.onDataAvailable=this.remux.bind(this),i.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this},Object.defineProperty(n.prototype,"onInitSegment",{get:function(){return this._onInitSegment},set:function(i){this._onInitSegment=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onMediaSegment",{get:function(){return this._onMediaSegment},set:function(i){this._onMediaSegment=i},enumerable:!1,configurable:!0}),n.prototype.insertDiscontinuity=function(){this._audioNextDts=this._videoNextDts=void 0},n.prototype.seek=function(i){this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()},n.prototype.remux=function(i,t){if(!this._onMediaSegment)throw new k.IllegalStateException("MP4Remuxer: onMediaSegment callback must be specificed!");this._dtsBaseInited||this._calculateDtsBase(i,t),t&&this._remuxVideo(t),i&&this._remuxAudio(i)},n.prototype._onTrackMetadataReceived=function(i,t){var e=null,a="mp4",o=t.codec;if(i==="audio")this._audioMeta=t,t.codec==="mp3"&&this._mp3UseMpegAudio?(a="mpeg",o="",e=new Uint8Array):e=We.generateInitSegment(t);else{if(i!=="video")return;this._videoMeta=t,e=We.generateInitSegment(t)}if(!this._onInitSegment)throw new k.IllegalStateException("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(i,{type:i,data:e.buffer,codec:o,container:"".concat(i,"/").concat(a),mediaDuration:t.duration})},n.prototype._calculateDtsBase=function(i,t){this._dtsBaseInited||(i&&i.samples&&i.samples.length&&(this._audioDtsBase=i.samples[0].dts),t&&t.samples&&t.samples.length&&(this._videoDtsBase=t.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)},n.prototype.getTimestampBase=function(){if(this._dtsBaseInited)return this._dtsBase},n.prototype.flushStashedSamples=function(){var i=this._videoStashedLastSample,t=this._audioStashedLastSample,e={type:"video",id:1,sequenceNumber:0,samples:[],length:0};i!=null&&(e.samples.push(i),e.length=i.length);var a={type:"audio",id:2,sequenceNumber:0,samples:[],length:0};t!=null&&(a.samples.push(t),a.length=t.length),this._videoStashedLastSample=null,this._audioStashedLastSample=null,this._remuxVideo(e,!0),this._remuxAudio(a,!0)},n.prototype._remuxAudio=function(i,t){if(this._audioMeta!=null){var e,a=i,o=a.samples,r=void 0,s=-1,d=this._audioMeta.refSampleDuration,l=this._audioMeta.codec==="mp3"&&this._mp3UseMpegAudio,y=this._dtsBaseInited&&this._audioNextDts===void 0,f=!1;if(o&&o.length!==0&&(o.length!==1||t)){var g=0,T=null,B=0;l?(g=0,B=a.length):(g=8,B=8+a.length);var F=null;if(o.length>1&&(B-=(F=o.pop()).length),this._audioStashedLastSample!=null){var q=this._audioStashedLastSample;this._audioStashedLastSample=null,o.unshift(q),B+=q.length}F!=null&&(this._audioStashedLastSample=F);var Z=o[0].dts-this._dtsBase;if(this._audioNextDts)r=Z-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())r=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&this._audioMeta.originalCodec!=="mp3"&&(f=!0);else{var U=this._audioSegmentInfoList.getLastSampleBefore(Z);if(U!=null){var H=Z-(U.originalDts+U.duration);H<=3&&(H=0),r=Z-(U.dts+U.duration+H)}else r=0}if(f){var he=Z-r,ve=this._videoSegmentInfoList.getLastSegmentBefore(Z);if(ve!=null&&ve.beginDts=3*d&&this._fillAudioTimestampGap){Ce=!0;var be,Be=Math.floor(r/d);_.default.w(this.TAG,`Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync. -`+"originalDts: ".concat(Se," ms, curRefDts: ").concat(pe," ms, ")+"dtsCorrection: ".concat(Math.round(r)," ms, generate: ").concat(Be," frames")),ne=Math.floor(pe),Te=Math.floor(pe+d)-ne,(be=gt.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount))==null&&(_.default.w(this.TAG,"Unable to generate silent frame for "+"".concat(this._audioMeta.originalCodec," with ").concat(this._audioMeta.channelCount," channels, repeat last frame")),be=De),we=[];for(var ye=0;ye=1?ge[ge.length-1].duration:Math.floor(d),this._audioNextDts=ne+Te;s===-1&&(s=ne),ge.push({dts:ne,pts:ne,cts:0,unit:q.unit,size:q.unit.byteLength,duration:Te,originalDts:Se,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}}),Ce&&ge.push.apply(ge,we)}}if(ge.length===0)return a.samples=[],void(a.length=0);for(l?T=new Uint8Array(B):((T=new Uint8Array(B))[0]=B>>>24&255,T[1]=B>>>16&255,T[2]=B>>>8&255,T[3]=255&B,T.set(We.types.mdat,4)),ce=0;ce1&&(g-=(T=r.pop()).length),this._videoStashedLastSample!=null){var B=this._videoStashedLastSample;this._videoStashedLastSample=null,r.unshift(B),g+=B.length}T!=null&&(this._videoStashedLastSample=T);var F=r[0].dts-this._dtsBase;if(this._videoNextDts)s=F-this._videoNextDts;else if(this._videoSegmentInfoList.isEmpty())s=0;else{var q=this._videoSegmentInfoList.getLastSampleBefore(F);if(q!=null){var Z=F-(q.originalDts+q.duration);Z<=3&&(Z=0),s=F-(q.dts+q.duration+Z)}else s=0}for(var U=new ze.MediaSegmentInfo,H=[],he=0;he=1?H[H.length-1].duration:Math.floor(this._videoMeta.refSampleDuration),ne){var Se=new ze.SampleInfo(ae,ce,De,B.dts,!0);Se.fileposition=B.fileposition,U.appendSyncPoint(Se)}H.push({dts:ae,pts:ce,cts:ge,units:B.units,size:B.length,isKeyframe:ne,duration:De,originalDts:ve,flags:{isLeading:0,dependsOn:ne?2:1,isDependedOn:ne?1:0,hasRedundancy:0,isNonSync:ne?0:1}})}for((f=new Uint8Array(g))[0]=g>>>24&255,f[1]=g>>>16&255,f[2]=g>>>8&255,f[3]=255&g,f.set(We.types.mdat,4),he=0;he0)this._demuxer.bindDataSource(this._ioctl),this._demuxer.timestampBase=this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase,a=this._demuxer.parseChunks(i,t);else{var o=null;(o=de.probe(i)).match&&(this._setupFLVDemuxerRemuxer(o),a=this._demuxer.parseChunks(i,t)),o.match||o.needMoreData||(o=ft.probe(i)).match&&(this._setupTSDemuxerRemuxer(o),a=this._demuxer.parseChunks(i,t)),o.match||o.needMoreData||(o=null,_.default.e(this.TAG,"Non MPEG-TS/FLV, Unsupported media type!"),Promise.resolve().then(function(){e._internalAbort()}),this._emitter.emit(Ie.default.DEMUX_ERROR,m.default.FORMAT_UNSUPPORTED,"Non MPEG-TS/FLV, Unsupported media type!"))}return a},n.prototype._setupFLVDemuxerRemuxer=function(i){this._demuxer=new de(i,this._config),this._remuxer||(this._remuxer=new yt(this._config));var t=this._mediaDataSource;t.duration==null||isNaN(t.duration)||(this._demuxer.overridedDuration=t.duration),typeof t.hasAudio=="boolean"&&(this._demuxer.overridedHasAudio=t.hasAudio),typeof t.hasVideo=="boolean"&&(this._demuxer.overridedHasVideo=t.hasVideo),this._demuxer.timestampBase=t.segments[this._currentSegmentIndex].timestampBase,this._demuxer.onError=this._onDemuxException.bind(this),this._demuxer.onMediaInfo=this._onMediaInfo.bind(this),this._demuxer.onMetaDataArrived=this._onMetaDataArrived.bind(this),this._demuxer.onScriptDataArrived=this._onScriptDataArrived.bind(this),this._demuxer.onSeiArrived=this._onSEI.bind(this),this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl)),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},n.prototype._setupTSDemuxerRemuxer=function(i){var t=this._demuxer=new ft(i,this._config);this._remuxer||(this._remuxer=new yt(this._config)),t.onError=this._onDemuxException.bind(this),t.onMediaInfo=this._onMediaInfo.bind(this),t.onMetaDataArrived=this._onMetaDataArrived.bind(this),t.onTimedID3Metadata=this._onTimedID3Metadata.bind(this),t.onPGSSubtitleData=this._onPGSSubtitle.bind(this),t.onSynchronousKLVMetadata=this._onSynchronousKLVMetadata.bind(this),t.onAsynchronousKLVMetadata=this._onAsynchronousKLVMetadata.bind(this),t.onSMPTE2038Metadata=this._onSMPTE2038Metadata.bind(this),t.onSEI=this._onSEI.bind(this),t.onSCTE35Metadata=this._onSCTE35Metadata.bind(this),t.onPESPrivateDataDescriptor=this._onPESPrivateDataDescriptor.bind(this),t.onPESPrivateData=this._onPESPrivateData.bind(this),this._remuxer.bindDataSource(this._demuxer),this._demuxer.bindDataSource(this._ioctl),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},n.prototype._onMediaInfo=function(i){var t=this;this._mediaInfo==null&&(this._mediaInfo=Object.assign({},i),this._mediaInfo.keyframesIndex=null,this._mediaInfo.segments=[],this._mediaInfo.segmentCount=this._mediaDataSource.segments.length,Object.setPrototypeOf(this._mediaInfo,R.default.prototype));var e=Object.assign({},i);Object.setPrototypeOf(e,R.default.prototype),this._mediaInfo.segments[this._currentSegmentIndex]=e,this._reportSegmentMediaInfo(this._currentSegmentIndex),this._pendingSeekTime!=null&&Promise.resolve().then(function(){var a=t._pendingSeekTime;t._pendingSeekTime=null,t.seek(a)})},n.prototype._onMetaDataArrived=function(i){this._emitter.emit(Ie.default.METADATA_ARRIVED,i)},n.prototype._onScriptDataArrived=function(i){this._emitter.emit(Ie.default.SCRIPTDATA_ARRIVED,i)},n.prototype._onTimedID3Metadata=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.dts!=null&&(i.dts-=t),this._emitter.emit(Ie.default.TIMED_ID3_METADATA_ARRIVED,i))},n.prototype._onPGSSubtitle=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.dts!=null&&(i.dts-=t),this._emitter.emit(Ie.default.PGS_SUBTITLE_ARRIVED,i))},n.prototype._onSynchronousKLVMetadata=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.dts!=null&&(i.dts-=t),this._emitter.emit(Ie.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,i))},n.prototype._onAsynchronousKLVMetadata=function(i){this._emitter.emit(Ie.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,i)},n.prototype._onSMPTE2038Metadata=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.dts!=null&&(i.dts-=t),i.nearest_pts!=null&&(i.nearest_pts-=t),this._emitter.emit(Ie.default.SMPTE2038_METADATA_ARRIVED,i))},n.prototype._onSEI=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),this._emitter.emit(Ie.default.SEI_ARRIVED,i))},n.prototype._onSCTE35Metadata=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.nearest_pts!=null&&(i.nearest_pts-=t),this._emitter.emit(Ie.default.SCTE35_METADATA_ARRIVED,i))},n.prototype._onPESPrivateDataDescriptor=function(i){this._emitter.emit(Ie.default.PES_PRIVATE_DATA_DESCRIPTOR,i)},n.prototype._onPESPrivateData=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.nearest_pts!=null&&(i.nearest_pts-=t),i.dts!=null&&(i.dts-=t),this._emitter.emit(Ie.default.PES_PRIVATE_DATA_ARRIVED,i))},n.prototype._onIOSeeked=function(){this._remuxer.insertDiscontinuity()},n.prototype._onIOComplete=function(i){var t=i+1;t0&&e[0].originalDts===a&&(a=e[0].pts),this._emitter.emit(Ie.default.RECOMMEND_SEEKPOINT,a)}},n.prototype._enableStatisticsReporter=function(){this._statisticsReporter==null&&(this._statisticsReporter=self.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval))},n.prototype._disableStatisticsReporter=function(){this._statisticsReporter&&(self.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},n.prototype._reportSegmentMediaInfo=function(i){var t=this._mediaInfo.segments[i],e=Object.assign({},t);e.duration=this._mediaInfo.duration,e.segmentCount=this._mediaInfo.segmentCount,delete e.segments,delete e.keyframesIndex,this._emitter.emit(Ie.default.MEDIA_INFO,e)},n.prototype._reportStatisticsInfo=function(){var i={};i.url=this._ioctl.currentURL,i.hasRedirect=this._ioctl.hasRedirect,i.hasRedirect&&(i.redirectedURL=this._ioctl.currentRedirectedURL),i.speed=this._ioctl.currentSpeed,i.loaderType=this._ioctl.loaderType,i.currentSegmentIndex=this._currentSegmentIndex,i.totalSegmentCount=this._mediaDataSource.segments.length,this._emitter.emit(Ie.default.STATISTICS_INFO,i)},n}())},137:function(le,Q,D){D.r(Q),D(856);var X=D(947),P=D(811),_=D(886),S=D(726);Q.default=function(R){var v=null,I=function(te,ee){R.postMessage({msg:"logcat_callback",data:{type:te,logcat:ee}})}.bind(this);function b(te,ee){var Re={msg:S.default.INIT_SEGMENT,data:{type:te,data:ee}};R.postMessage(Re,[ee.data])}function k(te,ee){var Re={msg:S.default.MEDIA_SEGMENT,data:{type:te,data:ee}};R.postMessage(Re,[ee.data])}function w(){var te={msg:S.default.LOADING_COMPLETE};R.postMessage(te)}function O(){var te={msg:S.default.RECOVERED_EARLY_EOF};R.postMessage(te)}function A(te){var ee={msg:S.default.MEDIA_INFO,data:te};R.postMessage(ee)}function G(te){var ee={msg:S.default.METADATA_ARRIVED,data:te};R.postMessage(ee)}function m(te){var ee={msg:S.default.SCRIPTDATA_ARRIVED,data:te};R.postMessage(ee)}function N(te){var ee={msg:S.default.TIMED_ID3_METADATA_ARRIVED,data:te};R.postMessage(ee)}function x(te){var ee={msg:S.default.PGS_SUBTITLE_ARRIVED,data:te};R.postMessage(ee)}function K(te){var ee={msg:S.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,data:te};R.postMessage(ee)}function M(te){var ee={msg:S.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,data:te};R.postMessage(ee)}function u(te){var ee={msg:S.default.SMPTE2038_METADATA_ARRIVED,data:te};R.postMessage(ee)}function h(te){var ee={msg:S.default.SEI_ARRIVED,data:te};R.postMessage(ee)}function p(te){var ee={msg:S.default.SCTE35_METADATA_ARRIVED,data:te};R.postMessage(ee)}function E(te){var ee={msg:S.default.PES_PRIVATE_DATA_DESCRIPTOR,data:te};R.postMessage(ee)}function W(te){var ee={msg:S.default.PES_PRIVATE_DATA_ARRIVED,data:te};R.postMessage(ee)}function z(te){var ee={msg:S.default.STATISTICS_INFO,data:te};R.postMessage(ee)}function se(te,ee){R.postMessage({msg:S.default.IO_ERROR,data:{type:te,info:ee}})}function de(te,ee){R.postMessage({msg:S.default.DEMUX_ERROR,data:{type:te,info:ee}})}function me(te){R.postMessage({msg:S.default.RECOMMEND_SEEKPOINT,data:te})}P.default.install(),R.addEventListener("message",function(te){switch(te.data.cmd){case"init":(v=new _.default(te.data.param[0],te.data.param[1])).on(S.default.IO_ERROR,se.bind(this)),v.on(S.default.DEMUX_ERROR,de.bind(this)),v.on(S.default.INIT_SEGMENT,b.bind(this)),v.on(S.default.MEDIA_SEGMENT,k.bind(this)),v.on(S.default.LOADING_COMPLETE,w.bind(this)),v.on(S.default.RECOVERED_EARLY_EOF,O.bind(this)),v.on(S.default.MEDIA_INFO,A.bind(this)),v.on(S.default.METADATA_ARRIVED,G.bind(this)),v.on(S.default.SCRIPTDATA_ARRIVED,m.bind(this)),v.on(S.default.TIMED_ID3_METADATA_ARRIVED,N.bind(this)),v.on(S.default.PGS_SUBTITLE_ARRIVED,x.bind(this)),v.on(S.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,K.bind(this)),v.on(S.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,M.bind(this)),v.on(S.default.SMPTE2038_METADATA_ARRIVED,u.bind(this)),v.on(S.default.SEI_ARRIVED,h.bind(this)),v.on(S.default.SCTE35_METADATA_ARRIVED,p.bind(this)),v.on(S.default.PES_PRIVATE_DATA_DESCRIPTOR,E.bind(this)),v.on(S.default.PES_PRIVATE_DATA_ARRIVED,W.bind(this)),v.on(S.default.STATISTICS_INFO,z.bind(this)),v.on(S.default.RECOMMEND_SEEKPOINT,me.bind(this));break;case"destroy":v&&(v.destroy(),v=null),R.postMessage({msg:"destroyed"});break;case"start":v.start();break;case"stop":v.stop();break;case"seek":v.seek(te.data.param);break;case"pause":v.pause();break;case"resume":v.resume();break;case"logging_config":var ee=te.data.param;X.default.applyConfig(ee),ee.enableCallback===!0?X.default.addLogListener(I):X.default.removeLogListener(I)}})}},827:function(le,Q,D){D.r(Q),Q.default={OK:"OK",FORMAT_ERROR:"FormatError",FORMAT_UNSUPPORTED:"FormatUnsupported",CODEC_UNSUPPORTED:"CodecUnsupported"}},976:function(le,Q,D){le.exports=D(311).default},653:function(le,Q,D){D.r(Q),D.d(Q,{default:function(){return K}});var X,P=D(856),_=function(){function M(){this._firstCheckpoint=0,this._lastCheckpoint=0,this._intervalBytes=0,this._totalBytes=0,this._lastSecondBytes=0,self.performance&&self.performance.now?this._now=self.performance.now.bind(self.performance):this._now=Date.now}return M.prototype.reset=function(){this._firstCheckpoint=this._lastCheckpoint=0,this._totalBytes=this._intervalBytes=0,this._lastSecondBytes=0},M.prototype.addBytes=function(u){this._firstCheckpoint===0?(this._firstCheckpoint=this._now(),this._lastCheckpoint=this._firstCheckpoint,this._intervalBytes+=u,this._totalBytes+=u):this._now()-this._lastCheckpoint<1000?(this._intervalBytes+=u,this._totalBytes+=u):(this._lastSecondBytes=this._intervalBytes,this._intervalBytes=u,this._totalBytes+=u,this._lastCheckpoint=this._now())},Object.defineProperty(M.prototype,"currentKBps",{get:function(){this.addBytes(0);var u=(this._now()-this._lastCheckpoint)/1000;return u==0&&(u=1),this._intervalBytes/u/1024},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"lastSecondKBps",{get:function(){return this.addBytes(0),this._lastSecondBytes!==0?this._lastSecondBytes/1024:this._now()-this._lastCheckpoint>=500?this.currentKBps:0},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"averageKBps",{get:function(){var u=(this._now()-this._firstCheckpoint)/1000;return this._totalBytes/u/1024},enumerable:!1,configurable:!0}),M}(),S=D(470),R=D(994),v=D(867),I=(X=function(M,u){return X=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,p){h.__proto__=p}||function(h,p){for(var E in p)Object.prototype.hasOwnProperty.call(p,E)&&(h[E]=p[E])},X(M,u)},function(M,u){if(typeof u!="function"&&u!==null)throw TypeError("Class extends value "+String(u)+" is not a constructor or null");function h(){this.constructor=M}X(M,u),M.prototype=u===null?Object.create(u):(h.prototype=u.prototype,new h)}),b=function(M){function u(h,p){var E=M.call(this,"fetch-stream-loader")||this;return E.TAG="FetchStreamLoader",E._seekHandler=h,E._config=p,E._needStash=!0,E._requestAbort=!1,E._abortController=null,E._contentLength=null,E._receivedLength=0,E}return I(u,M),u.isSupported=function(){try{var h=R.default.msedge&&R.default.version.minor>=15048,p=!R.default.msedge||h;return self.fetch&&self.ReadableStream&&p}catch(E){return!1}},u.prototype.destroy=function(){this.isWorking()&&this.abort(),M.prototype.destroy.call(this)},u.prototype.open=function(h,p){var E=this;this._dataSource=h,this._range=p;var W=h.url;this._config.reuseRedirectedURL&&h.redirectedURL!=null&&(W=h.redirectedURL);var z=this._seekHandler.getConfig(W,p),se=new self.Headers;if(typeof z.headers=="object"){var de=z.headers;for(var me in de)de.hasOwnProperty(me)&&se.append(me,de[me])}var te={method:"GET",headers:se,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};if(typeof this._config.headers=="object")for(var me in this._config.headers)se.append(me,this._config.headers[me]);h.cors===!1&&(te.mode="same-origin"),h.withCredentials&&(te.credentials="include"),h.referrerPolicy&&(te.referrerPolicy=h.referrerPolicy),self.AbortController&&(this._abortController=new self.AbortController,te.signal=this._abortController.signal),this._status=S.LoaderStatus.kConnecting,self.fetch(z.url,te).then(function(ee){if(E._requestAbort)return E._status=S.LoaderStatus.kIdle,void ee.body.cancel();if(ee.ok&&ee.status>=200&&ee.status<=299){if(ee.url!==z.url&&E._onURLRedirect){var Re=E._seekHandler.removeURLParameters(ee.url);E._onURLRedirect(Re)}var J=ee.headers.get("Content-Length");return J!=null&&(E._contentLength=parseInt(J),E._contentLength!==0&&E._onContentLengthKnown&&E._onContentLengthKnown(E._contentLength)),E._pump.call(E,ee.body.getReader())}if(E._status=S.LoaderStatus.kError,!E._onError)throw new v.RuntimeException("FetchStreamLoader: Http code invalid, "+ee.status+" "+ee.statusText);E._onError(S.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:ee.status,msg:ee.statusText})}).catch(function(ee){if(!E._abortController||!E._abortController.signal.aborted){if(E._status=S.LoaderStatus.kError,!E._onError)throw ee;E._onError(S.LoaderErrors.EXCEPTION,{code:-1,msg:ee.message})}})},u.prototype.abort=function(){if(this._requestAbort=!0,(this._status!==S.LoaderStatus.kBuffering||!R.default.chrome)&&this._abortController)try{this._abortController.abort()}catch(h){}},u.prototype._pump=function(h){var p=this;return h.read().then(function(E){if(E.done)if(p._contentLength!==null&&p._receivedLength299)){if(this._status=S.LoaderStatus.kError,!this._onError)throw new v.RuntimeException("MozChunkedLoader: Http code invalid, "+p.status+" "+p.statusText);this._onError(S.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:p.status,msg:p.statusText})}else this._status=S.LoaderStatus.kBuffering}},u.prototype._onProgress=function(h){if(this._status!==S.LoaderStatus.kError){this._contentLength===null&&h.total!==null&&h.total!==0&&(this._contentLength=h.total,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength));var p=h.target.response,E=this._range.from+this._receivedLength;this._receivedLength+=p.byteLength,this._onDataArrival&&this._onDataArrival(p,E,this._receivedLength)}},u.prototype._onLoadEnd=function(h){this._requestAbort!==!0?this._status!==S.LoaderStatus.kError&&(this._status=S.LoaderStatus.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1)):this._requestAbort=!1},u.prototype._onXhrError=function(h){this._status=S.LoaderStatus.kError;var p=0,E=null;if(this._contentLength&&h.loaded=this._contentLength&&(E=this._range.from+this._contentLength-1),this._currentRequestRange={from:p,to:E},this._internalOpen(this._dataSource,this._currentRequestRange)},u.prototype._internalOpen=function(h,p){this._lastTimeLoaded=0;var E=h.url;this._config.reuseRedirectedURL&&(this._currentRedirectedURL!=null?E=this._currentRedirectedURL:h.redirectedURL!=null&&(E=h.redirectedURL));var W=this._seekHandler.getConfig(E,p);this._currentRequestURL=W.url;var z=this._xhr=new XMLHttpRequest;if(z.open("GET",W.url,!0),z.responseType="arraybuffer",z.onreadystatechange=this._onReadyStateChange.bind(this),z.onprogress=this._onProgress.bind(this),z.onload=this._onLoad.bind(this),z.onerror=this._onXhrError.bind(this),h.withCredentials&&(z.withCredentials=!0),typeof W.headers=="object"){var se=W.headers;for(var de in se)se.hasOwnProperty(de)&&z.setRequestHeader(de,se[de])}if(typeof this._config.headers=="object")for(var de in se=this._config.headers)se.hasOwnProperty(de)&&z.setRequestHeader(de,se[de]);z.send()},u.prototype.abort=function(){this._requestAbort=!0,this._internalAbort(),this._status=S.LoaderStatus.kComplete},u.prototype._internalAbort=function(){this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr.abort(),this._xhr=null)},u.prototype._onReadyStateChange=function(h){var p=h.target;if(p.readyState===2){if(p.responseURL!=null){var E=this._seekHandler.removeURLParameters(p.responseURL);p.responseURL!==this._currentRequestURL&&E!==this._currentRedirectedURL&&(this._currentRedirectedURL=E,this._onURLRedirect&&this._onURLRedirect(E))}if(p.status>=200&&p.status<=299){if(this._waitForTotalLength)return;this._status=S.LoaderStatus.kBuffering}else{if(this._status=S.LoaderStatus.kError,!this._onError)throw new v.RuntimeException("RangeLoader: Http code invalid, "+p.status+" "+p.statusText);this._onError(S.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:p.status,msg:p.statusText})}}},u.prototype._onProgress=function(h){if(this._status!==S.LoaderStatus.kError){if(this._contentLength===null){var p=!1;if(this._waitForTotalLength){this._waitForTotalLength=!1,this._totalLengthReceived=!0,p=!0;var E=h.total;this._internalAbort(),E!=null&E!==0&&(this._totalLength=E)}if(this._range.to===-1?this._contentLength=this._totalLength-this._range.from:this._contentLength=this._range.to-this._range.from+1,p)return void this._openSubRange();this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength)}var W=h.loaded-this._lastTimeLoaded;this._lastTimeLoaded=h.loaded,this._speedSampler.addBytes(W)}},u.prototype._normalizeSpeed=function(h){var p=this._chunkSizeKBList,E=p.length-1,W=0,z=0,se=E;if(h=p[W]&&h=3&&(p=this._speedSampler.currentKBps)),p!==0){var E=this._normalizeSpeed(p);this._currentSpeedNormalized!==E&&(this._currentSpeedNormalized=E,this._currentChunkSizeKB=E)}var W=h.target.response,z=this._range.from+this._receivedLength;this._receivedLength+=W.byteLength;var se=!1;this._contentLength!=null&&this._receivedLength0&&this._receivedLength0)for(var z=p.split("&"),se=0;se0;de[0]!==this._startName&&de[0]!==this._endName&&(me&&(W+="&"),W+=z[se])}return W.length===0?h:h+"?"+W},M}(),K=function(){function M(u,h,p){this.TAG="IOController",this._config=h,this._extraData=p,this._stashInitialSize=65536,h.stashInitialSize!=null&&h.stashInitialSize>0&&(this._stashInitialSize=h.stashInitialSize),this._stashUsed=0,this._stashSize=this._stashInitialSize,this._bufferSize=Math.max(this._stashSize,3145728),this._stashBuffer=new ArrayBuffer(this._bufferSize),this._stashByteStart=0,this._enableStash=!0,h.enableStashBuffer===!1&&(this._enableStash=!1),this._loader=null,this._loaderClass=null,this._seekHandler=null,this._dataSource=u,this._isWebSocketURL=/wss?:\/\/(.+?)/.test(u.url),this._refTotalLength=u.filesize?u.filesize:null,this._totalLength=this._refTotalLength,this._fullRequestFlag=!1,this._currentRange=null,this._redirectedURL=null,this._speedNormalized=0,this._speedSampler=new _,this._speedNormalizeList=[32,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096],this._isEarlyEofReconnecting=!1,this._paused=!1,this._resumeFrom=0,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._selectSeekHandler(),this._selectLoader(),this._createLoader()}return M.prototype.destroy=function(){this._loader.isWorking()&&this._loader.abort(),this._loader.destroy(),this._loader=null,this._loaderClass=null,this._dataSource=null,this._stashBuffer=null,this._stashUsed=this._stashSize=this._bufferSize=this._stashByteStart=0,this._currentRange=null,this._speedSampler=null,this._isEarlyEofReconnecting=!1,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._extraData=null},M.prototype.isWorking=function(){return this._loader&&this._loader.isWorking()&&!this._paused},M.prototype.isPaused=function(){return this._paused},Object.defineProperty(M.prototype,"status",{get:function(){return this._loader.status},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"extraData",{get:function(){return this._extraData},set:function(u){this._extraData=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(u){this._onDataArrival=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onSeeked",{get:function(){return this._onSeeked},set:function(u){this._onSeeked=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onError",{get:function(){return this._onError},set:function(u){this._onError=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onComplete",{get:function(){return this._onComplete},set:function(u){this._onComplete=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onRedirect",{get:function(){return this._onRedirect},set:function(u){this._onRedirect=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onRecoveredEarlyEof",{get:function(){return this._onRecoveredEarlyEof},set:function(u){this._onRecoveredEarlyEof=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"currentURL",{get:function(){return this._dataSource.url},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"hasRedirect",{get:function(){return this._redirectedURL!=null||this._dataSource.redirectedURL!=null},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"currentRedirectedURL",{get:function(){return this._redirectedURL||this._dataSource.redirectedURL},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"currentSpeed",{get:function(){return this._loaderClass===A?this._loader.currentSpeed:this._speedSampler.lastSecondKBps},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"loaderType",{get:function(){return this._loader.type},enumerable:!1,configurable:!0}),M.prototype._selectSeekHandler=function(){var u=this._config;if(u.seekType==="range")this._seekHandler=new N(this._config.rangeLoadZeroStart);else if(u.seekType==="param"){var h=u.seekParamStart||"bstart",p=u.seekParamEnd||"bend";this._seekHandler=new x(h,p)}else{if(u.seekType!=="custom")throw new v.InvalidArgumentException("Invalid seekType in config: ".concat(u.seekType));if(typeof u.customSeekHandler!="function")throw new v.InvalidArgumentException("Custom seekType specified in config but invalid customSeekHandler!");this._seekHandler=new u.customSeekHandler}},M.prototype._selectLoader=function(){if(this._config.customLoader!=null)this._loaderClass=this._config.customLoader;else if(this._isWebSocketURL)this._loaderClass=m;else if(b.isSupported())this._loaderClass=b;else if(w.isSupported())this._loaderClass=w;else{if(!A.isSupported())throw new v.RuntimeException("Your browser doesn't support xhr with arraybuffer responseType!");this._loaderClass=A}},M.prototype._createLoader=function(){this._loader=new this._loaderClass(this._seekHandler,this._config),this._loader.needStashBuffer===!1&&(this._enableStash=!1),this._loader.onContentLengthKnown=this._onContentLengthKnown.bind(this),this._loader.onURLRedirect=this._onURLRedirect.bind(this),this._loader.onDataArrival=this._onLoaderChunkArrival.bind(this),this._loader.onComplete=this._onLoaderComplete.bind(this),this._loader.onError=this._onLoaderError.bind(this)},M.prototype.open=function(u){this._currentRange={from:0,to:-1},u&&(this._currentRange.from=u),this._speedSampler.reset(),u||(this._fullRequestFlag=!0),this._loader.open(this._dataSource,Object.assign({},this._currentRange))},M.prototype.abort=function(){this._loader.abort(),this._paused&&(this._paused=!1,this._resumeFrom=0)},M.prototype.pause=function(){this.isWorking()&&(this._loader.abort(),this._stashUsed!==0?(this._resumeFrom=this._stashByteStart,this._currentRange.to=this._stashByteStart-1):this._resumeFrom=this._currentRange.to+1,this._stashUsed=0,this._stashByteStart=0,this._paused=!0)},M.prototype.resume=function(){if(this._paused){this._paused=!1;var u=this._resumeFrom;this._resumeFrom=0,this._internalSeek(u,!0)}},M.prototype.seek=function(u){this._paused=!1,this._stashUsed=0,this._stashByteStart=0,this._internalSeek(u,!0)},M.prototype._internalSeek=function(u,h){this._loader.isWorking()&&this._loader.abort(),this._flushStashBuffer(h),this._loader.destroy(),this._loader=null;var p={from:u,to:-1};this._currentRange={from:p.from,to:-1},this._speedSampler.reset(),this._stashSize=this._stashInitialSize,this._createLoader(),this._loader.open(this._dataSource,p),this._onSeeked&&this._onSeeked()},M.prototype.updateUrl=function(u){if(!u||typeof u!="string"||u.length===0)throw new v.InvalidArgumentException("Url must be a non-empty string!");this._dataSource.url=u},M.prototype._expandBuffer=function(u){for(var h=this._stashSize;h+10485760){var E=new Uint8Array(this._stashBuffer,0,this._stashUsed);new Uint8Array(p,0,h).set(E,0)}this._stashBuffer=p,this._bufferSize=h}},M.prototype._normalizeSpeed=function(u){var h=this._speedNormalizeList,p=h.length-1,E=0,W=0,z=p;if(u=h[E]&&u=512&&u<=1024?Math.floor(1.5*u):2*u)>8192&&(h=8192);var p=1024*h+1048576;this._bufferSize0){var z=this._stashBuffer.slice(0,this._stashUsed);(me=this._dispatchChunks(z,this._stashByteStart))0&&(te=new Uint8Array(z,me),de.set(te,0),this._stashUsed=te.byteLength,this._stashByteStart+=me):(this._stashUsed=0,this._stashByteStart+=me),this._stashUsed+u.byteLength>this._bufferSize&&(this._expandBuffer(this._stashUsed+u.byteLength),de=new Uint8Array(this._stashBuffer,0,this._bufferSize)),de.set(new Uint8Array(u),this._stashUsed),this._stashUsed+=u.byteLength}else(me=this._dispatchChunks(u,h))this._bufferSize&&(this._expandBuffer(se),de=new Uint8Array(this._stashBuffer,0,this._bufferSize)),de.set(new Uint8Array(u,me),0),this._stashUsed+=se,this._stashByteStart=h+me);else if(this._stashUsed===0){var se;(me=this._dispatchChunks(u,h))this._bufferSize&&this._expandBuffer(se),(de=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(u,me),0),this._stashUsed+=se,this._stashByteStart=h+me)}else{var de,me;if(this._stashUsed+u.byteLength>this._bufferSize&&this._expandBuffer(this._stashUsed+u.byteLength),(de=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(u),this._stashUsed),this._stashUsed+=u.byteLength,(me=this._dispatchChunks(this._stashBuffer.slice(0,this._stashUsed),this._stashByteStart))0){var te=new Uint8Array(this._stashBuffer,me);de.set(te,0)}this._stashUsed-=me,this._stashByteStart+=me}}},M.prototype._flushStashBuffer=function(u){if(this._stashUsed>0){var h=this._stashBuffer.slice(0,this._stashUsed),p=this._dispatchChunks(h,this._stashByteStart),E=h.byteLength-p;if(p0){var W=new Uint8Array(this._stashBuffer,0,this._bufferSize),z=new Uint8Array(h,p);W.set(z,0),this._stashUsed=z.byteLength,this._stashByteStart+=p}return 0}P.default.w(this.TAG,"".concat(E," bytes unconsumed data remain when flush buffer, dropped"))}return this._stashUsed=0,this._stashByteStart=0,E}return 0},M.prototype._onLoaderComplete=function(u,h){this._flushStashBuffer(!0),this._onComplete&&this._onComplete(this._extraData)},M.prototype._onLoaderError=function(u,h){switch(P.default.e(this.TAG,"Loader error, code = ".concat(h.code,", msg = ").concat(h.msg)),this._flushStashBuffer(!1),this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,u=S.LoaderErrors.UNRECOVERABLE_EARLY_EOF),u){case S.LoaderErrors.EARLY_EOF:if(!this._config.isLive&&this._totalLength){var p=this._currentRange.to+1;return void(p0){var fe=this._media_element.buffered.start(0);(fe<1&&c0){var fe=j.start(0);if(fe<1&&C=fe&&c0&&this._suspendTransmuxerIfBufferedPositionExceeded(j)},L.prototype._suspendTransmuxerIfBufferedPositionExceeded=function(c){c>=this._media_element.currentTime+this._config.lazyLoadMaxDuration&&!this._paused&&(b.default.v(this.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),this.suspendTransmuxer(),this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate))},L.prototype.suspendTransmuxer=function(){this._paused=!0,this._on_pause_transmuxer()},L.prototype._resumeTransmuxerIfNeeded=function(){for(var c=this._media_element.buffered,C=this._media_element.currentTime,j=this._config.lazyLoadRecoverDuration,fe=!1,re=0;re=V&&C=Y-j&&(fe=!0);break}}fe&&(b.default.v(this.TAG,"Continue loading from paused position"),this.resumeTransmuxer(),this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate))},L.prototype.resumeTransmuxer=function(){this._paused=!1,this._on_resume_transmuxer()},L}(),E=function(){function L(c,C){this.TAG="StartupStallJumper",this._media_element=null,this._on_direct_seek=null,this._canplay_received=!1,this.e=null,this._media_element=c,this._on_direct_seek=C,this.e={onMediaCanPlay:this._onMediaCanPlay.bind(this),onMediaStalled:this._onMediaStalled.bind(this),onMediaProgress:this._onMediaProgress.bind(this)},this._media_element.addEventListener("canplay",this.e.onMediaCanPlay),this._media_element.addEventListener("stalled",this.e.onMediaStalled),this._media_element.addEventListener("progress",this.e.onMediaProgress)}return L.prototype.destroy=function(){this._media_element.removeEventListener("canplay",this.e.onMediaCanPlay),this._media_element.removeEventListener("stalled",this.e.onMediaStalled),this._media_element.removeEventListener("progress",this.e.onMediaProgress),this._media_element=null,this._on_direct_seek=null},L.prototype._onMediaCanPlay=function(c){this._canplay_received=!0,this._media_element.removeEventListener("canplay",this.e.onMediaCanPlay)},L.prototype._onMediaStalled=function(c){this._detectAndFixStuckPlayback(!0)},L.prototype._onMediaProgress=function(c){this._detectAndFixStuckPlayback()},L.prototype._detectAndFixStuckPlayback=function(c){var C=this._media_element,j=C.buffered;c||!this._canplay_received||C.readyState<2?j.length>0&&C.currentTimethis._config.liveBufferLatencyMaxLatency&&fe-C>this._config.liveBufferLatencyMaxLatency){var re=fe-this._config.liveBufferLatencyMinRemain;this._on_direct_seek(re)}}},L}(),z=function(){function L(c,C){this._config=null,this._media_element=null,this.e=null,this._config=c,this._media_element=C,this.e={onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this)},this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate)}return L.prototype.destroy=function(){this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element=null,this._config=null},L.prototype._onMediaTimeUpdate=function(c){if(this._config.isLive&&this._config.liveSync){var C=this._getCurrentLatency();if(C>this._config.liveSyncMaxLatency){var j=Math.min(2,Math.max(1,this._config.liveSyncPlaybackRate));this._media_element.playbackRate=j}else C>this._config.liveSyncTargetLatency||this._media_element.playbackRate!==1&&this._media_element.playbackRate!==0&&(this._media_element.playbackRate=1)}},L.prototype._getCurrentLatency=function(){if(!this._media_element)return 0;var c=this._media_element.buffered,C=this._media_element.currentTime;return c.length==0?0:c.end(c.length-1)-C},L}(),se=function(){function L(c,C){this.TAG="PlayerEngineMainThread",this._emitter=new k,this._media_element=null,this._mse_controller=null,this._transmuxer=null,this._pending_seek_time=null,this._seeking_handler=null,this._loading_controller=null,this._startup_stall_jumper=null,this._live_latency_chaser=null,this._live_latency_synchronizer=null,this._mse_source_opened=!1,this._has_pending_load=!1,this._loaded_metadata_received=!1,this._media_info=null,this._statistics_info=null,this.e=null,this._media_data_source=c,this._config=S(),typeof C=="object"&&Object.assign(this._config,C),c.isLive===!0&&(this._config.isLive=!0),this.e={onMediaLoadedMetadata:this._onMediaLoadedMetadata.bind(this)}}return L.prototype.destroy=function(){this._emitter.emit(A.default.DESTROYING),this._transmuxer&&this.unload(),this._media_element&&this.detachMediaElement(),this.e=null,this._media_data_source=null,this._emitter.removeAllListeners(),this._emitter=null},L.prototype.on=function(c,C){var j=this;this._emitter.addListener(c,C),c===A.default.MEDIA_INFO&&this._media_info?Promise.resolve().then(function(){return j._emitter.emit(A.default.MEDIA_INFO,j.mediaInfo)}):c==A.default.STATISTICS_INFO&&this._statistics_info&&Promise.resolve().then(function(){return j._emitter.emit(A.default.STATISTICS_INFO,j.statisticsInfo)})},L.prototype.off=function(c,C){this._emitter.removeListener(c,C)},L.prototype.attachMediaElement=function(c){var C=this;this._media_element=c,c.src="",c.removeAttribute("src"),c.srcObject=null,c.load(),c.addEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._mse_controller=new O.default(this._config),this._mse_controller.on(m.default.UPDATE_END,this._onMSEUpdateEnd.bind(this)),this._mse_controller.on(m.default.BUFFER_FULL,this._onMSEBufferFull.bind(this)),this._mse_controller.on(m.default.SOURCE_OPEN,this._onMSESourceOpen.bind(this)),this._mse_controller.on(m.default.ERROR,this._onMSEError.bind(this)),this._mse_controller.on(m.default.START_STREAMING,this._onMSEStartStreaming.bind(this)),this._mse_controller.on(m.default.END_STREAMING,this._onMSEEndStreaming.bind(this)),this._mse_controller.initialize({getCurrentTime:function(){return C._media_element.currentTime},getReadyState:function(){return C._media_element.readyState}}),this._mse_controller.isManagedMediaSource()?(c.disableRemotePlayback=!0,c.srcObject=this._mse_controller.getObject()):c.src=this._mse_controller.getObjectURL()},L.prototype.detachMediaElement=function(){this._media_element&&(this._mse_controller.shutdown(),this._media_element.removeEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element=null,this._mse_controller.revokeObjectURL()),this._mse_controller&&(this._mse_controller.destroy(),this._mse_controller=null)},L.prototype.load=function(){var c=this;if(!this._media_element)throw new x.IllegalStateException("HTMLMediaElement must be attached before load()!");if(this._transmuxer)throw new x.IllegalStateException("load() has been called, please call unload() first!");this._has_pending_load||(!this._config.deferLoadAfterSourceOpen||this._mse_source_opened?(this._transmuxer=new G.default(this._media_data_source,this._config),this._transmuxer.on(K.default.INIT_SEGMENT,function(C,j){c._mse_controller.appendInitSegment(j)}),this._transmuxer.on(K.default.MEDIA_SEGMENT,function(C,j){c._mse_controller.appendMediaSegment(j),!c._config.isLive&&C==="video"&&j.data&&j.data.byteLength>0&&"info"in j&&c._seeking_handler.appendSyncPoints(j.info.syncPoints),c._loading_controller.notifyBufferedPositionChanged(j.info.endDts/1000)}),this._transmuxer.on(K.default.LOADING_COMPLETE,function(){c._mse_controller.endOfStream(),c._emitter.emit(A.default.LOADING_COMPLETE)}),this._transmuxer.on(K.default.RECOVERED_EARLY_EOF,function(){c._emitter.emit(A.default.RECOVERED_EARLY_EOF)}),this._transmuxer.on(K.default.IO_ERROR,function(C,j){c._emitter.emit(A.default.ERROR,N.ErrorTypes.NETWORK_ERROR,C,j)}),this._transmuxer.on(K.default.DEMUX_ERROR,function(C,j){c._emitter.emit(A.default.ERROR,N.ErrorTypes.MEDIA_ERROR,C,j)}),this._transmuxer.on(K.default.MEDIA_INFO,function(C){c._media_info=C,c._emitter.emit(A.default.MEDIA_INFO,Object.assign({},C))}),this._transmuxer.on(K.default.STATISTICS_INFO,function(C){c._statistics_info=c._fillStatisticsInfo(C),c._emitter.emit(A.default.STATISTICS_INFO,Object.assign({},C))}),this._transmuxer.on(K.default.RECOMMEND_SEEKPOINT,function(C){c._media_element&&!c._config.accurateSeek&&c._seeking_handler.directSeek(C/1000)}),this._transmuxer.on(K.default.METADATA_ARRIVED,function(C){c._emitter.emit(A.default.METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.SCRIPTDATA_ARRIVED,function(C){c._emitter.emit(A.default.SCRIPTDATA_ARRIVED,C)}),this._transmuxer.on(K.default.TIMED_ID3_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.TIMED_ID3_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.PGS_SUBTITLE_ARRIVED,function(C){c._emitter.emit(A.default.PGS_SUBTITLE_ARRIVED,C)}),this._transmuxer.on(K.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.SMPTE2038_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.SMPTE2038_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.SEI_ARRIVED,function(C){c._emitter.emit(A.default.SEI_ARRIVED,C)}),this._transmuxer.on(K.default.SCTE35_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.SCTE35_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.PES_PRIVATE_DATA_DESCRIPTOR,function(C){c._emitter.emit(A.default.PES_PRIVATE_DATA_DESCRIPTOR,C)}),this._transmuxer.on(K.default.PES_PRIVATE_DATA_ARRIVED,function(C){c._emitter.emit(A.default.PES_PRIVATE_DATA_ARRIVED,C)}),this._seeking_handler=new h(this._config,this._media_element,this._onRequiredUnbufferedSeek.bind(this)),this._loading_controller=new p(this._config,this._media_element,this._onRequestPauseTransmuxer.bind(this),this._onRequestResumeTransmuxer.bind(this)),this._startup_stall_jumper=new E(this._media_element,this._onRequestDirectSeek.bind(this)),this._config.isLive&&this._config.liveBufferLatencyChasing&&(this._live_latency_chaser=new W(this._config,this._media_element,this._onRequestDirectSeek.bind(this))),this._config.isLive&&this._config.liveSync&&(this._live_latency_synchronizer=new z(this._config,this._media_element)),this._media_element.readyState>0&&this._seeking_handler.directSeek(0),this._transmuxer.open()):this._has_pending_load=!0)},L.prototype.unload=function(){var c,C,j,fe,re,V,Y,ie,oe;(c=this._media_element)===null||c===void 0||c.pause(),(C=this._live_latency_synchronizer)===null||C===void 0||C.destroy(),this._live_latency_synchronizer=null,(j=this._live_latency_chaser)===null||j===void 0||j.destroy(),this._live_latency_chaser=null,(fe=this._startup_stall_jumper)===null||fe===void 0||fe.destroy(),this._startup_stall_jumper=null,(re=this._loading_controller)===null||re===void 0||re.destroy(),this._loading_controller=null,(V=this._seeking_handler)===null||V===void 0||V.destroy(),this._seeking_handler=null,(Y=this._mse_controller)===null||Y===void 0||Y.flush(),(ie=this._transmuxer)===null||ie===void 0||ie.close(),(oe=this._transmuxer)===null||oe===void 0||oe.destroy(),this._transmuxer=null},L.prototype.play=function(){return this._media_element.play()},L.prototype.pause=function(){this._media_element.pause()},L.prototype.seek=function(c){this._media_element&&this._seeking_handler?this._seeking_handler.seek(c):this._pending_seek_time=c},Object.defineProperty(L.prototype,"mediaInfo",{get:function(){return Object.assign({},this._media_info)},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"statisticsInfo",{get:function(){return Object.assign({},this._statistics_info)},enumerable:!1,configurable:!0}),L.prototype._onMSESourceOpen=function(){this._mse_source_opened=!0,this._has_pending_load&&(this._has_pending_load=!1,this.load())},L.prototype._onMSEUpdateEnd=function(){this._config.isLive&&this._config.liveBufferLatencyChasing&&this._live_latency_chaser&&this._live_latency_chaser.notifyBufferedRangeUpdate(),this._loading_controller.notifyBufferedPositionChanged()},L.prototype._onMSEBufferFull=function(){b.default.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._loading_controller.suspendTransmuxer()},L.prototype._onMSEError=function(c){this._emitter.emit(A.default.ERROR,N.ErrorTypes.MEDIA_ERROR,N.ErrorDetails.MEDIA_MSE_ERROR,c)},L.prototype._onMSEStartStreaming=function(){this._loaded_metadata_received&&(this._config.isLive||(b.default.v(this.TAG,"Resume transmuxing task due to ManagedMediaSource onStartStreaming"),this._loading_controller.resumeTransmuxer()))},L.prototype._onMSEEndStreaming=function(){this._config.isLive||(b.default.v(this.TAG,"Suspend transmuxing task due to ManagedMediaSource onEndStreaming"),this._loading_controller.suspendTransmuxer())},L.prototype._onMediaLoadedMetadata=function(c){this._loaded_metadata_received=!0,this._pending_seek_time!=null&&(this._seeking_handler.seek(this._pending_seek_time),this._pending_seek_time=null)},L.prototype._onRequestDirectSeek=function(c){this._seeking_handler.directSeek(c)},L.prototype._onRequiredUnbufferedSeek=function(c){this._mse_controller.flush(),this._transmuxer.seek(c)},L.prototype._onRequestPauseTransmuxer=function(){this._transmuxer.pause()},L.prototype._onRequestResumeTransmuxer=function(){this._transmuxer.resume()},L.prototype._fillStatisticsInfo=function(c){if(c.playerType="MSEPlayer",!(this._media_element instanceof HTMLVideoElement))return c;var C=!0,j=0,fe=0;if(this._media_element.getVideoPlaybackQuality){var re=this._media_element.getVideoPlaybackQuality();j=re.totalVideoFrames,fe=re.droppedVideoFrames}else this._media_element.webkitDecodedFrameCount!=null?(j=this._media_element.webkitDecodedFrameCount,fe=this._media_element.webkitDroppedFrameCount):C=!1;return C&&(c.decodedFrames=j,c.droppedFrames=fe),c},L}(),de=D(861),me=D(947),te=function(){function L(c,C){this.TAG="PlayerEngineDedicatedThread",this._emitter=new k,this._media_element=null,this._worker_destroying=!1,this._seeking_handler=null,this._loading_controller=null,this._startup_stall_jumper=null,this._live_latency_chaser=null,this._live_latency_synchronizer=null,this._pending_seek_time=null,this._media_info=null,this._statistics_info=null,this.e=null,this._media_data_source=c,this._config=S(),typeof C=="object"&&Object.assign(this._config,C),c.isLive===!0&&(this._config.isLive=!0),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this),onMediaLoadedMetadata:this._onMediaLoadedMetadata.bind(this),onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this),onMediaReadyStateChanged:this._onMediaReadyStateChange.bind(this)},me.default.registerListener(this.e.onLoggingConfigChanged),this._worker=de(877,{all:!0}),this._worker.addEventListener("message",this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:"init",media_data_source:this._media_data_source,config:this._config}),this._worker.postMessage({cmd:"logging_config",logging_config:me.default.getConfig()})}return L.isSupported=function(){return!!(self.Worker&&(self.MediaSource&&("canConstructInDedicatedWorker"in self.MediaSource)&&self.MediaSource.canConstructInDedicatedWorker===!0||self.ManagedMediaSource&&("canConstructInDedicatedWorker"in self.ManagedMediaSource)&&self.ManagedMediaSource.canConstructInDedicatedWorker===!0))},L.prototype.destroy=function(){this._emitter.emit(A.default.DESTROYING),this.unload(),this.detachMediaElement(),this._worker_destroying=!0,this._worker.postMessage({cmd:"destroy"}),me.default.removeListener(this.e.onLoggingConfigChanged),this.e=null,this._media_data_source=null,this._emitter.removeAllListeners(),this._emitter=null},L.prototype.on=function(c,C){var j=this;this._emitter.addListener(c,C),c===A.default.MEDIA_INFO&&this._media_info?Promise.resolve().then(function(){return j._emitter.emit(A.default.MEDIA_INFO,j.mediaInfo)}):c==A.default.STATISTICS_INFO&&this._statistics_info&&Promise.resolve().then(function(){return j._emitter.emit(A.default.STATISTICS_INFO,j.statisticsInfo)})},L.prototype.off=function(c,C){this._emitter.removeListener(c,C)},L.prototype.attachMediaElement=function(c){this._media_element=c,this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element.addEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element.addEventListener("readystatechange",this.e.onMediaReadyStateChanged),this._worker.postMessage({cmd:"initialize_mse"})},L.prototype.detachMediaElement=function(){this._worker.postMessage({cmd:"shutdown_mse"}),this._media_element&&(this._media_element.removeEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element.removeEventListener("readystatechange",this.e.onMediaReadyStateChanged),this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element=null)},L.prototype.load=function(){this._worker.postMessage({cmd:"load"}),this._seeking_handler=new h(this._config,this._media_element,this._onRequiredUnbufferedSeek.bind(this)),this._loading_controller=new p(this._config,this._media_element,this._onRequestPauseTransmuxer.bind(this),this._onRequestResumeTransmuxer.bind(this)),this._startup_stall_jumper=new E(this._media_element,this._onRequestDirectSeek.bind(this)),this._config.isLive&&this._config.liveBufferLatencyChasing&&(this._live_latency_chaser=new W(this._config,this._media_element,this._onRequestDirectSeek.bind(this))),this._config.isLive&&this._config.liveSync&&(this._live_latency_synchronizer=new z(this._config,this._media_element)),this._media_element.readyState>0&&this._seeking_handler.directSeek(0)},L.prototype.unload=function(){var c,C,j,fe,re,V;(c=this._media_element)===null||c===void 0||c.pause(),this._worker.postMessage({cmd:"unload"}),(C=this._live_latency_synchronizer)===null||C===void 0||C.destroy(),this._live_latency_synchronizer=null,(j=this._live_latency_chaser)===null||j===void 0||j.destroy(),this._live_latency_chaser=null,(fe=this._startup_stall_jumper)===null||fe===void 0||fe.destroy(),this._startup_stall_jumper=null,(re=this._loading_controller)===null||re===void 0||re.destroy(),this._loading_controller=null,(V=this._seeking_handler)===null||V===void 0||V.destroy(),this._seeking_handler=null},L.prototype.play=function(){return this._media_element.play()},L.prototype.pause=function(){this._media_element.pause()},L.prototype.seek=function(c){this._media_element&&this._seeking_handler?this._seeking_handler.seek(c):this._pending_seek_time=c},Object.defineProperty(L.prototype,"mediaInfo",{get:function(){return Object.assign({},this._media_info)},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"statisticsInfo",{get:function(){return Object.assign({},this._statistics_info)},enumerable:!1,configurable:!0}),L.prototype._onLoggingConfigChanged=function(c){var C;(C=this._worker)===null||C===void 0||C.postMessage({cmd:"logging_config",logging_config:c})},L.prototype._onMSEUpdateEnd=function(){this._config.isLive&&this._config.liveBufferLatencyChasing&&this._live_latency_chaser&&this._live_latency_chaser.notifyBufferedRangeUpdate(),this._loading_controller.notifyBufferedPositionChanged()},L.prototype._onMSEBufferFull=function(){b.default.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._loading_controller.suspendTransmuxer()},L.prototype._onMediaLoadedMetadata=function(c){this._pending_seek_time!=null&&(this._seeking_handler.seek(this._pending_seek_time),this._pending_seek_time=null)},L.prototype._onRequestDirectSeek=function(c){this._seeking_handler.directSeek(c)},L.prototype._onRequiredUnbufferedSeek=function(c){this._worker.postMessage({cmd:"unbuffered_seek",milliseconds:c})},L.prototype._onRequestPauseTransmuxer=function(){this._worker.postMessage({cmd:"pause_transmuxer"})},L.prototype._onRequestResumeTransmuxer=function(){this._worker.postMessage({cmd:"resume_transmuxer"})},L.prototype._onMediaTimeUpdate=function(c){this._worker.postMessage({cmd:"timeupdate",current_time:c.target.currentTime})},L.prototype._onMediaReadyStateChange=function(c){this._worker.postMessage({cmd:"readystatechange",ready_state:c.target.readyState})},L.prototype._onWorkerMessage=function(c){var C,j=c.data,fe=j.msg;if(fe=="destroyed"||this._worker_destroying)return this._worker_destroying=!1,(C=this._worker)===null||C===void 0||C.terminate(),void(this._worker=null);switch(fe){case"mse_init":var re=j;typeof self.ManagedMediaSource=="function"&&typeof self.MediaSource!="function"&&(this._media_element.disableRemotePlayback=!0),this._media_element.srcObject=re.handle;break;case"mse_event":(re=j).event==m.default.UPDATE_END?this._onMSEUpdateEnd():re.event==m.default.BUFFER_FULL&&this._onMSEBufferFull();break;case"transmuxing_event":if((re=j).event==K.default.MEDIA_INFO){var V=j;this._media_info=V.info,this._emitter.emit(A.default.MEDIA_INFO,Object.assign({},V.info))}else if(re.event==K.default.STATISTICS_INFO){var Y=j;this._statistics_info=this._fillStatisticsInfo(Y.info),this._emitter.emit(A.default.STATISTICS_INFO,Object.assign({},Y.info))}else if(re.event==K.default.RECOMMEND_SEEKPOINT){var ie=j;this._media_element&&!this._config.accurateSeek&&this._seeking_handler.directSeek(ie.milliseconds/1000)}break;case"player_event":if((re=j).event==A.default.ERROR){var oe=j;this._emitter.emit(A.default.ERROR,oe.error_type,oe.error_detail,oe.info)}else if("extraData"in re){var ue=j;this._emitter.emit(ue.event,ue.extraData)}break;case"logcat_callback":re=j,b.default.emitter.emit("log",re.type,re.logcat);break;case"buffered_position_changed":re=j,this._loading_controller.notifyBufferedPositionChanged(re.buffered_position_milliseconds/1000)}},L.prototype._fillStatisticsInfo=function(c){if(c.playerType="MSEPlayer",!(this._media_element instanceof HTMLVideoElement))return c;var C=!0,j=0,fe=0;if(this._media_element.getVideoPlaybackQuality){var re=this._media_element.getVideoPlaybackQuality();j=re.totalVideoFrames,fe=re.droppedVideoFrames}else this._media_element.webkitDecodedFrameCount!=null?(j=this._media_element.webkitDecodedFrameCount,fe=this._media_element.webkitDroppedFrameCount):C=!1;return C&&(c.decodedFrames=j,c.droppedFrames=fe),c},L}(),ee=function(){function L(c,C){this.TAG="MSEPlayer",this._type="MSEPlayer",this._media_element=null,this._player_engine=null;var j=c.type.toLowerCase();if(j!=="mse"&&j!=="mpegts"&&j!=="m2ts"&&j!=="flv")throw new x.InvalidArgumentException("MSEPlayer requires an mpegts/m2ts/flv MediaDataSource input!");if(C&&C.enableWorkerForMSE&&te.isSupported())try{this._player_engine=new te(c,C)}catch(fe){b.default.e(this.TAG,"Error while initializing PlayerEngineDedicatedThread, fallback to PlayerEngineMainThread"),this._player_engine=new se(c,C)}else this._player_engine=new se(c,C)}return L.prototype.destroy=function(){this._player_engine.destroy(),this._player_engine=null,this._media_element=null},L.prototype.on=function(c,C){this._player_engine.on(c,C)},L.prototype.off=function(c,C){this._player_engine.off(c,C)},L.prototype.attachMediaElement=function(c){this._media_element=c,this._player_engine.attachMediaElement(c)},L.prototype.detachMediaElement=function(){this._media_element=null,this._player_engine.detachMediaElement()},L.prototype.load=function(){this._player_engine.load()},L.prototype.unload=function(){this._player_engine.unload()},L.prototype.play=function(){return this._player_engine.play()},L.prototype.pause=function(){this._player_engine.pause()},Object.defineProperty(L.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"buffered",{get:function(){return this._media_element.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"duration",{get:function(){return this._media_element.duration},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"volume",{get:function(){return this._media_element.volume},set:function(c){this._media_element.volume=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"muted",{get:function(){return this._media_element.muted},set:function(c){this._media_element.muted=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"currentTime",{get:function(){return this._media_element?this._media_element.currentTime:0},set:function(c){this._player_engine.seek(c)},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"mediaInfo",{get:function(){return this._player_engine.mediaInfo},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"statisticsInfo",{get:function(){return this._player_engine.statisticsInfo},enumerable:!1,configurable:!0}),L}(),Re=function(){function L(c,C){this.TAG="NativePlayer",this._type="NativePlayer",this._emitter=new(w()),this._config=S(),typeof C=="object"&&Object.assign(this._config,C);var j=c.type.toLowerCase();if(j==="mse"||j==="mpegts"||j==="m2ts"||j==="flv")throw new x.InvalidArgumentException("NativePlayer does't support mse/mpegts/m2ts/flv MediaDataSource input!");if(c.hasOwnProperty("segments"))throw new x.InvalidArgumentException("NativePlayer(".concat(c.type,") doesn't support multipart playback!"));this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this)},this._pendingSeekTime=null,this._statisticsReporter=null,this._mediaDataSource=c,this._mediaElement=null}return L.prototype.destroy=function(){this._emitter.emit(A.default.DESTROYING),this._mediaElement&&(this.unload(),this.detachMediaElement()),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null},L.prototype.on=function(c,C){var j=this;c===A.default.MEDIA_INFO?this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(function(){j._emitter.emit(A.default.MEDIA_INFO,j.mediaInfo)}):c===A.default.STATISTICS_INFO&&this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(function(){j._emitter.emit(A.default.STATISTICS_INFO,j.statisticsInfo)}),this._emitter.addListener(c,C)},L.prototype.off=function(c,C){this._emitter.removeListener(c,C)},L.prototype.attachMediaElement=function(c){if(this._mediaElement=c,c.addEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._pendingSeekTime!=null)try{c.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch(C){}},L.prototype.detachMediaElement=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src"),this._mediaElement.removeEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._mediaElement=null),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},L.prototype.load=function(){if(!this._mediaElement)throw new x.IllegalStateException("HTMLMediaElement must be attached before load()!");this._mediaElement.src=this._mediaDataSource.url,this._mediaElement.readyState>0&&(this._mediaElement.currentTime=0),this._mediaElement.preload="auto",this._mediaElement.load(),this._statisticsReporter=window.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval)},L.prototype.unload=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src")),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},L.prototype.play=function(){return this._mediaElement.play()},L.prototype.pause=function(){this._mediaElement.pause()},Object.defineProperty(L.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"buffered",{get:function(){return this._mediaElement.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"duration",{get:function(){return this._mediaElement.duration},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"volume",{get:function(){return this._mediaElement.volume},set:function(c){this._mediaElement.volume=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"muted",{get:function(){return this._mediaElement.muted},set:function(c){this._mediaElement.muted=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"currentTime",{get:function(){return this._mediaElement?this._mediaElement.currentTime:0},set:function(c){this._mediaElement?this._mediaElement.currentTime=c:this._pendingSeekTime=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"mediaInfo",{get:function(){var c={mimeType:(this._mediaElement instanceof HTMLAudioElement?"audio/":"video/")+this._mediaDataSource.type};return this._mediaElement&&(c.duration=Math.floor(1000*this._mediaElement.duration),this._mediaElement instanceof HTMLVideoElement&&(c.width=this._mediaElement.videoWidth,c.height=this._mediaElement.videoHeight)),c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"statisticsInfo",{get:function(){var c={playerType:this._type,url:this._mediaDataSource.url};if(!(this._mediaElement instanceof HTMLVideoElement))return c;var C=!0,j=0,fe=0;if(this._mediaElement.getVideoPlaybackQuality){var re=this._mediaElement.getVideoPlaybackQuality();j=re.totalVideoFrames,fe=re.droppedVideoFrames}else this._mediaElement.webkitDecodedFrameCount!=null?(j=this._mediaElement.webkitDecodedFrameCount,fe=this._mediaElement.webkitDroppedFrameCount):C=!1;return C&&(c.decodedFrames=j,c.droppedFrames=fe),c},enumerable:!1,configurable:!0}),L.prototype._onvLoadedMetadata=function(c){this._pendingSeekTime!=null&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null),this._emitter.emit(A.default.MEDIA_INFO,this.mediaInfo)},L.prototype._reportStatisticsInfo=function(){this._emitter.emit(A.default.STATISTICS_INFO,this.statisticsInfo)},L}();X.default.install();var J={createPlayer:function(L,c){var C=L;if(C==null||typeof C!="object")throw new x.InvalidArgumentException("MediaDataSource must be an javascript object!");if(!C.hasOwnProperty("type"))throw new x.InvalidArgumentException("MediaDataSource must has type field to indicate video file type!");switch(C.type){case"mse":case"mpegts":case"m2ts":case"flv":return new ee(C,c);default:return new Re(C,c)}},isSupported:function(){return v.supportMSEH264Playback()},getFeatureList:function(){return v.getFeatureList()}};J.BaseLoader=I.BaseLoader,J.LoaderStatus=I.LoaderStatus,J.LoaderErrors=I.LoaderErrors,J.Events=A.default,J.ErrorTypes=N.ErrorTypes,J.ErrorDetails=N.ErrorDetails,J.MSEPlayer=ee,J.NativePlayer=Re,J.LoggingControl=me.default,Object.defineProperty(J,"version",{enumerable:!0,get:function(){return"1.8.2"}});var ke=J},355:function(le,Q,D){D.r(Q),D.d(Q,{ErrorDetails:function(){return S},ErrorTypes:function(){return _}});var X=D(470),P=D(827),_={NETWORK_ERROR:"NetworkError",MEDIA_ERROR:"MediaError",OTHER_ERROR:"OtherError"},S={NETWORK_EXCEPTION:X.LoaderErrors.EXCEPTION,NETWORK_STATUS_CODE_INVALID:X.LoaderErrors.HTTP_STATUS_CODE_INVALID,NETWORK_TIMEOUT:X.LoaderErrors.CONNECTING_TIMEOUT,NETWORK_UNRECOVERABLE_EARLY_EOF:X.LoaderErrors.UNRECOVERABLE_EARLY_EOF,MEDIA_MSE_ERROR:"MediaMSEError",MEDIA_FORMAT_ERROR:P.default.FORMAT_ERROR,MEDIA_FORMAT_UNSUPPORTED:P.default.FORMAT_UNSUPPORTED,MEDIA_CODEC_UNSUPPORTED:P.default.CODEC_UNSUPPORTED}},994:function(le,Q,D){D.r(Q);var X={};(function(){var P=self.navigator.userAgent.toLowerCase(),_=/(edge)\/([\w.]+)/.exec(P)||/(opr)[\/]([\w.]+)/.exec(P)||/(chrome)[ \/]([\w.]+)/.exec(P)||/(iemobile)[\/]([\w.]+)/.exec(P)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(P)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(P)||/(webkit)[ \/]([\w.]+)/.exec(P)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(P)||/(msie) ([\w.]+)/.exec(P)||P.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(P)||P.indexOf("compatible")<0&&/(firefox)[ \/]([\w.]+)/.exec(P)||[],S=/(ipad)/.exec(P)||/(ipod)/.exec(P)||/(windows phone)/.exec(P)||/(iphone)/.exec(P)||/(kindle)/.exec(P)||/(android)/.exec(P)||/(windows)/.exec(P)||/(mac)/.exec(P)||/(linux)/.exec(P)||/(cros)/.exec(P)||[],R={browser:_[5]||_[3]||_[1]||"",version:_[2]||_[4]||"0",majorVersion:_[4]||_[2]||"0",platform:S[0]||""},v={};if(R.browser){v[R.browser]=!0;var I=R.majorVersion.split(".");v.version={major:parseInt(R.majorVersion,10),string:R.version},I.length>1&&(v.version.minor=parseInt(I[1],10)),I.length>2&&(v.version.build=parseInt(I[2],10))}if(R.platform&&(v[R.platform]=!0),(v.chrome||v.opr||v.safari)&&(v.webkit=!0),v.rv||v.iemobile){v.rv&&delete v.rv;var b="msie";R.browser=b,v[b]=!0}if(v.edge){delete v.edge;var k="msedge";R.browser=k,v[k]=!0}if(v.opr){var w="opera";R.browser=w,v[w]=!0}if(v.safari&&v.android){var O="android";R.browser=O,v[O]=!0}for(var A in v.name=R.browser,v.platform=R.platform,X)X.hasOwnProperty(A)&&delete X[A];Object.assign(X,v)})(),Q.default=X},867:function(le,Q,D){D.r(Q),D.d(Q,{IllegalStateException:function(){return S},InvalidArgumentException:function(){return R},NotImplementedException:function(){return v},RuntimeException:function(){return _}});var X,P=(X=function(I,b){return X=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(k,w){k.__proto__=w}||function(k,w){for(var O in w)Object.prototype.hasOwnProperty.call(w,O)&&(k[O]=w[O])},X(I,b)},function(I,b){if(typeof b!="function"&&b!==null)throw TypeError("Class extends value "+String(b)+" is not a constructor or null");function k(){this.constructor=I}X(I,b),I.prototype=b===null?Object.create(b):(k.prototype=b.prototype,new k)}),_=function(){function I(b){this._message=b}return Object.defineProperty(I.prototype,"name",{get:function(){return"RuntimeException"},enumerable:!1,configurable:!0}),Object.defineProperty(I.prototype,"message",{get:function(){return this._message},enumerable:!1,configurable:!0}),I.prototype.toString=function(){return this.name+": "+this.message},I}(),S=function(I){function b(k){return I.call(this,k)||this}return P(b,I),Object.defineProperty(b.prototype,"name",{get:function(){return"IllegalStateException"},enumerable:!1,configurable:!0}),b}(_),R=function(I){function b(k){return I.call(this,k)||this}return P(b,I),Object.defineProperty(b.prototype,"name",{get:function(){return"InvalidArgumentException"},enumerable:!1,configurable:!0}),b}(_),v=function(I){function b(k){return I.call(this,k)||this}return P(b,I),Object.defineProperty(b.prototype,"name",{get:function(){return"NotImplementedException"},enumerable:!1,configurable:!0}),b}(_)},856:function(le,Q,D){D.r(Q);var X=D(7),P=D.n(X),_=function(){function S(){}return S.e=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","error",I),S.ENABLE_ERROR&&(console.error?console.error(I):console.warn?console.warn(I):console.log(I))},S.i=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","info",I),S.ENABLE_INFO&&(console.info?console.info(I):console.log(I))},S.w=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","warn",I),S.ENABLE_WARN&&(console.warn?console.warn(I):console.log(I))},S.d=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","debug",I),S.ENABLE_DEBUG&&(console.debug?console.debug(I):console.log(I))},S.v=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","verbose",I),S.ENABLE_VERBOSE&&console.log(I)},S}();_.GLOBAL_TAG="mpegts.js",_.FORCE_GLOBAL_TAG=!1,_.ENABLE_ERROR=!0,_.ENABLE_INFO=!0,_.ENABLE_WARN=!0,_.ENABLE_DEBUG=!0,_.ENABLE_VERBOSE=!0,_.ENABLE_CALLBACK=!1,_.emitter=new(P()),Q.default=_},947:function(le,Q,D){D.r(Q);var X=D(7),P=D.n(X),_=D(856),S=function(){function R(){}return Object.defineProperty(R,"forceGlobalTag",{get:function(){return _.default.FORCE_GLOBAL_TAG},set:function(v){_.default.FORCE_GLOBAL_TAG=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"globalTag",{get:function(){return _.default.GLOBAL_TAG},set:function(v){_.default.GLOBAL_TAG=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableAll",{get:function(){return _.default.ENABLE_VERBOSE&&_.default.ENABLE_DEBUG&&_.default.ENABLE_INFO&&_.default.ENABLE_WARN&&_.default.ENABLE_ERROR},set:function(v){_.default.ENABLE_VERBOSE=v,_.default.ENABLE_DEBUG=v,_.default.ENABLE_INFO=v,_.default.ENABLE_WARN=v,_.default.ENABLE_ERROR=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableDebug",{get:function(){return _.default.ENABLE_DEBUG},set:function(v){_.default.ENABLE_DEBUG=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableVerbose",{get:function(){return _.default.ENABLE_VERBOSE},set:function(v){_.default.ENABLE_VERBOSE=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableInfo",{get:function(){return _.default.ENABLE_INFO},set:function(v){_.default.ENABLE_INFO=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableWarn",{get:function(){return _.default.ENABLE_WARN},set:function(v){_.default.ENABLE_WARN=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableError",{get:function(){return _.default.ENABLE_ERROR},set:function(v){_.default.ENABLE_ERROR=v,R._notifyChange()},enumerable:!1,configurable:!0}),R.getConfig=function(){return{globalTag:_.default.GLOBAL_TAG,forceGlobalTag:_.default.FORCE_GLOBAL_TAG,enableVerbose:_.default.ENABLE_VERBOSE,enableDebug:_.default.ENABLE_DEBUG,enableInfo:_.default.ENABLE_INFO,enableWarn:_.default.ENABLE_WARN,enableError:_.default.ENABLE_ERROR,enableCallback:_.default.ENABLE_CALLBACK}},R.applyConfig=function(v){_.default.GLOBAL_TAG=v.globalTag,_.default.FORCE_GLOBAL_TAG=v.forceGlobalTag,_.default.ENABLE_VERBOSE=v.enableVerbose,_.default.ENABLE_DEBUG=v.enableDebug,_.default.ENABLE_INFO=v.enableInfo,_.default.ENABLE_WARN=v.enableWarn,_.default.ENABLE_ERROR=v.enableError,_.default.ENABLE_CALLBACK=v.enableCallback},R._notifyChange=function(){var v=R.emitter;if(v.listenerCount("change")>0){var I=R.getConfig();v.emit("change",I)}},R.registerListener=function(v){R.emitter.addListener("change",v)},R.removeListener=function(v){R.emitter.removeListener("change",v)},R.addLogListener=function(v){_.default.emitter.addListener("log",v),_.default.emitter.listenerCount("log")>0&&(_.default.ENABLE_CALLBACK=!0,R._notifyChange())},R.removeLogListener=function(v){_.default.emitter.removeListener("log",v),_.default.emitter.listenerCount("log")===0&&(_.default.ENABLE_CALLBACK=!1,R._notifyChange())},R}();S.emitter=new(P()),Q.default=S},811:function(le,Q,D){D.r(Q);var X=function(){function P(){}return P.install=function(){Object.setPrototypeOf=Object.setPrototypeOf||function(_,S){return _.__proto__=S,_},Object.assign=Object.assign||function(_){if(_==null)throw TypeError("Cannot convert undefined or null to object");for(var S=Object(_),R=1;R0?0|S:0;return this.substring(R,R+_.length)===_}}),typeof self.Promise!="function"&&D(964).polyfill()},P}();X.install(),Q.default=X},861:function(le,Q,D){function X(b){var k={};function w(A){if(k[A])return k[A].exports;var G=k[A]={i:A,id:A,l:!1,loaded:!1,exports:{}};return b[A].call(G.exports,G,G.exports,w),G.l=!0,G.loaded=!0,G.exports}w.m=b,w.c=k,w.d=function(A,G){for(var m in G)w.o(G,m)&&!w.o(A,m)&&Object.defineProperty(A,m,{enumerable:!0,get:G[m]})},w.r=function(A){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(A,"__esModule",{value:!0})},w.n=function(A){var G=A&&A.__esModule?function(){return A.default}:function(){return A};return w.d(G,{a:G}),G},w.o=function(A,G){return Object.prototype.hasOwnProperty.call(A,G)},w.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||Function("return this")()}catch(A){if(typeof self=="object")return self}}(),w.p="/";var O=w(ENTRY_MODULE);return O.default||O}var P="[\\.|\\-|\\+|\\w|/|@]+",_="\\(\\s*(/\\*.*?\\*/)?\\s*.*?("+P+").*?\\)";function S(b){return(b+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function R(b){return!isNaN(1*b)}function v(b,k,w){var O={};O[w]=[];var A=k.toString(),G=A.match(/^(?:function\s*\w*\s*)?\(\s*\w+\s*,\s*\w+\s*,\s*(\w+)\s*\)/);if(!G)return O;for(var m,N=G[1],x=new RegExp("(\\\\n|\\W)"+S(N)+_,"g");m=x.exec(A);)m[3]!=="dll-reference"&&O[w].push(m[3]);for(x=new RegExp("\\("+S(N)+'\\("(dll-reference\\s('+P+'))"\\)\\)'+_,"g");m=x.exec(A);)b[m[2]]||(O[w].push(m[1]),b[m[2]]=D(m[1]).m),O[m[2]]=O[m[2]]||[],O[m[2]].push(m[4]);for(var K=Object.keys(O),M=0;M0},!1)}le.exports=function(b,k){k=k||{};var w={main:D.m},O=k.all?{main:Object.keys(w.main)}:function(x,K){for(var M={main:[K]},u={main:[]},h={main:{}};I(M);)for(var p=Object.keys(M),E=0;E{try{return Ae(R)}catch{return!1}})){let R=_t(_);if(R)D.push(R)}}if(D.length===0)return null;let X=D.length===1?D[0]:`${String(D[0])} and ${String(D[1])}`;return`This ${le} is ${String(X)}, which this browser cannot decode.${Me?` ${Me}`:""}`}var bi="VLC can — the button is beside Play.";function Ct(_e,Ae){return ct(_e,Ae,bi,"channel")}var Ai=[[/\bAFT[A-Z0-9]+\b/i,"firetv"],[/\bKF[A-Z]+\b/,"silk"],[/\bSilk\b/i,"silk"],[/\bAndroid TV\b/i,"androidtv"],[/\bGoogleTV\b/i,"googletv"],[/\bTizen\b/i,"tizen"],[/\bWeb0S\b/i,"webos"],[/\bRoku\b/i,"roku"],[/AppleTV/i,"appletv"],[/\bCrKey\b/i,"chromecast"],[/\bSMART-TV\b/i,"smarttv"],[/\bSmartTV\b/i,"smarttv"]];function Ri(_e){if(!_e)return null;for(let[Ae,Me]of Ai)if(Ae.test(_e))return Me;return null}function wt(_e){return Ri(_e)!==null}function It(_e){return{enableWorker:!1,enableStashBuffer:!0,stashInitialSize:393216,liveBufferLatencyChasing:!1,liveBufferLatencyMaxLatency:5,liveBufferLatencyMinRemain:1,autoCleanupSourceBuffer:!0,autoCleanupMaxBackwardDuration:30,autoCleanupMinBackwardDuration:10,lazyLoad:!1,lazyLoadMaxDuration:60,lazyLoadRecoverDuration:30,seekType:"range"}}function Ti(){try{return Boolean(Ye.default.getFeatureList().mseLivePlayback)}catch{return!1}}var Bt=5,Li=2000,ki=5000,Di=3;function Mi(_e,Ae,Me,le=()=>{}){let Q=It(wt(navigator.userAgent)),D=null,X=!1,P=0,_=null,S=null,R=-1,v=0,I=()=>{if(_)clearTimeout(_);if(S)clearInterval(S);_=null,S=null},b=()=>{if(!D)return;let m=D;D=null;try{m.destroy()}catch{}},k=(m)=>{if(X)return;X=!0,I(),b(),Me(m)},w=(m)=>{if(X)return;if(P>=Bt)return k(m);P+=1,I(),b(),le(`Reconnecting… (${P}/${Bt})`),_=setTimeout(()=>{if(_=null,!X)A()},Li*2**(P-1))},O=()=>{if(S)clearInterval(S);R=_e.currentTime,v=0,S=setInterval(()=>{if(X||!D)return;if(_e.paused||_e.ended||_e.seeking){v=0,R=_e.currentTime;return}if(_e.currentTime===R){if(v+=1,v>=Di)v=0,w("The stream stopped sending. Try VLC, or press Play again.");return}R=_e.currentTime,v=0},ki)};function A(){D=Ye.default.createPlayer({type:"mpegts",isLive:!0,url:Ae,withCredentials:!0},Q),D.on(Ye.default.Events.MEDIA_INFO,(m)=>{let N=Ct(m,(x)=>window.MediaSource?.isTypeSupported?.(x)??!1);if(N)k(N)}),D.on(Ye.default.Events.ERROR,(m,N,x)=>{let K=x?.code;if(K===429)return k("The line was busy. Try that again.");if(K===409)return k("Somebody else is watching that line right now. Try again in a bit.");if(K===404)return k("That channel is no longer on your list.");if(K===415)return k("That channel needs a different player. Try VLC.");if(K===502||K===504)return k("Your provider did not send a stream for that channel.");if(m===Ye.default.ErrorTypes.NETWORK_ERROR)return w("The stream stopped. Your provider may have dropped it, or you started another channel somewhere else.");w(N?`That stream could not be played here (${N}). Try VLC.`:"That stream could not be played here. Try VLC.")}),D.attachMediaElement(_e),D.load(),D.play()?.catch(()=>{}),O()}let G=()=>{P=0,le(null)};return _e.addEventListener("playing",G),A(),()=>{X=!0,I(),_e.removeEventListener("playing",G),b(),_e.removeAttribute("src"),_e.load()}}window.__tipoffPlayer={supported:Ti,attach:Mi}; +var ci=Object.create;var{getPrototypeOf:hi,defineProperty:Dt,getOwnPropertyNames:fi}=Object;var pi=Object.prototype.hasOwnProperty;function mi(_e){return this[_e]}var gi,yi,vi=(_e,Ae,Me)=>{var le=_e!=null&&typeof _e==="object";if(le){var Q=Ae?gi??=new WeakMap:yi??=new WeakMap,D=Q.get(_e);if(D)return D}Me=_e!=null?ci(hi(_e)):{};let X=Ae||!_e||!_e.__esModule?Dt(Me,"default",{value:_e,enumerable:!0}):Me;if(_e&&typeof _e==="object"||typeof _e==="function"){for(let P of fi(_e))if(!pi.call(X,P))Dt(X,P,{get:mi.bind(_e,P),enumerable:!0})}if(le)Q.set(_e,X);return X};var Si=(_e,Ae)=>()=>(Ae||_e((Ae={exports:{}}).exports,Ae),Ae.exports);var Mt=Si(function(et,lt){/*! For license information please see mpegts.js.LICENSE.txt */(function(_e,Ae){typeof et=="object"&&typeof lt=="object"?lt.exports=Ae():typeof define=="function"&&define.amd?define([],Ae):typeof et=="object"?et.mpegts=Ae():_e.mpegts=Ae()})(et,function(){return function(){var _e={964:function(le,Q,D){le.exports=function(){function X(V){return typeof V=="function"}var P=Array.isArray?Array.isArray:function(V){return Object.prototype.toString.call(V)==="[object Array]"},_=0,S=void 0,R=void 0,v=function(V,Y){G[_]=V,G[_+1]=Y,(_+=2)===2&&(R?R(m):u())},I=typeof window<"u"?window:void 0,b=I||{},k=b.MutationObserver||b.WebKitMutationObserver,w=typeof self>"u"&&typeof process<"u"&&{}.toString.call(process)==="[object process]",O=typeof Uint8ClampedArray<"u"&&typeof importScripts<"u"&&typeof MessageChannel<"u";function A(){var V=setTimeout;return function(){return V(m,1)}}var G=Array(1000);function m(){for(var V=0;V<_;V+=2)(0,G[V])(G[V+1]),G[V]=void 0,G[V+1]=void 0;_=0}var U,x,K,M,u=void 0;function h(V,Y){var ie=this,oe=new this.constructor(W);oe[E]===void 0&&j(oe);var ue=ie._state;if(ue){var Ee=arguments[ue-1];v(function(){return c(ue,oe,Ee,ie._result)})}else ke(ie,oe,V,Y);return oe}function p(V){if(V&&typeof V=="object"&&V.constructor===this)return V;var Y=new this(W);return te(Y,V),Y}u=w?function(){return process.nextTick(m)}:k?(x=0,K=new k(m),M=document.createTextNode(""),K.observe(M,{characterData:!0}),function(){M.data=x=++x%2}):O?((U=new MessageChannel).port1.onmessage=m,function(){return U.port2.postMessage(0)}):I===void 0?function(){try{var V=Function("return this")().require("vertx");return(S=V.runOnLoop||V.runOnContext)!==void 0?function(){S(m)}:A()}catch(Y){return A()}}():A();var E=Math.random().toString(36).substring(2);function W(){}var z=void 0,se=1,de=2;function me(V,Y,ie){Y.constructor===V.constructor&&ie===h&&Y.constructor.resolve===p?function(oe,ue){ue._state===se?Re(oe,ue._result):ue._state===de?J(oe,ue._result):ke(ue,void 0,function(Ee){return te(oe,Ee)},function(Ee){return J(oe,Ee)})}(V,Y):ie===void 0?Re(V,Y):X(ie)?function(oe,ue,Ee){v(function(Pe){var Ue=!1,je=function(Fe,Xe,nt,Ne){try{Fe.call(Xe,nt,Ne)}catch(Qe){return Qe}}(Ee,ue,function(Fe){Ue||(Ue=!0,ue!==Fe?te(Pe,Fe):Re(Pe,Fe))},function(Fe){Ue||(Ue=!0,J(Pe,Fe))},Pe._label);!Ue&&je&&(Ue=!0,J(Pe,je))},oe)}(V,Y,ie):Re(V,Y)}function te(V,Y){if(V===Y)J(V,TypeError("You cannot resolve a promise with itself"));else if(ue=typeof(oe=Y),oe===null||ue!=="object"&&ue!=="function")Re(V,Y);else{var ie=void 0;try{ie=Y.then}catch(Ee){return void J(V,Ee)}me(V,Y,ie)}var oe,ue}function ee(V){V._onerror&&V._onerror(V._result),L(V)}function Re(V,Y){V._state===z&&(V._result=Y,V._state=se,V._subscribers.length!==0&&v(L,V))}function J(V,Y){V._state===z&&(V._state=de,V._result=Y,v(ee,V))}function ke(V,Y,ie,oe){var ue=V._subscribers,Ee=ue.length;V._onerror=null,ue[Ee]=Y,ue[Ee+se]=ie,ue[Ee+de]=oe,Ee===0&&V._state&&v(L,V)}function L(V){var{_subscribers:Y,_state:ie}=V;if(Y.length!==0){for(var oe=void 0,ue=void 0,Ee=V._result,Pe=0;Pe0&&h.length>M&&!h.warned){h.warned=!0;var E=Error("Possible EventEmitter memory leak detected. "+h.length+" "+String(U)+" listeners added. Use emitter.setMaxListeners() to increase limit");E.name="MaxListenersExceededWarning",E.emitter=m,E.type=U,E.count=h.length,p=E,console&&console.warn&&console.warn(p)}return m}function b(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function k(m,U,x){var K={fired:!1,wrapFn:void 0,target:m,type:U,listener:x},M=b.bind(K);return M.listener=x,K.wrapFn=M,M}function w(m,U,x){var K=m._events;if(K===void 0)return[];var M=K[U];return M===void 0?[]:typeof M=="function"?x?[M.listener||M]:[M]:x?function(u){for(var h=Array(u.length),p=0;p0&&(u=U[0]),u instanceof Error)throw u;var h=Error("Unhandled error."+(u?" ("+u.message+")":""));throw h.context=u,h}var p=M[m];if(p===void 0)return!1;if(typeof p=="function")X(p,this,U);else{var E=p.length,W=A(p,E);for(x=0;x=0;u--)if(x[u]===U||x[u].listener===U){h=x[u].listener,M=u;break}if(M<0)return this;M===0?x.shift():function(p,E){for(;E+1=0;K--)this.removeListener(m,U[K]);return this},_.prototype.listeners=function(m){return w(this,m,!0)},_.prototype.rawListeners=function(m){return w(this,m,!1)},_.listenerCount=function(m,U){return typeof m.listenerCount=="function"?m.listenerCount(U):O.call(m,U)},_.prototype.listenerCount=O,_.prototype.eventNames=function(){return this._eventsCount>0?Q(this._events):[]}},955:function(le,Q,D){D.r(Q);var X=function(){function P(){this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.refFrames=null,this.chromaFormat=null,this.sarNum=null,this.sarDen=null,this.metadata=null,this.segments=null,this.segmentCount=null,this.hasKeyframesIndex=null,this.keyframesIndex=null}return P.prototype.isComplete=function(){var _=this.hasAudio===!1||this.hasAudio===!0&&this.audioCodec!=null&&this.audioSampleRate!=null&&this.audioChannelCount!=null,S=this.hasVideo===!1||this.hasVideo===!0&&this.videoCodec!=null&&this.width!=null&&this.height!=null&&this.fps!=null&&this.profile!=null&&this.level!=null&&this.refFrames!=null&&this.chromaFormat!=null&&this.sarNum!=null&&this.sarDen!=null;return this.mimeType!=null&&_&&S},P.prototype.isSeekable=function(){return this.hasKeyframesIndex===!0},P.prototype.getNearestKeyframe=function(_){if(this.keyframesIndex==null)return null;var S=this.keyframesIndex,R=this._search(S.times,_);return{index:R,milliseconds:S.times[R],fileposition:S.filepositions[R]}},P.prototype._search=function(_,S){var R=0,v=_.length-1,I=0,b=0,k=v;for(S<_[0]&&(R=0,b=k+1);b<=k;){if((I=b+Math.floor((k-b)/2))===v||S>=_[I]&&S<_[I+1]){R=I;break}_[I]0&&v[0].originalDts=I[w].dts&&vI[k].lastSample.originalDts&&v=I[k].lastSample.originalDts&&(k===I.length-1||k0&&(w=this._searchNearestSegmentBefore(b.originalBeginDts)+1),this._lastAppendLocation=w,this._list.splice(w,0,b)},R.prototype.getLastSegmentBefore=function(v){var I=this._searchNearestSegmentBefore(v);return I>=0?this._list[I]:null},R.prototype.getLastSampleBefore=function(v){var I=this.getLastSegmentBefore(v);return I!=null?I.lastSample:null},R.prototype.getLastSyncPointBefore=function(v){for(var I=this._searchNearestSegmentBefore(v),b=this._list[I].syncPoints;b.length===0&&I>0;)I--,b=this._list[I].syncPoints;return b.length>0?b[b.length-1]:null},R}()},346:function(le,Q,D){D.r(Q);var X=D(7),P=D.n(X),_=D(856),S=D(994),R=D(403),v=D(867),I=function(){function b(k){this.TAG="MSEController",this._config=k,this._emitter=new(P()),this._config.isLive&&this._config.autoCleanupSourceBuffer==null&&(this._config.autoCleanupSourceBuffer=!0),this.e={onSourceOpen:this._onSourceOpen.bind(this),onSourceEnded:this._onSourceEnded.bind(this),onSourceClose:this._onSourceClose.bind(this),onStartStreaming:this._onStartStreaming.bind(this),onEndStreaming:this._onEndStreaming.bind(this),onQualityChange:this._onQualityChange.bind(this),onSourceBufferError:this._onSourceBufferError.bind(this),onSourceBufferUpdateEnd:this._onSourceBufferUpdateEnd.bind(this)},this._useManagedMediaSource=typeof self.ManagedMediaSource=="function"&&typeof self.MediaSource!="function",this._mediaSource=null,this._mediaSourceObjectURL=null,this._mediaElementProxy=null,this._isBufferFull=!1,this._hasPendingEos=!1,this._requireSetMediaDuration=!1,this._pendingMediaDuration=0,this._pendingSourceBufferInit=[],this._mimeTypes={video:null,audio:null},this._sourceBuffers={video:null,audio:null},this._lastInitSegments={video:null,audio:null},this._pendingSegments={video:[],audio:[]},this._pendingRemoveRanges={video:[],audio:[]}}return b.prototype.destroy=function(){this._mediaSource&&this.shutdown(),this._mediaSourceObjectURL&&this.revokeObjectURL(),this.e=null,this._emitter.removeAllListeners(),this._emitter=null},b.prototype.on=function(k,w){this._emitter.addListener(k,w)},b.prototype.off=function(k,w){this._emitter.removeListener(k,w)},b.prototype.initialize=function(k){if(this._mediaSource)throw new v.IllegalStateException("MediaSource has been attached to an HTMLMediaElement!");this._useManagedMediaSource&&_.default.v(this.TAG,"Using ManagedMediaSource");var w=this._mediaSource=this._useManagedMediaSource?new self.ManagedMediaSource:new self.MediaSource;w.addEventListener("sourceopen",this.e.onSourceOpen),w.addEventListener("sourceended",this.e.onSourceEnded),w.addEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(w.addEventListener("startstreaming",this.e.onStartStreaming),w.addEventListener("endstreaming",this.e.onEndStreaming),w.addEventListener("qualitychange",this.e.onQualityChange)),this._mediaElementProxy=k},b.prototype.shutdown=function(){if(this._mediaSource){var k=this._mediaSource;for(var w in this._sourceBuffers){var O=this._pendingSegments[w];O.splice(0,O.length),this._pendingSegments[w]=null,this._pendingRemoveRanges[w]=null,this._lastInitSegments[w]=null;var A=this._sourceBuffers[w];if(A){if(k.readyState!=="closed"){try{k.removeSourceBuffer(A)}catch(G){_.default.e(this.TAG,G.message)}A.removeEventListener("error",this.e.onSourceBufferError),A.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)}this._mimeTypes[w]=null,this._sourceBuffers[w]=null}}if(k.readyState==="open")try{k.endOfStream()}catch(G){_.default.e(this.TAG,G.message)}this._mediaElementProxy=null,k.removeEventListener("sourceopen",this.e.onSourceOpen),k.removeEventListener("sourceended",this.e.onSourceEnded),k.removeEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(k.removeEventListener("startstreaming",this.e.onStartStreaming),k.removeEventListener("endstreaming",this.e.onEndStreaming),k.removeEventListener("qualitychange",this.e.onQualityChange)),this._pendingSourceBufferInit=[],this._isBufferFull=!1,this._mediaSource=null}},b.prototype.isManagedMediaSource=function(){return this._useManagedMediaSource},b.prototype.getObject=function(){if(!this._mediaSource)throw new v.IllegalStateException("MediaSource has not been initialized yet!");return this._mediaSource},b.prototype.getHandle=function(){if(!this._mediaSource)throw new v.IllegalStateException("MediaSource has not been initialized yet!");return this._mediaSource.handle},b.prototype.getObjectURL=function(){if(!this._mediaSource)throw new v.IllegalStateException("MediaSource has not been initialized yet!");return this._mediaSourceObjectURL==null&&(this._mediaSourceObjectURL=URL.createObjectURL(this._mediaSource)),this._mediaSourceObjectURL},b.prototype.revokeObjectURL=function(){this._mediaSourceObjectURL&&(URL.revokeObjectURL(this._mediaSourceObjectURL),this._mediaSourceObjectURL=null)},b.prototype.appendInitSegment=function(k,w){if(w===void 0&&(w=void 0),!this._mediaSource||this._mediaSource.readyState!=="open"||this._mediaSource.streaming===!1)return this._pendingSourceBufferInit.push(k),void this._pendingSegments[k.type].push(k);var O=k,A="".concat(O.container);O.codec&&O.codec.length>0&&(O.codec==="opus"&&S.default.safari&&(O.codec="Opus"),A+=";codecs=".concat(O.codec));var G=!1;if(_.default.v(this.TAG,"Received Initialization Segment, mimeType: "+A),this._lastInitSegments[O.type]=O,A!==this._mimeTypes[O.type]){if(this._mimeTypes[O.type])_.default.v(this.TAG,"Notice: ".concat(O.type," mimeType changed, origin: ").concat(this._mimeTypes[O.type],", target: ").concat(A));else{G=!0;try{var m=this._sourceBuffers[O.type]=this._mediaSource.addSourceBuffer(A);m.addEventListener("error",this.e.onSourceBufferError),m.addEventListener("updateend",this.e.onSourceBufferUpdateEnd)}catch(U){return _.default.e(this.TAG,U.message),void this._emitter.emit(R.default.ERROR,{code:U.code,msg:U.message})}}this._mimeTypes[O.type]=A}w||this._pendingSegments[O.type].push(O),G||this._sourceBuffers[O.type]&&!this._sourceBuffers[O.type].updating&&this._doAppendSegments(),S.default.safari&&O.container==="audio/mpeg"&&O.mediaDuration>0&&(this._requireSetMediaDuration=!0,this._pendingMediaDuration=O.mediaDuration/1000,this._updateMediaSourceDuration())},b.prototype.appendMediaSegment=function(k){var w=k;this._pendingSegments[w.type].push(w),this._config.autoCleanupSourceBuffer&&this._needCleanupSourceBuffer()&&this._doCleanupSourceBuffer();var O=this._sourceBuffers[w.type];!O||O.updating||this._hasPendingRemoveRanges()||this._doAppendSegments()},b.prototype.flush=function(){for(var k in this._sourceBuffers)if(this._sourceBuffers[k]){var w=this._sourceBuffers[k];if(this._mediaSource.readyState==="open")try{w.abort()}catch(x){_.default.e(this.TAG,x.message)}var O=this._pendingSegments[k];if(O.splice(0,O.length),this._mediaSource.readyState!=="closed"){for(var A=0;A=1&&k-A.start(0)>=this._config.autoCleanupMaxBackwardDuration)return!0}}return!1},b.prototype._doCleanupSourceBuffer=function(){var k=this._mediaElementProxy.getCurrentTime();for(var w in this._sourceBuffers){var O=this._sourceBuffers[w];if(O){for(var A=O.buffered,G=!1,m=0;m=this._config.autoCleanupMaxBackwardDuration){G=!0;var K=k-this._config.autoCleanupMinBackwardDuration;this._pendingRemoveRanges[w].push({start:U,end:K})}}else x0&&(isNaN(w)||O>w)&&(_.default.v(this.TAG,"Update MediaSource duration from ".concat(w," to ").concat(O)),this._mediaSource.duration=O),this._requireSetMediaDuration=!1,this._pendingMediaDuration=0}},b.prototype._doRemoveRanges=function(){for(var k in this._pendingRemoveRanges)if(this._sourceBuffers[k]&&!this._sourceBuffers[k].updating)for(var w=this._sourceBuffers[k],O=this._pendingRemoveRanges[k];O.length&&!w.updating;){var A=O.shift();w.remove(A.start,A.end)}},b.prototype._doAppendSegments=function(){var k=this._pendingSegments;for(var w in k)if(this._sourceBuffers[w]&&!this._sourceBuffers[w].updating&&this._mediaSource.streaming!==!1&&k[w].length>0){var O=k[w].shift();if(typeof O.timestampOffset=="number"&&isFinite(O.timestampOffset)){var A=this._sourceBuffers[w].timestampOffset,G=O.timestampOffset/1000;Math.abs(A-G)>0.1&&(_.default.v(this.TAG,"Update MPEG audio timestampOffset from ".concat(A," to ").concat(G)),this._sourceBuffers[w].timestampOffset=G),delete O.timestampOffset}if(!O.data||O.data.byteLength===0)continue;try{this._sourceBuffers[w].appendBuffer(O.data),this._isBufferFull=!1}catch(m){this._pendingSegments[w].unshift(O),m.code===22?(this._isBufferFull||this._emitter.emit(R.default.BUFFER_FULL),this._isBufferFull=!0):(_.default.e(this.TAG,m.message),this._emitter.emit(R.default.ERROR,{code:m.code,msg:m.message}))}}},b.prototype._onSourceOpen=function(){if(_.default.v(this.TAG,"MediaSource onSourceOpen"),this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._pendingSourceBufferInit.length>0)for(var k=this._pendingSourceBufferInit;k.length;){var w=k.shift();this.appendInitSegment(w,!0)}this._hasPendingSegments()&&this._doAppendSegments(),this._emitter.emit(R.default.SOURCE_OPEN)},b.prototype._onStartStreaming=function(){_.default.v(this.TAG,"ManagedMediaSource onStartStreaming"),this._emitter.emit(R.default.START_STREAMING)},b.prototype._onEndStreaming=function(){_.default.v(this.TAG,"ManagedMediaSource onEndStreaming"),this._emitter.emit(R.default.END_STREAMING)},b.prototype._onQualityChange=function(){_.default.v(this.TAG,"ManagedMediaSource onQualityChange")},b.prototype._onSourceEnded=function(){_.default.v(this.TAG,"MediaSource onSourceEnded")},b.prototype._onSourceClose=function(){_.default.v(this.TAG,"MediaSource onSourceClose"),this._mediaSource&&this.e!=null&&(this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._mediaSource.removeEventListener("sourceended",this.e.onSourceEnded),this._mediaSource.removeEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(this._mediaSource.removeEventListener("startstreaming",this.e.onStartStreaming),this._mediaSource.removeEventListener("endstreaming",this.e.onEndStreaming),this._mediaSource.removeEventListener("qualitychange",this.e.onQualityChange)))},b.prototype._hasPendingSegments=function(){var k=this._pendingSegments;return k.video.length>0||k.audio.length>0},b.prototype._hasPendingRemoveRanges=function(){var k=this._pendingRemoveRanges;return k.video.length>0||k.audio.length>0},b.prototype._onSourceBufferUpdateEnd=function(){this._requireSetMediaDuration?this._updateMediaSourceDuration():this._hasPendingRemoveRanges()?this._doRemoveRanges():this._hasPendingSegments()?this._doAppendSegments():this._hasPendingEos&&this.endOfStream(),this._emitter.emit(R.default.UPDATE_END)},b.prototype._onSourceBufferError=function(k){_.default.e(this.TAG,"SourceBuffer Error: ".concat(k))},b}();Q.default=I},527:function(le,Q,D){D.r(Q);var X=D(7),P=D.n(X),_=D(861),S=D.n(_),R=D(856),v=D(947),I=D(886),b=D(726),k=(D(137),D(955)),w=function(){function O(A,G){if(this.TAG="Transmuxer",this._emitter=new(P()),G.enableWorker&&typeof Worker<"u")try{this._worker=S()(137),this._workerDestroying=!1,this._worker.addEventListener("message",this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:"init",param:[A,G]}),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this)},v.default.registerListener(this.e.onLoggingConfigChanged),this._worker.postMessage({cmd:"logging_config",param:v.default.getConfig()})}catch(U){R.default.e(this.TAG,"Error while initialize transmuxing worker, fallback to inline transmuxing"),this._worker=null,this._controller=new I.default(A,G)}else this._controller=new I.default(A,G);if(this._controller){var m=this._controller;m.on(b.default.IO_ERROR,this._onIOError.bind(this)),m.on(b.default.DEMUX_ERROR,this._onDemuxError.bind(this)),m.on(b.default.INIT_SEGMENT,this._onInitSegment.bind(this)),m.on(b.default.MEDIA_SEGMENT,this._onMediaSegment.bind(this)),m.on(b.default.LOADING_COMPLETE,this._onLoadingComplete.bind(this)),m.on(b.default.RECOVERED_EARLY_EOF,this._onRecoveredEarlyEof.bind(this)),m.on(b.default.MEDIA_INFO,this._onMediaInfo.bind(this)),m.on(b.default.METADATA_ARRIVED,this._onMetaDataArrived.bind(this)),m.on(b.default.SCRIPTDATA_ARRIVED,this._onScriptDataArrived.bind(this)),m.on(b.default.TIMED_ID3_METADATA_ARRIVED,this._onTimedID3MetadataArrived.bind(this)),m.on(b.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,this._onSynchronousKLVMetadataArrived.bind(this)),m.on(b.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,this._onAsynchronousKLVMetadataArrived.bind(this)),m.on(b.default.SMPTE2038_METADATA_ARRIVED,this._onSMPTE2038MetadataArrived.bind(this)),m.on(b.default.SEI_ARRIVED,this._onSEIArrived.bind(this)),m.on(b.default.SCTE35_METADATA_ARRIVED,this._onSCTE35MetadataArrived.bind(this)),m.on(b.default.PES_PRIVATE_DATA_DESCRIPTOR,this._onPESPrivateDataDescriptor.bind(this)),m.on(b.default.PES_PRIVATE_DATA_ARRIVED,this._onPESPrivateDataArrived.bind(this)),m.on(b.default.STATISTICS_INFO,this._onStatisticsInfo.bind(this)),m.on(b.default.RECOMMEND_SEEKPOINT,this._onRecommendSeekpoint.bind(this))}}return O.prototype.destroy=function(){this._worker?this._workerDestroying||(this._workerDestroying=!0,this._worker.postMessage({cmd:"destroy"}),v.default.removeListener(this.e.onLoggingConfigChanged),this.e=null):(this._controller.destroy(),this._controller=null),this._emitter.removeAllListeners(),this._emitter=null},O.prototype.on=function(A,G){this._emitter.addListener(A,G)},O.prototype.off=function(A,G){this._emitter.removeListener(A,G)},O.prototype.hasWorker=function(){return this._worker!=null},O.prototype.open=function(){this._worker?this._worker.postMessage({cmd:"start"}):this._controller.start()},O.prototype.close=function(){this._worker?this._worker.postMessage({cmd:"stop"}):this._controller.stop()},O.prototype.seek=function(A){this._worker?this._worker.postMessage({cmd:"seek",param:A}):this._controller.seek(A)},O.prototype.pause=function(){this._worker?this._worker.postMessage({cmd:"pause"}):this._controller.pause()},O.prototype.resume=function(){this._worker?this._worker.postMessage({cmd:"resume"}):this._controller.resume()},O.prototype._onInitSegment=function(A,G){var m=this;Promise.resolve().then(function(){m._emitter.emit(b.default.INIT_SEGMENT,A,G)})},O.prototype._onMediaSegment=function(A,G){var m=this;Promise.resolve().then(function(){m._emitter.emit(b.default.MEDIA_SEGMENT,A,G)})},O.prototype._onLoadingComplete=function(){var A=this;Promise.resolve().then(function(){A._emitter.emit(b.default.LOADING_COMPLETE)})},O.prototype._onRecoveredEarlyEof=function(){var A=this;Promise.resolve().then(function(){A._emitter.emit(b.default.RECOVERED_EARLY_EOF)})},O.prototype._onMediaInfo=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.MEDIA_INFO,A)})},O.prototype._onMetaDataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.METADATA_ARRIVED,A)})},O.prototype._onScriptDataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SCRIPTDATA_ARRIVED,A)})},O.prototype._onTimedID3MetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.TIMED_ID3_METADATA_ARRIVED,A)})},O.prototype._onPGSSubtitleArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.PGS_SUBTITLE_ARRIVED,A)})},O.prototype._onSynchronousKLVMetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,A)})},O.prototype._onAsynchronousKLVMetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,A)})},O.prototype._onSMPTE2038MetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SMPTE2038_METADATA_ARRIVED,A)})},O.prototype._onSEIArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SEI_ARRIVED,A)})},O.prototype._onSCTE35MetadataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.SCTE35_METADATA_ARRIVED,A)})},O.prototype._onPESPrivateDataDescriptor=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.PES_PRIVATE_DATA_DESCRIPTOR,A)})},O.prototype._onPESPrivateDataArrived=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.PES_PRIVATE_DATA_ARRIVED,A)})},O.prototype._onStatisticsInfo=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.STATISTICS_INFO,A)})},O.prototype._onIOError=function(A,G){var m=this;Promise.resolve().then(function(){m._emitter.emit(b.default.IO_ERROR,A,G)})},O.prototype._onDemuxError=function(A,G){var m=this;Promise.resolve().then(function(){m._emitter.emit(b.default.DEMUX_ERROR,A,G)})},O.prototype._onRecommendSeekpoint=function(A){var G=this;Promise.resolve().then(function(){G._emitter.emit(b.default.RECOMMEND_SEEKPOINT,A)})},O.prototype._onLoggingConfigChanged=function(A){this._worker&&this._worker.postMessage({cmd:"logging_config",param:A})},O.prototype._onWorkerMessage=function(A){var G=A.data,m=G.data;if(G.msg==="destroyed"||this._workerDestroying)return this._workerDestroying=!1,this._worker.terminate(),void(this._worker=null);switch(G.msg){case b.default.INIT_SEGMENT:case b.default.MEDIA_SEGMENT:this._emitter.emit(G.msg,m.type,m.data);break;case b.default.LOADING_COMPLETE:case b.default.RECOVERED_EARLY_EOF:this._emitter.emit(G.msg);break;case b.default.MEDIA_INFO:Object.setPrototypeOf(m,k.default.prototype),this._emitter.emit(G.msg,m);break;case b.default.METADATA_ARRIVED:case b.default.SCRIPTDATA_ARRIVED:case b.default.TIMED_ID3_METADATA_ARRIVED:case b.default.PGS_SUBTITLE_ARRIVED:case b.default.SYNCHRONOUS_KLV_METADATA_ARRIVED:case b.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED:case b.default.SMPTE2038_METADATA_ARRIVED:case b.default.SCTE35_METADATA_ARRIVED:case b.default.SEI_ARRIVED:case b.default.PES_PRIVATE_DATA_DESCRIPTOR:case b.default.PES_PRIVATE_DATA_ARRIVED:case b.default.STATISTICS_INFO:this._emitter.emit(G.msg,m);break;case b.default.IO_ERROR:case b.default.DEMUX_ERROR:this._emitter.emit(G.msg,m.type,m.info);break;case b.default.RECOMMEND_SEEKPOINT:this._emitter.emit(G.msg,m);break;case"logcat_callback":R.default.emitter.emit("log",m.type,m.logcat)}},O}();Q.default=w},886:function(le,Q,D){D.r(Q),D.d(Q,{default:function(){return li}});var X=D(7),P=D.n(X),_=D(856),S=D(994),R=D(955);function v(n,i,t){var e=n;if(i+t=128){i.push(String.fromCharCode(65535&o)),e+=2;continue}}else if(t[e]<240){if(v(t,e,2)&&(o=(15&t[e])<<12|(63&t[e+1])<<6|63&t[e+2])>=2048&&(63488&o)!=55296){i.push(String.fromCharCode(65535&o)),e+=3;continue}}else if(t[e]<248){var o;if(v(t,e,3)&&(o=(7&t[e])<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])>65536&&o<1114112){o-=65536,i.push(String.fromCharCode(o>>>10|55296)),i.push(String.fromCharCode(1023&o|56320)),e+=4;continue}}i.push(String.fromCharCode(65533)),++e}return i.join("")},k=D(867),w=(I=new ArrayBuffer(2),new DataView(I).setInt16(0,256,!0),new Int16Array(I)[0]===256),O=function(){function n(){}return n.parseScriptData=function(i,t,e){var a={};try{var o=n.parseValue(i,t,e),r=n.parseValue(i,t+o.size,e-o.size);a[o.data]=r.data}catch(s){_.default.e("AMF",s.toString())}return a},n.parseObject=function(i,t,e){if(e<3)throw new k.IllegalStateException("Data not enough when parse ScriptDataObject");var a=n.parseString(i,t,e),o=n.parseValue(i,t+a.size,e-a.size),r=o.objectEnd;return{data:{name:a.data,value:o.data},size:a.size+o.size,objectEnd:r}},n.parseVariable=function(i,t,e){return n.parseObject(i,t,e)},n.parseString=function(i,t,e){if(e<2)throw new k.IllegalStateException("Data not enough when parse String");var a=new DataView(i,t,e).getUint16(0,!w);return{data:a>0?b(new Uint8Array(i,t+2,a)):"",size:2+a}},n.parseLongString=function(i,t,e){if(e<4)throw new k.IllegalStateException("Data not enough when parse LongString");var a=new DataView(i,t,e).getUint32(0,!w);return{data:a>0?b(new Uint8Array(i,t+4,a)):"",size:4+a}},n.parseDate=function(i,t,e){if(e<10)throw new k.IllegalStateException("Data size invalid when parse Date");var a=new DataView(i,t,e),o=a.getFloat64(0,!w),r=a.getInt16(8,!w);return{data:new Date(o+=60*r*1000),size:10}},n.parseValue=function(i,t,e){if(e<1)throw new k.IllegalStateException("Data not enough when parse Value");var a,o=new DataView(i,t,e),r=1,s=o.getUint8(0),d=!1;try{switch(s){case 0:a=o.getFloat64(1,!w),r+=8;break;case 1:a=!!o.getUint8(1),r+=1;break;case 2:var l=n.parseString(i,t+1,e-1);a=l.data,r+=l.size;break;case 3:a={};var y=0;for((16777215&o.getUint32(e-4,!w))==9&&(y=3);r32)throw new k.InvalidArgumentException("ExpGolomb: readBits() bits exceeded max 32bits!");if(i<=this._current_word_bits_left){var t=this._current_word>>>32-i;return this._current_word<<=i,this._current_word_bits_left-=i,t}var e=this._current_word_bits_left?this._current_word:0;e>>>=32-this._current_word_bits_left;var a=i-this._current_word_bits_left;this._fillCurrentWord();var o=Math.min(a,this._current_word_bits_left),r=this._current_word>>>32-o;return this._current_word<<=o,this._current_word_bits_left-=o,e<>>i)return this._current_word<<=i,this._current_word_bits_left-=i,i;return this._fillCurrentWord(),i+this._skipLeadingZero()},n.prototype.readUEG=function(){var i=this._skipLeadingZero();return this.readBits(i+1)-1},n.prototype.readSEG=function(){var i=this.readUEG();return 1&i?i+1>>>1:-1*(i>>>1)},n}(),G=function(){function n(){}return n._ebsp2rbsp=function(i){for(var t=i,e=t.byteLength,a=new Uint8Array(e),o=0,r=0;r=2&&t[r]===3&&t[r-1]===0&&t[r-2]===0||(a[o]=t[r],o++);return new Uint8Array(a.buffer,0,o)},n.parseSPS=function(i){for(var t=i.subarray(1,4),e="avc1.",a=0;a<3;a++){var o=t[a].toString(16);o.length<2&&(o="0"+o),e+=o}var r=n._ebsp2rbsp(i),s=new A(r);s.readByte();var d=s.readByte();s.readByte();var l=s.readByte();s.readUEG();var y=n.getProfileString(d),f=n.getLevelString(l),g=1,T=420,B=8,F=8;if((d===100||d===110||d===122||d===244||d===44||d===83||d===86||d===118||d===128||d===138||d===144)&&((g=s.readUEG())===3&&s.readBits(1),g<=3&&(T=[0,420,422,444][g]),B=s.readUEG()+8,F=s.readUEG()+8,s.readBits(1),s.readBool()))for(var q=g!==3?8:12,Z=0;Z0&&ye<16?(Ce=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ye-1],we=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ye-1]):ye===255&&(Ce=s.readByte()<<8|s.readByte(),we=s.readByte()<<8|s.readByte())}if(s.readBool()&&s.readBool(),s.readBool()&&(s.readBits(4),s.readBool()&&s.readBits(24)),s.readBool()&&(s.readUEG(),s.readUEG()),s.readBool()){var Oe=s.readBits(32),Ve=s.readBits(32);pe=s.readBool(),Te=(be=Ve)/(Be=2*Oe)}}var xe=1;Ce===1&&we===1||(xe=Ce/we);var Ge=0,Le=0;g===0?(Ge=1,Le=2-ae):(Ge=g===3?1:2,Le=(g===1?2:1)*(2-ae));var He=16*(ve+1),qe=16*(ne+1)*(2-ae);He-=(ge+ce)*Ge,qe-=(De+Se)*Le;var tt=Math.ceil(He*xe);return s.destroy(),s=null,{codec_mimetype:e,profile_idc:d,level_idc:l,profile_string:y,level_string:f,chroma_format_idc:g,bit_depth:B,bit_depth_luma:B,bit_depth_chroma:F,ref_frames:he,chroma_format:T,chroma_format_string:n.getChromaFormatString(T),frame_rate:{fixed:pe,fps:Te,fps_den:Be,fps_num:be},sar_ratio:{width:Ce,height:we},codec_size:{width:He,height:qe},present_size:{width:tt,height:qe}}},n._skipScalingList=function(i,t){for(var e=8,a=8,o=0;o=2&&t[r]===3&&t[r-1]===0&&t[r-2]===0||(a[o]=t[r],o++);return new Uint8Array(a.buffer,0,o)},n.parseVPS=function(i){var t=n._ebsp2rbsp(i),e=new A(t);return e.readByte(),e.readByte(),e.readBits(4),e.readBits(2),e.readBits(6),{num_temporal_layers:e.readBits(3)+1,temporal_id_nested:e.readBool()}},n.parseSPS=function(i){var t=n._ebsp2rbsp(i),e=new A(t);e.readByte(),e.readByte();for(var a=0,o=0,r=0,s=0,d=(e.readBits(4),e.readBits(3)),l=(e.readBool(),e.readBits(2)),y=e.readBool(),f=e.readBits(5),g=e.readByte(),T=e.readByte(),B=e.readByte(),F=e.readByte(),q=e.readByte(),Z=e.readByte(),N=e.readByte(),H=e.readByte(),he=e.readByte(),ve=e.readByte(),ne=e.readByte(),ae=[],ge=[],ce=0;ce0)for(ce=d;ce<8;ce++)e.readBits(2);for(ce=0;ce1&&e.readSEG(),ce=0;ce0&&Ze<=16?($e=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][Ze-1],Je=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][Ze-1]):Ze===255&&($e=e.readBits(16),Je=e.readBits(16))}if(e.readBool()&&e.readBool(),e.readBool()&&(e.readBits(3),e.readBool(),e.readBool()&&(e.readByte(),e.readByte(),e.readByte())),e.readBool()&&(e.readUEG(),e.readUEG()),e.readBool(),e.readBool(),e.readBool(),e.readBool()&&(e.readUEG(),e.readUEG(),e.readUEG(),e.readUEG()),e.readBool()&&(at=e.readBits(32),rt=e.readBits(32),e.readBool()&&e.readUEG(),e.readBool())){var ot,st,it=!1;for(ot=e.readBool(),st=e.readBool(),(ot||st)&&((it=e.readBool())&&(e.readByte(),e.readBits(5),e.readBool(),e.readBits(5)),e.readBits(4),e.readBits(4),it&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)),ce=0;ce<=d;ce++){var bt=e.readBool();Et=bt;var At=!0,dt=1;bt||(At=e.readBool());var Rt=!1;if(At?e.readUEG():Rt=e.readBool(),Rt||(dt=e.readUEG()+1),ot){for(Le=0;Le>3),r=!!(4&i[e]),s=!!(2&i[e]);i[e],e+=1,r&&(e+=1);var d=Number.POSITIVE_INFINITY;if(s){d=0;for(var l=0;;l++){var y=i[e++];if(d|=(127&y)<<7*l,!(128&y))break}}console.log(o),o===1?t=h(h({},n.parseSeuqneceHeader(i.subarray(e,e+d))),{sequence_header_data:i.subarray(a,e+d)}):(o==3&&t||o==6&&t)&&(t=n.parseOBUFrameHeader(i.subarray(e,e+d),0,0,t)),e+=d}return t},n.parseSeuqneceHeader=function(i){var t=new A(i),e=t.readBits(3),a=(t.readBool(),t.readBool()),o=!0,r=0,s=1,d=void 0,l=[];if(a)l.push({operating_point_idc:0,level:t.readBits(5),tier:0});else{if(t.readBool()){var y=t.readBits(32),f=t.readBits(32),g=t.readBool();if(g){for(var T=0;t.readBits(1)===0;)T+=1;T>=32||t.readBits(T)}r=f,s=y,o=g,t.readBool()&&(t.readBits(5),t.readBits(32),d=t.readBits(5),t.readBits(5))}for(var B=t.readBool(),F=t.readBits(5),q=0;q<=F;q++){var Z=t.readBits(12),N=t.readBits(5),H=N>7?t.readBits(1):0;l.push({operating_point_idc:Z,level:N,tier:H}),B&&t.readBool()&&t.readBits(4)}}var he=l[0],ve=he.level,ne=he.tier,ae=t.readBits(4),ge=t.readBits(4),ce=t.readBits(ae+1)+1,De=t.readBits(ge+1)+1,Se=!1;a||(Se=t.readBool()),Se&&(t.readBits(4),t.readBits(4)),t.readBool(),t.readBool(),t.readBool();var Ce=!1,we=2,Te=2,pe=0;a||(t.readBool(),t.readBool(),t.readBool(),t.readBool(),(Ce=t.readBool())&&(t.readBool(),t.readBool()),Te=(we=t.readBool()?2:t.readBits(1))?t.readBool()?2:t.readBits(1):2,pe=Ce?t.readBits(3)+1:0);var be=t.readBool(),Be=(t.readBool(),t.readBool(),t.readBool()),ye=8;ye=e===2&&Be?t.readBool()?12:10:Be?10:8;var Oe=!1;e!==1&&(Oe=t.readBool()),t.readBool()&&(t.readBits(8),t.readBits(8),t.readBits(8));var Ve=1,xe=1;return Oe?(t.readBits(1),Ve=1,xe=1):(t.readBits(1),e==0?(Ve=1,xe=1):e==1?(Ve=0,xe=0):ye==12?t.readBits(1)&&t.readBits(1):(Ve=1,xe=0),Ve&&xe&&t.readBits(2),t.readBits(1)),t.readBool(),t.destroy(),t=null,{codec_mimetype:"av01.".concat(e,".").concat(n.getLevelString(ve,ne),".").concat(ye.toString(10).padStart(2,"0")),level:ve,tier:ne,level_string:n.getLevelString(ve,ne),profile_idc:e,profile_string:"".concat(e),bit_depth:ye,ref_frames:1,chroma_format:n.getChromaFormat(Oe,Ve,xe),chroma_format_string:n.getChromaFormatString(Oe,Ve,xe),sequence_header:{frame_id_numbers_present_flag:Se,additional_frame_id_length_minus_1:void 0,delta_frame_id_length_minus_2:void 0,reduced_still_picture_header:a,decoder_model_info_present_flag:!1,operating_points:l,buffer_removal_time_length_minus_1:d,equal_picture_interval:o,seq_force_screen_content_tools:we,seq_force_integer_mv:Te,enable_order_hint:Ce,order_hint_bits:pe,enable_superres:be,frame_width_bit:ae+1,frame_height_bit:ge+1,max_frame_width:ce,max_frame_height:De},keyframe:void 0,frame_rate:{fixed:o,fps:r/s,fps_den:s,fps_num:r}}},n.parseOBUFrameHeader=function(i,t,e,a){var o=a.sequence_header,r=new A(i),s=(o.max_frame_width,o.max_frame_height,0);o.frame_id_numbers_present_flag&&(s=o.additional_frame_id_length_minus_1+o.delta_frame_id_length_minus_2+3);var d=0,l=!0,y=!0,f=!1;if(!o.reduced_still_picture_header){if(r.readBool())return a;l=(d=r.readBits(2))===2||d===0,(y=r.readBool())&&o.decoder_model_info_present_flag&&o.equal_picture_interval,y&&r.readBool(),f=!!(d===3||d===0&&y)||r.readBool()}a.keyframe=l,r.readBool();var g=o.seq_force_screen_content_tools;o.seq_force_screen_content_tools===2&&(g=r.readBits(1)),g&&(o.seq_force_integer_mv,o.seq_force_integer_mv==2&&r.readBits(1)),o.frame_id_numbers_present_flag&&r.readBits(s);var T;if(T=d==3||!o.reduced_still_picture_header&&r.readBool(),r.readBits(o.order_hint_bits),l||f||r.readBits(3),o.decoder_model_info_present_flag&&r.readBool()){for(var B=0;B<=o.operating_points_cnt_minus_1;B++)if(o.operating_points[B].decoder_model_present_for_this_op[B]){var F=o.operating_points[B].operating_point_idc;(F===0||F>>t&1&&F>>e+8&1)&&r.readBits(o.buffer_removal_time_length_minus_1+1)}}var q=255;if(d===3||d==0&&y||(q=r.readBits(8)),(l||q!==255)&&f&&o.enable_order_hint)for(var Z=0;Z<8;Z++)r.readBits(o.order_hint_bits);if(l){var N=n.frameSizeAndRenderSize(r,T,o);a.codec_size={width:N.FrameWidth,height:N.FrameHeight},a.present_size={width:N.RenderWidth,height:N.RenderHeight},a.sar_ratio={width:N.RenderWidth/N.FrameWidth,height:N.RenderHeight/N.FrameHeight}}return r.destroy(),r=null,a},n.frameSizeAndRenderSize=function(i,t,e){var{max_frame_width:a,max_frame_height:o}=e;t&&(a=i.readBits(e.frame_width_bit)+1,o=i.readBits(e.frame_height_bit)+1);var r=!1;e.enable_superres&&(r=i.readBool());var s=8;r&&(s=i.readBits(3)+9);var d=a;a=Math.floor((8*d+s/2)/s);var l=d,y=o;if(i.readBool()){var f=i.readBits(16)+1,g=i.readBits(16)+1;l=i.readBits(f)+1,y=i.readBits(g)+1}return{UpscaledWidth:d,FrameWidth:a,FrameHeight:o,RenderWidth:l,RenderHeight:y}},n.getLevelString=function(i,t){return"".concat(i.toString(10).padStart(2,"0")).concat(t===0?"M":"H")},n.getChromaFormat=function(i,t,e){return i?0:t===0&&e===0?3:t===1&&e===0?2:t===1&&e===1?1:Number.NaN},n.getChromaFormatString=function(i,t,e){return i?"4:0:0":t===0&&e===0?"4:4:4":t===1&&e===0?"4:2:2":t===1&&e===1?"4:2:0":"Unknown"},n}(),E=function(){};function W(n,i,t){if(!n||n.byteLength<2)return null;var e=1;t==="h265"&&(e=2);var a=function(y){for(var f=y,g=f.byteLength,T=new Uint8Array(g),B=0,F=0;F=2&&f[F]===3&&f[F-1]===0&&f[F-2]===0||(T[B]=f[F],B++);return new Uint8Array(T.buffer,0,B)}(n.subarray(e)),o=0;if(o===a.byteLength-1&&a[o]===128)return null;for(var r=0;o=a.byteLength)return null;r+=a[o++];for(var s=0;o=a.byteLength)return null;if(s+=a[o++],o+s>a.byteLength)return null;var d=new E;d.type=r,d.size=s;var l=a.subarray(o,o+s);return r===5&&s>=16&&(d.uuid=l.subarray(0,16),d.user_data=l.subarray(16)),i!==void 0&&(d.pts=i),d}var z,se=function(){function n(i,t){this.TAG="FLVDemuxer",this._config=t,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._onSeiArrived=null,this._dataOffset=i.dataOffset,this._firstParse=!0,this._dispatch=!1,this._hasAudio=i.hasAudioTrack,this._hasVideo=i.hasVideoTrack,this._hasAudioFlagOverrided=!1,this._hasVideoFlagOverrided=!1,this._audioInitialMetadataDispatched=!1,this._videoInitialMetadataDispatched=!1,this._mediaInfo=new R.default,this._mediaInfo.hasAudio=this._hasAudio,this._mediaInfo.hasVideo=this._hasVideo,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._naluLengthSize=4,this._timestampBase=0,this._timescale=1000,this._duration=0,this._durationOverrided=!1,this._referenceFrameRate={fixed:!0,fps:23.976,fps_num:23976,fps_den:1000},this._flvSoundRateTable=[5500,11025,22050,44100,48000],this._mpegSamplingRates=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],this._mpegAudioV10SampleRateTable=[44100,48000,32000,0],this._mpegAudioV20SampleRateTable=[22050,24000,16000,0],this._mpegAudioV25SampleRateTable=[11025,12000,8000,0],this._mpegAudioL1BitRateTable=[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1],this._mpegAudioL2BitRateTable=[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],this._mpegAudioL3BitRateTable=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],this._videoTrack={type:"video",id:1,sequenceNumber:0,samples:[],length:0},this._audioTrack={type:"audio",id:2,sequenceNumber:0,samples:[],length:0},this._littleEndian=function(){var e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]===256}()}return n.prototype.destroy=function(){this._mediaInfo=null,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._videoTrack=null,this._audioTrack=null,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._onSeiArrived=null},n.probe=function(i){var t=new Uint8Array(i);if(t.byteLength<9)return{needMoreData:!0};var e={match:!1};if(t[0]!==70||t[1]!==76||t[2]!==86||t[3]!==1)return e;var a,o=(4&t[4])>>>2!=0,r=!!(1&t[4]),s=(a=t)[5]<<24|a[6]<<16|a[7]<<8|a[8];return s<9?e:{match:!0,consumed:s,dataOffset:s,hasAudioTrack:o,hasVideoTrack:r}},n.prototype.bindDataSource=function(i){return i.onDataArrival=this.parseChunks.bind(this),this},Object.defineProperty(n.prototype,"onTrackMetadata",{get:function(){return this._onTrackMetadata},set:function(i){this._onTrackMetadata=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onMediaInfo",{get:function(){return this._onMediaInfo},set:function(i){this._onMediaInfo=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onMetaDataArrived",{get:function(){return this._onMetaDataArrived},set:function(i){this._onMetaDataArrived=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onScriptDataArrived",{get:function(){return this._onScriptDataArrived},set:function(i){this._onScriptDataArrived=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onSeiArrived",{get:function(){return this._onSeiArrived},set:function(i){this._onSeiArrived=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onError",{get:function(){return this._onError},set:function(i){this._onError=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onDataAvailable",{get:function(){return this._onDataAvailable},set:function(i){this._onDataAvailable=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"timestampBase",{get:function(){return this._timestampBase},set:function(i){this._timestampBase=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"overridedDuration",{get:function(){return this._duration},set:function(i){this._durationOverrided=!0,this._duration=i,this._mediaInfo.duration=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"overridedHasAudio",{set:function(i){this._hasAudioFlagOverrided=!0,this._hasAudio=i,this._mediaInfo.hasAudio=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"overridedHasVideo",{set:function(i){this._hasVideoFlagOverrided=!0,this._hasVideo=i,this._mediaInfo.hasVideo=i},enumerable:!1,configurable:!0}),n.prototype.resetMediaInfo=function(){this._mediaInfo=new R.default},n.prototype._isInitialMetadataDispatched=function(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!(this._hasAudio||!this._hasVideo)&&this._videoInitialMetadataDispatched},n.prototype.parseChunks=function(i,t){if(!(this._onError&&this._onMediaInfo&&this._onTrackMetadata&&this._onDataAvailable))throw new k.IllegalStateException("Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var e=0,a=this._littleEndian;if(t===0){if(!(i.byteLength>13))return 0;e=n.probe(i).dataOffset}for(this._firstParse&&(this._firstParse=!1,t+e!==this._dataOffset&&_.default.w(this.TAG,"First time parsing but chunk byteStart invalid!"),(o=new DataView(i,e)).getUint32(0,!a)!==0&&_.default.w(this.TAG,"PrevTagSize0 !== 0 !!!"),e+=4);ei.byteLength)break;var r=o.getUint8(0),s=16777215&o.getUint32(0,!a);if(e+11+s+4>i.byteLength)break;if(r===8||r===9||r===18){var d=o.getUint8(4),l=o.getUint8(5),y=o.getUint8(6)|l<<8|d<<16|o.getUint8(7)<<24;16777215&o.getUint32(7,!a)&&_.default.w(this.TAG,"Meet tag which has StreamID != 0!");var f=e+11;switch(r){case 8:this._parseAudioData(i,f,s,y);break;case 9:this._parseVideoData(i,f,s,y,t+e);break;case 18:this._parseScriptData(i,f,s)}var g=o.getUint32(11+s,!a);g!==11+s&&_.default.w(this.TAG,"Invalid PrevTagSize ".concat(g)),e+=11+s+4}else _.default.w(this.TAG,"Unsupported tag type ".concat(r,", skipped")),e+=11+s+4}return this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack),e},n.prototype._parseScriptData=function(i,t,e){var a=O.parseScriptData(i,t,e);if(a.hasOwnProperty("onMetaData")){if(a.onMetaData==null||typeof a.onMetaData!="object")return void _.default.w(this.TAG,"Invalid onMetaData structure!");this._metadata&&_.default.w(this.TAG,"Found another onMetaData tag!"),this._metadata=a;var o=this._metadata.onMetaData;if(this._onMetaDataArrived&&this._onMetaDataArrived(Object.assign({},o)),typeof o.hasAudio=="boolean"&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=o.hasAudio,this._mediaInfo.hasAudio=this._hasAudio),typeof o.hasVideo=="boolean"&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=o.hasVideo,this._mediaInfo.hasVideo=this._hasVideo),typeof o.audiodatarate=="number"&&(this._mediaInfo.audioDataRate=o.audiodatarate),typeof o.videodatarate=="number"&&(this._mediaInfo.videoDataRate=o.videodatarate),typeof o.width=="number"&&(this._mediaInfo.width=o.width),typeof o.height=="number"&&(this._mediaInfo.height=o.height),typeof o.duration=="number"){if(!this._durationOverrided){var r=Math.floor(o.duration*this._timescale);this._duration=r,this._mediaInfo.duration=r}}else this._mediaInfo.duration=0;if(typeof o.framerate=="number"){var s=Math.floor(1000*o.framerate);if(s>0){var d=s/1000;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=d,this._referenceFrameRate.fps_num=s,this._referenceFrameRate.fps_den=1000,this._mediaInfo.fps=d}}if(typeof o.keyframes=="object"){this._mediaInfo.hasKeyframesIndex=!0;var l=o.keyframes;this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(l),o.keyframes=null}else this._mediaInfo.hasKeyframesIndex=!1;this._dispatch=!1,this._mediaInfo.metadata=o,_.default.v(this.TAG,"Parsed onMetaData"),this._mediaInfo.isComplete()&&this._onMediaInfo(this._mediaInfo)}Object.keys(a).length>0&&this._onScriptDataArrived&&this._onScriptDataArrived(Object.assign({},a))},n.prototype._parseSEIPayload=function(i,t,e){var a=W(i,t,e);a&&typeof this._onSeiArrived=="function"&&this._onSeiArrived(a)},n.prototype._parseKeyframesIndex=function(i){for(var t=[],e=[],a=1;a>>4;if(r!==9)if(r===2||r===3||r===10){var s=0,d=(12&o)>>>2;if(d>=0&&d<=4){s=this._flvSoundRateTable[d];var l=(2&o)>>>1,y=1&o,f=this._audioMetadata,g=this._audioTrack;if(f||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(f=this._audioMetadata={}).type="audio",f.id=g.id,f.timescale=this._timescale,f.duration=this._duration,f.audioSampleRate=s,f.channelCount=y===0?1:2),r===10){var T=this._parseAACAudioData(i,t+1,e-1);if(T==null)return;if(T.packetType===0){if(f.config){if(u(T.data.config,f.config))return;_.default.w(this.TAG,"AudioSpecificConfig has been changed, re-generate initialization segment")}var B=T.data;f.audioSampleRate=B.samplingRate,f.channelCount=B.channelCount,f.codec=B.codec,f.originalCodec=B.originalCodec,f.config=B.config,f.refSampleDuration=1024/f.audioSampleRate*f.timescale,_.default.v(this.TAG,"Parsed AudioSpecificConfig"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",f),(N=this._mediaInfo).audioCodec=f.originalCodec,N.audioSampleRate=f.audioSampleRate,N.audioChannelCount=f.channelCount,N.hasVideo?N.videoCodec!=null&&(N.mimeType='video/x-flv; codecs="'+N.videoCodec+","+N.audioCodec+'"'):N.mimeType='video/x-flv; codecs="'+N.audioCodec+'"',N.isComplete()&&this._onMediaInfo(N)}else if(T.packetType===1){var F=this._timestampBase+a,q={unit:T.data,length:T.data.byteLength,dts:F,pts:F};g.samples.push(q),g.length+=T.data.length}else _.default.e(this.TAG,"Flv: Unsupported AAC data type ".concat(T.packetType))}else if(r===2){if(!f.codec){if((B=this._parseMP3AudioData(i,t+1,e-1,!0))==null)return;f.audioSampleRate=B.samplingRate,f.channelCount=B.channelCount,f.codec=B.codec,f.originalCodec=B.originalCodec,f.refSampleDuration=1152/f.audioSampleRate*f.timescale,_.default.v(this.TAG,"Parsed MPEG Audio Frame Header"),this._audioInitialMetadataDispatched=!0,this._onTrackMetadata("audio",f),(N=this._mediaInfo).audioCodec=f.codec,N.audioSampleRate=f.audioSampleRate,N.audioChannelCount=f.channelCount,N.audioDataRate=B.bitRate,N.hasVideo?N.videoCodec!=null&&(N.mimeType='video/x-flv; codecs="'+N.videoCodec+","+N.audioCodec+'"'):N.mimeType='video/x-flv; codecs="'+N.audioCodec+'"',N.isComplete()&&this._onMediaInfo(N)}if((H=this._parseMP3AudioData(i,t+1,e-1,!1))==null)return;F=this._timestampBase+a;var Z={unit:H,length:H.byteLength,dts:F,pts:F};g.samples.push(Z),g.length+=H.length}else if(r===3){var N;f.codec||(f.audioSampleRate=s,f.sampleSize=8*(l+1),f.littleEndian=!0,f.codec="ipcm",f.originalCodec="ipcm",this._audioInitialMetadataDispatched=!0,this._onTrackMetadata("audio",f),(N=this._mediaInfo).audioCodec=f.codec,N.audioSampleRate=f.audioSampleRate,N.audioChannelCount=f.channelCount,N.audioDataRate=f.sampleSize*f.audioSampleRate,N.hasVideo?N.videoCodec!=null&&(N.mimeType='video/x-flv; codecs="'+N.videoCodec+","+N.audioCodec+'"'):N.mimeType='video/x-flv; codecs="'+N.audioCodec+'"',N.isComplete()&&this._onMediaInfo(N));var H=new Uint8Array(i,t+1,e-1),he=(F=this._timestampBase+a,{unit:H,length:H.byteLength,dts:F,pts:F});g.samples.push(he),g.length+=H.length}}else this._onError(m.default.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+d)}else this._onError(m.default.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+r);else{if(e<=5)return void _.default.w(this.TAG,"Flv: Invalid audio packet, missing AudioFourCC in Ehnanced FLV payload!");var ve=15&o,ne=String.fromCharCode.apply(String,new Uint8Array(i,t,e).slice(1,5));switch(ne){case"Opus":this._parseOpusAudioPacket(i,t+5,e-5,a,ve);break;case"fLaC":this._parseFlacAudioPacket(i,t+5,e-5,a,ve);break;default:this._onError(m.default.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec: "+ne)}}}},n.prototype._parseAACAudioData=function(i,t,e){if(!(e<=1)){var a={},o=new Uint8Array(i,t,e);return a.packetType=o[0],o[0]===0?a.data=this._parseAACAudioSpecificConfig(i,t+1,e-1):a.data=o.subarray(1),a}_.default.w(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!")},n.prototype._parseAACAudioSpecificConfig=function(i,t,e){var a,o,r=new Uint8Array(i,t,e),s=null,d=0,l=null;if(d=a=r[0]>>>3,(o=(7&r[0])<<1|r[1]>>>7)<0||o>=this._mpegSamplingRates.length)this._onError(m.default.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var y=this._mpegSamplingRates[o],f=(120&r[1])>>>3;if(!(f<0||f>=8)){d===5&&(l=(7&r[1])<<1|r[2]>>>7,r[2]);var g=self.navigator.userAgent.toLowerCase();return g.indexOf("firefox")!==-1?o>=6?(d=5,s=[,,,,],l=o-3):(d=2,s=[,,],l=o):g.indexOf("android")!==-1?(d=2,s=[,,],l=o):(d=5,l=o,s=[,,,,],o>=6?l=o-3:f===1&&(d=2,s=[,,],l=o)),s[0]=d<<3,s[0]|=(15&o)>>>1,s[1]=(15&o)<<7,s[1]|=(15&f)<<3,d===5&&(s[1]|=(15&l)>>>1,s[2]=(1&l)<<7,s[2]|=8,s[3]=0),{config:s,samplingRate:y,channelCount:f,codec:"mp4a.40."+d,originalCodec:"mp4a.40."+a}}this._onError(m.default.FORMAT_ERROR,"Flv: AAC invalid channel configuration")}},n.prototype._parseMP3AudioData=function(i,t,e,a){if(!(e<4)){this._littleEndian;var o=new Uint8Array(i,t,e),r=null;if(a){if(o[0]!==255)return;var s=o[1]>>>3&3,d=(6&o[1])>>1,l=(240&o[2])>>>4,y=(12&o[2])>>>2,f=3&~(o[3]>>>6)?2:1,g=0,T=0;switch(s){case 0:g=this._mpegAudioV25SampleRateTable[y];break;case 2:g=this._mpegAudioV20SampleRateTable[y];break;case 3:g=this._mpegAudioV10SampleRateTable[y]}switch(d){case 1:l>>16&255,B[2]=r.byteLength>>>8&255,B[3]=r.byteLength>>>0&255;var F={config:B,channelCount:g,samplingFrequence:f,sampleSize:T,codec:"flac",originalCodec:"flac"};if(a.config){if(u(F.config,a.config))return;_.default.w(this.TAG,"FlacSequenceHeader has been changed, re-generate initialization segment")}a.audioSampleRate=F.samplingFrequence,a.channelCount=F.channelCount,a.sampleSize=F.sampleSize,a.codec=F.codec,a.originalCodec=F.originalCodec,a.config=F.config,a.refSampleDuration=y!=null?1000*y/F.samplingFrequence:null,_.default.v(this.TAG,"Parsed FlacSequenceHeader"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",a);var q=this._mediaInfo;q.audioCodec=a.originalCodec,q.audioSampleRate=a.audioSampleRate,q.audioChannelCount=a.channelCount,q.hasVideo?q.videoCodec!=null&&(q.mimeType='video/x-flv; codecs="'+q.videoCodec+","+q.audioCodec+'"'):q.mimeType='video/x-flv; codecs="'+q.audioCodec+'"',q.isComplete()&&this._onMediaInfo(q)},n.prototype._parseFlacAudioData=function(i,t,e,a){var o=this._audioTrack,r=new Uint8Array(i,t,e),s=this._timestampBase+a,d={unit:r,length:r.byteLength,dts:s,pts:s};o.samples.push(d),o.length+=r.length},n.prototype._parseVideoData=function(i,t,e,a,o){if(e<=1)_.default.w(this.TAG,"Flv: Invalid video packet, missing VideoData payload!");else if(this._hasVideoFlagOverrided!==!0||this._hasVideo!==!1){var r=new Uint8Array(i,t,e)[0],s=(112&r)>>>4;if(128&r){var d=15&r,l=String.fromCharCode.apply(String,new Uint8Array(i,t,e).slice(1,5));if(l==="hvc1")this._parseEnhancedHEVCVideoPacket(i,t+5,e-5,a,o,s,d);else{if(l!=="av01")return void this._onError(m.default.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(l));this._parseEnhancedAV1VideoPacket(i,t+5,e-5,a,o,s,d)}}else{var y=15&r;if(y===7)this._parseAVCVideoPacket(i,t+1,e-1,a,o,s);else{if(y!==12)return void this._onError(m.default.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(y));this._parseHEVCVideoPacket(i,t+1,e-1,a,o,s)}}}},n.prototype._parseAVCVideoPacket=function(i,t,e,a,o,r){if(e<4)_.default.w(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var s=this._littleEndian,d=new DataView(i,t,e),l=d.getUint8(0),y=(16777215&d.getUint32(0,!s))<<8>>8;if(l===0)this._parseAVCDecoderConfigurationRecord(i,t+4,e-4);else if(l===1)this._parseAVCVideoData(i,t+4,e-4,a,o,r,y);else if(l!==2)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(l))}},n.prototype._parseHEVCVideoPacket=function(i,t,e,a,o,r){if(e<4)_.default.w(this.TAG,"Flv: Invalid HEVC packet, missing HEVCPacketType or/and CompositionTime");else{var s=this._littleEndian,d=new DataView(i,t,e),l=d.getUint8(0),y=(16777215&d.getUint32(0,!s))<<8>>8;if(l===0)this._parseHEVCDecoderConfigurationRecord(i,t+4,e-4);else if(l===1)this._parseHEVCVideoData(i,t+4,e-4,a,o,r,y);else if(l!==2)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(l))}},n.prototype._parseEnhancedHEVCVideoPacket=function(i,t,e,a,o,r,s){var d=this._littleEndian,l=new DataView(i,t,e);if(s===0)this._parseHEVCDecoderConfigurationRecord(i,t,e);else if(s===1){var y=(4294967040&l.getUint32(0,!d))>>8;this._parseHEVCVideoData(i,t+3,e-3,a,o,r,y)}else if(s===3)this._parseHEVCVideoData(i,t,e,a,o,r,0);else if(s!==2)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(s))},n.prototype._parseEnhancedAV1VideoPacket=function(i,t,e,a,o,r,s){if(this._littleEndian,new DataView(i,t,e),s===0)this._parseAV1CodecConfigurationRecord(i,t,e);else if(s===1)this._parseAV1VideoData(i,t,e,a,o,r,0);else{if(s===5)return void this._onError(m.default.FORMAT_ERROR,"Flv: Not Supported MP2T AV1 video packet type ".concat(s));if(s!==2)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(s))}},n.prototype._parseAVCDecoderConfigurationRecord=function(i,t,e){if(e<7)_.default.w(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");else{var a=this._videoMetadata,o=this._videoTrack,r=this._littleEndian,s=new DataView(i,t,e);if(a){if(a.avcc!==void 0){var d=new Uint8Array(i,t,e);if(u(d,a.avcc))return;_.default.w(this.TAG,"AVCDecoderConfigurationRecord has been changed, re-generate initialization segment")}}else this._hasVideo===!1&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),(a=this._videoMetadata={}).type="video",a.id=o.id,a.timescale=this._timescale,a.duration=this._duration;var l=s.getUint8(0),y=s.getUint8(1);if(s.getUint8(2),s.getUint8(3),l===1&&y!==0)if(this._naluLengthSize=1+(3&s.getUint8(4)),this._naluLengthSize===3||this._naluLengthSize===4){var f=31&s.getUint8(5);if(f!==0){f>1&&_.default.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ".concat(f));for(var g=6,T=0;T1&&_.default.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ".concat(ge)),g++,T=0;T=e){_.default.w(this.TAG,"Malformed Nalu near timestamp ".concat(B,", offset = ").concat(g,", dataSize = ").concat(e));break}var q=l.getUint32(g,!d);if(T===3&&(q>>>=8),q>e-T)return void _.default.w(this.TAG,"Malformed Nalus near timestamp ".concat(B,", NaluSize > DataSize!"));var Z=31&l.getUint8(g+T);Z===5&&(F=!0);var N=new Uint8Array(i,t+g,T+q),H={type:Z,data:N};y.push(H),f+=N.byteLength,Z===6&&this._parseSEIPayload(N.subarray(T),B+s,"h264"),g+=T+q}if(y.length){var he=this._videoTrack,ve={units:y,length:f,isKeyframe:F,dts:B,cts:s,pts:B+s};F&&(ve.fileposition=o),he.samples.push(ve),he.length+=f}},n.prototype._parseHEVCVideoData=function(i,t,e,a,o,r,s){for(var d=this._littleEndian,l=new DataView(i,t,e),y=[],f=0,g=0,T=this._naluLengthSize,B=this._timestampBase+a,F=r===1;g=e){_.default.w(this.TAG,"Malformed Nalu near timestamp ".concat(B,", offset = ").concat(g,", dataSize = ").concat(e));break}var q=l.getUint32(g,!d);if(T===3&&(q>>>=8),q>e-T)return void _.default.w(this.TAG,"Malformed Nalus near timestamp ".concat(B,", NaluSize > DataSize!"));var Z=l.getUint8(g+T)>>1&63;Z!==19&&Z!==20&&Z!==21||(F=!0);var N=new Uint8Array(i,t+g,T+q),H={type:Z,data:N};y.push(H),f+=N.byteLength,Z!==39&&Z!==40||this._parseSEIPayload(N.subarray(T),B+s,"h265"),g+=T+q}if(y.length){var he=this._videoTrack,ve={units:y,length:f,isKeyframe:F,dts:B,cts:s,pts:B+s};F&&(ve.fileposition=o),he.samples.push(ve),he.length+=f}},n.prototype._parseAV1VideoData=function(i,t,e,a,o,r,s){this._littleEndian,new DataView(i,t,e);var d,l=[],y=this._timestampBase+a,f=r===1;if(f){var g=this._videoMetadata,T=p.parseOBUs(new Uint8Array(i,t,e),g.extra);if(T==null)return void this._onError(m.default.FORMAT_ERROR,"Flv: Invalid AV1 VideoData");console.log(T),g.codecWidth=T.codec_size.width,g.codecHeight=T.codec_size.height,g.presentWidth=T.present_size.width,g.presentHeight=T.present_size.height,g.sarRatio=T.sar_ratio;var B=this._mediaInfo;B.width=g.codecWidth,B.height=g.codecHeight,B.sarNum=g.sarRatio.width,B.sarDen=g.sarRatio.height,_.default.v(this.TAG,"Parsed AV1DecoderConfigurationRecord"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._videoInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("video",g)}if(d=e,l.push({unitType:0,data:new Uint8Array(i,t+0,e)}),l.length){var F=this._videoTrack,q={units:l,length:d,isKeyframe:f,dts:y,cts:s,pts:y+s};f&&(q.fileposition=o),F.samples.push(q),F.length+=d}},n}(),de=se,me=function(){function n(){}return n.prototype.destroy=function(){this.onError=null,this.onMediaInfo=null,this.onMetaDataArrived=null,this.onTrackMetadata=null,this.onDataAvailable=null,this.onTimedID3Metadata=null,this.onPGSSubtitleData=null,this.onSynchronousKLVMetadata=null,this.onAsynchronousKLVMetadata=null,this.onSMPTE2038Metadata=null,this.onSEI=null,this.onSCTE35Metadata=null,this.onPESPrivateData=null,this.onPESPrivateDataDescriptor=null},n}(),te=function(){this.program_pmt_pid={}};(function(n){n[n.kMPEG1Audio=3]="kMPEG1Audio",n[n.kMPEG2Audio=4]="kMPEG2Audio",n[n.kPESPrivateData=6]="kPESPrivateData",n[n.kADTSAAC=15]="kADTSAAC",n[n.kLOASAAC=17]="kLOASAAC",n[n.kAC3=129]="kAC3",n[n.kEAC3=135]="kEAC3",n[n.kMetadata=21]="kMetadata",n[n.kSCTE35=134]="kSCTE35",n[n.kPGS=144]="kPGS",n[n.kH264=27]="kH264",n[n.kH265=36]="kH265"})(z||(z={}));var ee,Re=function(){this.pid_stream_type={},this.common_pids={h264:void 0,h265:void 0,av1:void 0,adts_aac:void 0,loas_aac:void 0,opus:void 0,ac3:void 0,eac3:void 0,mp3:void 0},this.pes_private_data_pids={},this.timed_id3_pids={},this.pgs_pids={},this.pgs_langs={},this.synchronous_klv_pids={},this.asynchronous_klv_pids={},this.scte_35_pids={},this.smpte2038_pids={}},J=function(){},ke=function(){},L=function(){this.slices=[],this.total_length=0,this.expected_length=0,this.file_position=0};(function(n){n[n.kUnspecified=0]="kUnspecified",n[n.kSliceNonIDR=1]="kSliceNonIDR",n[n.kSliceDPA=2]="kSliceDPA",n[n.kSliceDPB=3]="kSliceDPB",n[n.kSliceDPC=4]="kSliceDPC",n[n.kSliceIDR=5]="kSliceIDR",n[n.kSliceSEI=6]="kSliceSEI",n[n.kSliceSPS=7]="kSliceSPS",n[n.kSlicePPS=8]="kSlicePPS",n[n.kSliceAUD=9]="kSliceAUD",n[n.kEndOfSequence=10]="kEndOfSequence",n[n.kEndOfStream=11]="kEndOfStream",n[n.kFiller=12]="kFiller",n[n.kSPSExt=13]="kSPSExt",n[n.kReserved0=14]="kReserved0"})(ee||(ee={}));var c,C,j=function(){},fe=function(n){var i=n.data.byteLength;this.type=n.type,this.data=new Uint8Array(4+i),new DataView(this.data.buffer).setUint32(0,i),this.data.set(n.data,4)},re=function(){function n(i){this.TAG="H264AnnexBParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=i,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not find H264 startcode until payload end!")}return n.prototype.findNextStartCodeOffset=function(i){for(var t=i,e=this.data_;;){if(t+3>=e.byteLength)return this.eof_flag_=!0,e.byteLength;var a=e[t+0]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],o=e[t+0]<<16|e[t+1]<<8|e[t+2];if(a===1||o===1)return t;t++}},n.prototype.readNextNaluPayload=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_startcode_offset_,a=31&i[e+=(i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3])==1?4:3],o=(128&i[e])>>>7,r=this.findNextStartCodeOffset(e);if(this.current_startcode_offset_=r,!(a>=ee.kReserved0)&&o===0){var s=i.subarray(e,r);(t=new j).type=a,t.data=s}}return t},n}(),V=function(){function n(i,t,e){var a=8+i.byteLength+1+2+t.byteLength,o=!1;i[3]!==66&&i[3]!==77&&i[3]!==88&&(o=!0,a+=4);var r=this.data=new Uint8Array(a);r[0]=1,r[1]=i[1],r[2]=i[2],r[3]=i[3],r[4]=255,r[5]=225;var s=i.byteLength;r[6]=s>>>8,r[7]=255&s;var d=8;r.set(i,8),r[d+=s]=1;var l=t.byteLength;r[d+1]=l>>>8,r[d+2]=255&l,r.set(t,d+3),d+=3+l,o&&(r[d]=252|e.chroma_format_idc,r[d+1]=248|e.bit_depth_luma-8,r[d+2]=248|e.bit_depth_chroma-8,r[d+3]=0,d+=4)}return n.prototype.getData=function(){return this.data},n}();(function(n){n[n.kNull=0]="kNull",n[n.kAACMain=1]="kAACMain",n[n.kAAC_LC=2]="kAAC_LC",n[n.kAAC_SSR=3]="kAAC_SSR",n[n.kAAC_LTP=4]="kAAC_LTP",n[n.kAAC_SBR=5]="kAAC_SBR",n[n.kAAC_Scalable=6]="kAAC_Scalable",n[n.kLayer1=32]="kLayer1",n[n.kLayer2=33]="kLayer2",n[n.kLayer3=34]="kLayer3"})(c||(c={})),function(n){n[n.k96000Hz=0]="k96000Hz",n[n.k88200Hz=1]="k88200Hz",n[n.k64000Hz=2]="k64000Hz",n[n.k48000Hz=3]="k48000Hz",n[n.k44100Hz=4]="k44100Hz",n[n.k32000Hz=5]="k32000Hz",n[n.k24000Hz=6]="k24000Hz",n[n.k22050Hz=7]="k22050Hz",n[n.k16000Hz=8]="k16000Hz",n[n.k12000Hz=9]="k12000Hz",n[n.k11025Hz=10]="k11025Hz",n[n.k8000Hz=11]="k8000Hz",n[n.k7350Hz=12]="k7350Hz"}(C||(C={}));var Y,ie,oe=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],ue=(Y=function(n,i){return Y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a])},Y(n,i)},function(n,i){if(typeof i!="function"&&i!==null)throw TypeError("Class extends value "+String(i)+" is not a constructor or null");function t(){this.constructor=n}Y(n,i),n.prototype=i===null?Object.create(i):(t.prototype=i.prototype,new t)}),Ee=function(){},Pe=function(n){function i(){return n!==null&&n.apply(this,arguments)||this}return ue(i,n),i}(Ee),Ue=function(){function n(i){this.TAG="AACADTSParser",this.data_=i,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not found ADTS syncword until payload end")}return n.prototype.findNextSyncwordOffset=function(i){for(var t=i,e=this.data_;;){if(t+7>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<8|e[t+1])>>>4==4095)return t;t++}},n.prototype.readNextAACFrame=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_syncword_offset_,a=(8&i[e+1])>>>3,o=(6&i[e+1])>>>1,r=1&i[e+1],s=(192&i[e+2])>>>6,d=(60&i[e+2])>>>2,l=(1&i[e+2])<<2|(192&i[e+3])>>>6,y=(3&i[e+3])<<11|i[e+4]<<3|(224&i[e+5])>>>5;if(i[e+6],e+y>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var f=r===1?7:9,g=y-f;e+=f;var T=this.findNextSyncwordOffset(e+g);if(this.current_syncword_offset_=T,(a===0||a===1)&&o===0){var B=i.subarray(e,e+g);(t=new Ee).audio_object_type=s+1,t.sampling_freq_index=d,t.sampling_frequency=oe[d],t.channel_config=l,t.data=B}}return t},n.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},n.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},n}(),je=function(){function n(i){this.TAG="AACLOASParser",this.data_=i,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not found LOAS syncword until payload end")}return n.prototype.findNextSyncwordOffset=function(i){for(var t=i,e=this.data_;;){if(t+1>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<3|e[t+1]>>>5)==695)return t;t++}},n.prototype.getLATMValue=function(i){for(var t=i.readBits(2),e=0,a=0;a<=t;a++)e<<=8,e|=i.readByte();return e},n.prototype.readNextAACFrame=function(i){for(var t=this.data_,e=null;e==null&&!this.eof_flag_;){var a=this.current_syncword_offset_,o=(31&t[a+1])<<8|t[a+2];if(a+3+o>=this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var r=new A(t.subarray(a+3,a+3+o)),s=null;if(r.readBool()){if(i==null){_.default.w(this.TAG,"StreamMuxConfig Missing"),this.current_syncword_offset_=this.findNextSyncwordOffset(a+3+o),r.destroy();continue}s=i}else{var d=r.readBool();if(d&&r.readBool()){_.default.e(this.TAG,"audioMuxVersionA is Not Supported"),r.destroy();break}if(d&&this.getLATMValue(r),!r.readBool()){_.default.e(this.TAG,"allStreamsSameTimeFraming zero is Not Supported"),r.destroy();break}if(r.readBits(6)!==0){_.default.e(this.TAG,"more than 2 numSubFrames Not Supported"),r.destroy();break}if(r.readBits(4)!==0){_.default.e(this.TAG,"more than 2 numProgram Not Supported"),r.destroy();break}if(r.readBits(3)!==0){_.default.e(this.TAG,"more than 2 numLayer Not Supported"),r.destroy();break}var l=d?this.getLATMValue(r):0,y=r.readBits(5);l-=5;var f=r.readBits(4);l-=4;var g=r.readBits(4);l-=4,r.readBits(3),(l-=3)>0&&r.readBits(l);var T=r.readBits(3);if(T!==0){_.default.e(this.TAG,"frameLengthType = ".concat(T,". Only frameLengthType = 0 Supported")),r.destroy();break}r.readByte();var B=r.readBool();if(B)if(d)this.getLATMValue(r);else{for(var F=0;;){F<<=8;var q=r.readBool();if(F+=r.readByte(),!q)break}console.log(F)}r.readBool()&&r.readByte(),(s=new Pe).audio_object_type=y,s.sampling_freq_index=f,s.sampling_frequency=oe[s.sampling_freq_index],s.channel_config=g,s.other_data_present=B}for(var Z=0;;){var N=r.readByte();if(Z+=N,N!==255)break}for(var H=new Uint8Array(Z),he=0;he=6?(e=5,i=[,,,,],r=a-3):(e=2,i=[,,],r=a):s.indexOf("android")!==-1?(e=2,i=[,,],r=a):(e=5,r=a,i=[,,,,],a>=6?r=a-3:o===1&&(e=2,i=[,,],r=a)),i[0]=e<<3,i[0]|=(15&a)>>>1,i[1]=(15&a)<<7,i[1]|=(15&o)<<3,e===5&&(i[1]|=(15&r)>>>1,i[2]=(1&r)<<7,i[2]|=8,i[3]=0),this.config=i,this.sampling_rate=oe[a],this.channel_count=o,this.codec_mimetype="mp4a.40."+e,this.original_codec_mimetype="mp4a.40."+t},Xe=function(){},nt=function(){};(function(n){n[n.kSpliceNull=0]="kSpliceNull",n[n.kSpliceSchedule=4]="kSpliceSchedule",n[n.kSpliceInsert=5]="kSpliceInsert",n[n.kTimeSignal=6]="kTimeSignal",n[n.kBandwidthReservation=7]="kBandwidthReservation",n[n.kPrivateCommand=255]="kPrivateCommand"})(ie||(ie={}));var Ne,Qe=function(n){var i=n.readBool();return i?(n.readBits(6),{time_specified_flag:i,pts_time:4*n.readBits(31)+n.readBits(2)}):(n.readBits(7),{time_specified_flag:i})},ht=function(n){var i=n.readBool();return n.readBits(6),{auto_return:i,duration:4*n.readBits(31)+n.readBits(2)}},Ot=function(n,i){var t=i.readBits(8);return n?{component_tag:t}:{component_tag:t,splice_time:Qe(i)}},Pt=function(n){return{component_tag:n.readBits(8),utc_splice_time:n.readBits(32)}},xt=function(n){var i=n.readBits(32),t=n.readBool();n.readBits(7);var e={splice_event_id:i,splice_event_cancel_indicator:t};if(t)return e;if(e.out_of_network_indicator=n.readBool(),e.program_splice_flag=n.readBool(),e.duration_flag=n.readBool(),n.readBits(5),e.program_splice_flag)e.utc_splice_time=n.readBits(32);else{e.component_count=n.readBits(8),e.components=[];for(var a=0;a=e.byteLength)return this.eof_flag_=!0,e.byteLength;var a=e[t+0]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],o=e[t+0]<<16|e[t+1]<<8|e[t+2];if(a===1||o===1)return t;t++}},n.prototype.readNextNaluPayload=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_startcode_offset_,a=i[e+=(i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3])==1?4:3]>>1&63,o=(128&i[e])>>>7,r=this.findNextStartCodeOffset(e);if(this.current_startcode_offset_=r,o===0){var s=i.subarray(e,r);(t=new Ht).type=a,t.data=s}}return t},n}(),Wt=function(){function n(i,t,e,a){var o=23+(5+i.byteLength)+(5+t.byteLength)+(5+e.byteLength),r=this.data=new Uint8Array(o);r[0]=1,r[1]=(3&a.general_profile_space)<<6|(a.general_tier_flag?1:0)<<5|31&a.general_profile_idc,r[2]=a.general_profile_compatibility_flags_1,r[3]=a.general_profile_compatibility_flags_2,r[4]=a.general_profile_compatibility_flags_3,r[5]=a.general_profile_compatibility_flags_4,r[6]=a.general_constraint_indicator_flags_1,r[7]=a.general_constraint_indicator_flags_2,r[8]=a.general_constraint_indicator_flags_3,r[9]=a.general_constraint_indicator_flags_4,r[10]=a.general_constraint_indicator_flags_5,r[11]=a.general_constraint_indicator_flags_6,r[12]=a.general_level_idc,r[13]=240|(3840&a.min_spatial_segmentation_idc)>>8,r[14]=255&a.min_spatial_segmentation_idc,r[15]=252|3&a.parallelismType,r[16]=252|3&a.chroma_format_idc,r[17]=248|7&a.bit_depth_luma_minus8,r[18]=248|7&a.bit_depth_chroma_minus8,r[19]=0,r[20]=0,r[21]=(3&a.constant_frame_rate)<<6|(7&a.num_temporal_layers)<<3|(a.temporal_id_nested?1:0)<<2|3,r[22]=3,r[23]=128|Ne.kSliceVPS,r[24]=0,r[25]=1,r[26]=(65280&i.byteLength)>>8,r[27]=255&i.byteLength,r.set(i,28),r[23+(5+i.byteLength)+0]=128|Ne.kSliceSPS,r[23+(5+i.byteLength)+1]=0,r[23+(5+i.byteLength)+2]=1,r[23+(5+i.byteLength)+3]=(65280&t.byteLength)>>8,r[23+(5+i.byteLength)+4]=255&t.byteLength,r.set(t,23+(5+i.byteLength)+5),r[23+(5+i.byteLength+5+t.byteLength)+0]=128|Ne.kSlicePPS,r[23+(5+i.byteLength+5+t.byteLength)+1]=0,r[23+(5+i.byteLength+5+t.byteLength)+2]=1,r[23+(5+i.byteLength+5+t.byteLength)+3]=(65280&e.byteLength)>>8,r[23+(5+i.byteLength+5+t.byteLength)+4]=255&e.byteLength,r.set(e,23+(5+i.byteLength+5+t.byteLength)+5)}return n.prototype.getData=function(){return this.data},n}(),Yt=function(){},Xt=function(){},Qt=function(){},$t=[[64,64,80,80,96,96,112,112,128,128,160,160,192,192,224,224,256,256,320,320,384,384,448,448,512,512,640,640,768,768,896,896,1024,1024,1152,1152,1280,1280],[69,70,87,88,104,105,121,122,139,140,174,175,208,209,243,244,278,279,348,349,417,418,487,488,557,558,696,697,835,836,975,976,1114,1115,1253,1254,1393,1394],[96,96,120,120,144,144,168,168,192,192,240,240,288,288,336,336,384,384,480,480,576,576,672,672,768,768,960,960,1152,1152,1344,1344,1536,1536,1728,1728,1920,1920]],Jt=function(){function n(i){this.TAG="AC3Parser",this.data_=i,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not found AC3 syncword until payload end")}return n.prototype.findNextSyncwordOffset=function(i){for(var t=i,e=this.data_;;){if(t+7>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<8|e[t+1])==2935)return t;t++}},n.prototype.readNextAC3Frame=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_syncword_offset_,a=i[e+4]>>6,o=[48000,44200,33000][a],r=63&i[e+4],s=2*$t[a][r];if(isNaN(s)||e+s>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var d=this.findNextSyncwordOffset(e+s);this.current_syncword_offset_=d;var l=i[e+5]>>3,y=7&i[e+5],f=i[e+6]>>5,g=0;1&f&&f!==1&&(g+=2),4&f&&(g+=2),f===2&&(g+=2);var T=(i[e+6]<<8|i[e+7])>>12-g&1,B=[2,1,2,3,3,4,4,5][f]+T;(t=new Qt).sampling_frequency=o,t.channel_count=B,t.channel_mode=f,t.bit_stream_identification=l,t.low_frequency_effects_channel_on=T,t.bit_stream_mode=y,t.frame_size_code=r,t.data=i.subarray(e,e+s)}return t},n.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},n.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},n}(),Zt=function(n){var i;i=[n.sampling_rate_code<<6|n.bit_stream_identification<<1|n.bit_stream_mode>>2,(3&n.bit_stream_mode)<<6|n.channel_mode<<3|n.low_frequency_effects_channel_on<<2|n.frame_size_code>>4,n.frame_size_code<<4&224],this.config=i,this.sampling_rate=n.sampling_frequency,this.bit_stream_identification=n.bit_stream_identification,this.bit_stream_mode=n.bit_stream_mode,this.low_frequency_effects_channel_on=n.low_frequency_effects_channel_on,this.channel_count=n.channel_count,this.channel_mode=n.channel_mode,this.codec_mimetype="ac-3",this.original_codec_mimetype="ac-3"},ei=function(){},ti=function(){function n(i){this.TAG="EAC3Parser",this.data_=i,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not found AC3 syncword until payload end")}return n.prototype.findNextSyncwordOffset=function(i){for(var t=i,e=this.data_;;){if(t+7>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<8|e[t+1])==2935)return t;t++}},n.prototype.readNextEAC3Frame=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_syncword_offset_,a=new A(i.subarray(e+2)),o=(a.readBits(2),a.readBits(3),a.readBits(11)+1<<1),r=a.readBits(2),s=null,d=null;r===3?(s=[24000,22060,16000][r=a.readBits(2)],d=3):(s=[48000,44100,32000][r],d=a.readBits(2));var l=a.readBits(3),y=a.readBits(1),f=a.readBits(5);if(e+o>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var g=this.findNextSyncwordOffset(e+o);this.current_syncword_offset_=g;var T=[2,1,2,3,3,4,4,5][l]+y;a.destroy(),(t=new ei).sampling_frequency=s,t.channel_count=T,t.channel_mode=l,t.bit_stream_identification=f,t.low_frequency_effects_channel_on=y,t.frame_size=o,t.num_blks=[1,2,3,6][d],t.data=i.subarray(e,e+o)}return t},n.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},n.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},n}(),ii=function(n){var i,t=Math.floor(n.frame_size*n.sampling_frequency/(16*n.num_blks));i=[255&t,248&t,n.sampling_rate_code<<6|n.bit_stream_identification<<1,n.channel_mode<<1|n.low_frequency_effects_channel_on,0],this.config=i,this.sampling_rate=n.sampling_frequency,this.bit_stream_identification=n.bit_stream_identification,this.num_blks=n.num_blks,this.low_frequency_effects_channel_on=n.low_frequency_effects_channel_on,this.channel_count=n.channel_count,this.channel_mode=n.channel_mode,this.codec_mimetype="ec-3",this.original_codec_mimetype="ec-3"},ni=function(){},ai=function(){function n(i){this.TAG="AV1OBUInMpegTsParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=i,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&_.default.e(this.TAG,"Could not find AV1 startcode until payload end!")}return n._ebsp2rbsp=function(i){for(var t=i,e=t.byteLength,a=new Uint8Array(e),o=0,r=0;r=2&&t[r]===3&&t[r-1]===0&&t[r-2]===0||(a[o]=t[r],o++);return new Uint8Array(a.buffer,0,o)},n.prototype.findNextStartCodeOffset=function(i){for(var t=i,e=this.data_;;){if(t+2>=e.byteLength)return this.eof_flag_=!0,e.byteLength;if((e[t+0]<<16|e[t+1]<<8|e[t+2])==1)return t;t++}},n.prototype.readNextOBUPayload=function(){for(var i=this.data_,t=null;t==null&&!this.eof_flag_;){var e=this.current_startcode_offset_+3,a=this.findNextStartCodeOffset(e);this.current_startcode_offset_=a,t=n._ebsp2rbsp(i.subarray(e,a))}return t},n}(),ri=function(){},oi=function(){var n=function(i,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,a){e.__proto__=a}||function(e,a){for(var o in a)Object.prototype.hasOwnProperty.call(a,o)&&(e[o]=a[o])},n(i,t)};return function(i,t){if(typeof t!="function"&&t!==null)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function e(){this.constructor=i}n(i,t),i.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}}(),Ke=function(){return Ke=Object.assign||function(n){for(var i,t=1,e=arguments.length;t=4?(_.default.v("TSDemuxer","ts_packet_size = 192, m2ts mode"),a-=4):o===204&&_.default.v("TSDemuxer","ts_packet_size = 204, RS encoded MPEG2-TS stream"),{match:!0,consumed:0,ts_packet_size:o,sync_offset:a})},i.prototype.bindDataSource=function(t){return t.onDataArrival=this.parseChunks.bind(this),this},i.prototype.resetMediaInfo=function(){this.media_info_=new R.default},i.prototype.parseChunks=function(t,e){if(!(this.onError&&this.onMediaInfo&&this.onTrackMetadata&&this.onDataAvailable))throw new k.IllegalStateException("onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var a=0;for(this.first_parse_&&(this.first_parse_=!1,a=this.sync_offset_);a+this.ts_packet_size_<=t.byteLength;){var o=e+a;this.ts_packet_size_===192&&(a+=4);var r=new Uint8Array(t,a,188),s=r[0];if(s!==71){_.default.e(this.TAG,"sync_byte = ".concat(s,", not 0x47"));break}var d=(64&r[1])>>>6,l=(r[1],(31&r[1])<<8|r[2]),y=(48&r[3])>>>4,f=15&r[3],g=!(!this.pmt_||this.pmt_.pcr_pid!==l),T={},B=4;if(y==2||y==3){var F=r[4];if(F>0&&(g||y==3)&&(T.discontinuity_indicator=(128&r[5])>>>7,T.random_access_indicator=(64&r[5])>>>6,T.elementary_stream_priority_indicator=(32&r[5])>>>5,(16&r[5])>>>4)){var q=300*this.getPcrBase(r)+((1&r[10])<<8|r[11]);this.last_pcr_=q}if(y==2||5+F===188){a+=188,this.ts_packet_size_===204&&(a+=16);continue}B=5+F}if(y==1||y==3){if(l===0||l===this.current_pmt_pid_||this.pmt_!=null&&this.pmt_.pid_stream_type[l]===z.kSCTE35){var Z=188-B;this.handleSectionSlice(t,a+B,Z,{pid:l,file_position:o,payload_unit_start_indicator:d,continuity_conunter:f,random_access_indicator:T.random_access_indicator})}else if(this.pmt_!=null&&this.pmt_.pid_stream_type[l]!=null){Z=188-B;var N=this.pmt_.pid_stream_type[l];l!==this.pmt_.common_pids.h264&&l!==this.pmt_.common_pids.h265&&l!==this.pmt_.common_pids.av1&&l!==this.pmt_.common_pids.adts_aac&&l!==this.pmt_.common_pids.loas_aac&&l!==this.pmt_.common_pids.ac3&&l!==this.pmt_.common_pids.eac3&&l!==this.pmt_.common_pids.opus&&l!==this.pmt_.common_pids.mp3&&this.pmt_.pes_private_data_pids[l]!==!0&&this.pmt_.timed_id3_pids[l]!==!0&&this.pmt_.pgs_pids[l]!==!0&&this.pmt_.synchronous_klv_pids[l]!==!0&&this.pmt_.asynchronous_klv_pids[l]!==!0||this.handlePESSlice(t,a+B,Z,{pid:l,stream_type:N,file_position:o,payload_unit_start_indicator:d,continuity_conunter:f,random_access_indicator:T.random_access_indicator})}}a+=188,this.ts_packet_size_===204&&(a+=16)}return this.dispatchAudioVideoMediaSegment(),a},i.prototype.handleSectionSlice=function(t,e,a,o){var r=new Uint8Array(t,e,a),s=this.section_slice_queues_[o.pid];if(o.payload_unit_start_indicator){var d=r[0];if(s!=null&&s.total_length!==0){var l=new Uint8Array(t,e+1,Math.min(a,d));s.slices.push(l),s.total_length+=l.byteLength,s.total_length===s.expected_length?this.emitSectionSlices(s,o):this.clearSlices(s,o)}for(var y=1+d;y=s.expected_length&&this.clearSlices(s,o),y+=l.byteLength}}else s!=null&&s.total_length!==0&&(l=new Uint8Array(t,e,Math.min(a,s.expected_length-s.total_length)),s.slices.push(l),s.total_length+=l.byteLength,s.total_length===s.expected_length?this.emitSectionSlices(s,o):s.total_length>=s.expected_length&&this.clearSlices(s,o))},i.prototype.handlePESSlice=function(t,e,a,o){var r=new Uint8Array(t,e,a),s=r[0]<<16|r[1]<<8|r[2],d=(r[3],r[4]<<8|r[5]);if(o.payload_unit_start_indicator){if(s!==1)return void _.default.e(this.TAG,"handlePESSlice: packet_start_code_prefix should be 1 but with value ".concat(s));var l=this.pes_slice_queues_[o.pid];l&&(l.expected_length===0||l.expected_length===l.total_length?this.emitPESSlices(l,o):this.clearSlices(l,o)),this.pes_slice_queues_[o.pid]=new L,this.pes_slice_queues_[o.pid].file_position=o.file_position,this.pes_slice_queues_[o.pid].random_access_indicator=o.random_access_indicator}if(this.pes_slice_queues_[o.pid]!=null){var y=this.pes_slice_queues_[o.pid];y.slices.push(r),o.payload_unit_start_indicator&&(y.expected_length=d===0?0:d+6),y.total_length+=r.byteLength,y.expected_length>0&&y.expected_length===y.total_length?this.emitPESSlices(y,o):y.expected_length>0&&y.expected_length>>6,d=e[8],l=void 0,y=void 0;s!==2&&s!==3||(l=this.getTimestamp(e,9),y=s===3?this.getTimestamp(e,14):l);var f=9+d,g=void 0;if(r!==0){if(r<3+d)return void _.default.v(this.TAG,"Malformed PES: PES_packet_length < 3 + PES_header_data_length");g=r-3-d}else g=e.byteLength-f;var T=e.subarray(f,f+g);switch(t.stream_type){case z.kMPEG1Audio:case z.kMPEG2Audio:this.parseMP3Payload(T,l);break;case z.kPESPrivateData:this.pmt_.common_pids.av1===t.pid?this.parseAV1Payload(T,l,y,t.file_position,t.random_access_indicator):this.pmt_.common_pids.opus===t.pid?this.parseOpusPayload(T,l):this.pmt_.common_pids.ac3===t.pid?this.parseAC3Payload(T,l):this.pmt_.common_pids.eac3===t.pid?this.parseEAC3Payload(T,l):this.pmt_.asynchronous_klv_pids[t.pid]?this.parseAsynchronousKLVMetadataPayload(T,t.pid,o):this.pmt_.smpte2038_pids[t.pid]?this.parseSMPTE2038MetadataPayload(T,l,y,t.pid,o):this.parsePESPrivateDataPayload(T,l,y,t.pid,o);break;case z.kADTSAAC:this.parseADTSAACPayload(T,l);break;case z.kLOASAAC:this.parseLOASAACPayload(T,l);break;case z.kAC3:this.parseAC3Payload(T,l);break;case z.kEAC3:this.parseEAC3Payload(T,l);break;case z.kMetadata:this.pmt_.timed_id3_pids[t.pid]?this.parseTimedID3MetadataPayload(T,l,y,t.pid,o):this.pmt_.synchronous_klv_pids[t.pid]&&this.parseSynchronousKLVMetadataPayload(T,l,y,t.pid,o);break;case z.kPGS:this.parsePGSPayload(T,l,y,t.pid,o,this.pmt_.pgs_langs[t.pid]);break;case z.kH264:this.parseH264Payload(T,l,y,t.file_position,t.random_access_indicator);break;case z.kH265:this.parseH265Payload(T,l,y,t.file_position,t.random_access_indicator)}}else o!==188&&o!==191&&o!==240&&o!==241&&o!==255&&o!==242&&o!==248||t.stream_type!==z.kPESPrivateData||(f=6,g=void 0,g=r!==0?r:e.byteLength-f,T=e.subarray(f,f+g),this.parsePESPrivateDataPayload(T,void 0,void 0,t.pid,o));else _.default.e(this.TAG,"parsePES: packet_start_code_prefix should be 1 but with value ".concat(a))},i.prototype.parsePAT=function(t){var e=t[0];if(e===0){var a=(15&t[1])<<8|t[2],o=(t[3],t[4],(62&t[5])>>>1),r=1&t[5],s=t[6],d=(t[7],null);if(r===1&&s===0)(d=new te).version_number=o;else if((d=this.pat_)==null)return;for(var l=a-5-4,y=-1,f=-1,g=8;g<8+l;g+=4){var T=t[g]<<8|t[g+1],B=(31&t[g+2])<<8|t[g+3];T===0?d.network_pid=B:(d.program_pmt_pid[T]=B,y===-1&&(y=T),f===-1&&(f=B))}r===1&&s===0&&(this.pat_==null&&_.default.v(this.TAG,"Parsed first PAT: ".concat(JSON.stringify(d))),this.pat_=d,this.current_program_=y,this.current_pmt_pid_=f)}else _.default.e(this.TAG,"parsePAT: table_id ".concat(e," is not corresponded to PAT!"))},i.prototype.parsePMT=function(t){var e=t[0];if(e===2){var a=(15&t[1])<<8|t[2],o=t[3]<<8|t[4],r=(62&t[5])>>>1,s=1&t[5],d=t[6],l=(t[7],null);if(s===1&&d===0)(l=new Re).program_number=o,l.version_number=r,this.program_pmt_map_[o]=l;else if((l=this.program_pmt_map_[o])==null)return;l.pcr_pid=(31&t[8])<<8|t[9];for(var y=(15&t[10])<<8|t[11],f=12+y,g=a-9-y-4,T=f;T0){for(var H=T+5;H0)for(H=T+5;H0)for(H=T+5;H1&&(_.default.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(s,"ms, PES pts: ").concat(r,"ms")),r=s)}}for(var d,l=new Ue(t),y=null,f=r;(y=l.readNextAACFrame())!=null;){o=1024/y.sampling_frequency*1000;var g={codec:"aac",data:y};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"aac",audio_object_type:y.audio_object_type,sampling_freq_index:y.sampling_freq_index,sampling_frequency:y.sampling_frequency,channel_config:y.channel_config},this.dispatchAudioInitSegment(g)):this.detectAudioMetadataChange(g)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(g)),d=f;var T=Math.floor(f),B={unit:y.data,length:y.data.byteLength,pts:T,dts:T};this.audio_track_.samples.push(B),this.audio_track_.length+=y.data.byteLength,f+=o}l.hasIncompleteData()&&(this.aac_last_incomplete_data_=l.getIncompleteData()),d&&(this.audio_last_sample_pts_=d)}},i.prototype.parseLOASAACPayload=function(t,e){var a;if(!this.has_video_||this.video_init_segment_dispatched_){if(this.aac_last_incomplete_data_){var o=new Uint8Array(t.byteLength+this.aac_last_incomplete_data_.byteLength);o.set(this.aac_last_incomplete_data_,0),o.set(t,this.aac_last_incomplete_data_.byteLength),t=o}var r,s;if(e!=null&&(s=e/this.timescale_),this.audio_metadata_.codec==="aac"){if(e==null&&this.audio_last_sample_pts_!=null)r=1024/this.audio_metadata_.sampling_frequency*1000,s=this.audio_last_sample_pts_+r;else if(e==null)return void _.default.w(this.TAG,"AAC: Unknown pts");if(this.aac_last_incomplete_data_&&this.audio_last_sample_pts_){r=1024/this.audio_metadata_.sampling_frequency*1000;var d=this.audio_last_sample_pts_+r;Math.abs(d-s)>1&&(_.default.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(d,"ms, PES pts: ").concat(s,"ms")),s=d)}}for(var l,y=new je(t),f=null,g=s;(f=y.readNextAACFrame((a=this.loas_previous_frame)!==null&&a!==void 0?a:void 0))!=null;){this.loas_previous_frame=f,r=1024/f.sampling_frequency*1000;var T={codec:"aac",data:f};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"aac",audio_object_type:f.audio_object_type,sampling_freq_index:f.sampling_freq_index,sampling_frequency:f.sampling_frequency,channel_config:f.channel_config},this.dispatchAudioInitSegment(T)):this.detectAudioMetadataChange(T)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(T)),l=g;var B=Math.floor(g),F={unit:f.data,length:f.data.byteLength,pts:B,dts:B};this.audio_track_.samples.push(F),this.audio_track_.length+=f.data.byteLength,g+=r}y.hasIncompleteData()&&(this.aac_last_incomplete_data_=y.getIncompleteData()),l&&(this.audio_last_sample_pts_=l)}},i.prototype.parseAC3Payload=function(t,e){if(!this.has_video_||this.video_init_segment_dispatched_){var a,o;if(e!=null&&(o=e/this.timescale_),this.audio_metadata_.codec==="ac-3"){if(e==null&&this.audio_last_sample_pts_!=null)a=1536/this.audio_metadata_.sampling_frequency*1000,o=this.audio_last_sample_pts_+a;else if(e==null)return void _.default.w(this.TAG,"AC3: Unknown pts")}for(var r,s=new Jt(t),d=null,l=o;(d=s.readNextAC3Frame())!=null;){a=1536/d.sampling_frequency*1000;var y={codec:"ac-3",data:d};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"ac-3",sampling_frequency:d.sampling_frequency,bit_stream_identification:d.bit_stream_identification,bit_stream_mode:d.bit_stream_mode,low_frequency_effects_channel_on:d.low_frequency_effects_channel_on,channel_mode:d.channel_mode},this.dispatchAudioInitSegment(y)):this.detectAudioMetadataChange(y)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(y)),r=l;var f=Math.floor(l),g={unit:d.data,length:d.data.byteLength,pts:f,dts:f};this.audio_track_.samples.push(g),this.audio_track_.length+=d.data.byteLength,l+=a}r&&(this.audio_last_sample_pts_=r)}},i.prototype.parseEAC3Payload=function(t,e){if(!this.has_video_||this.video_init_segment_dispatched_){var a,o;if(e!=null&&(o=e/this.timescale_),this.audio_metadata_.codec==="ec-3"){if(e==null&&this.audio_last_sample_pts_!=null)a=256*this.audio_metadata_.num_blks/this.audio_metadata_.sampling_frequency*1000,o=this.audio_last_sample_pts_+a;else if(e==null)return void _.default.w(this.TAG,"EAC3: Unknown pts")}for(var r,s=new ti(t),d=null,l=o;(d=s.readNextEAC3Frame())!=null;){a=1536/d.sampling_frequency*1000;var y={codec:"ec-3",data:d};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"ec-3",sampling_frequency:d.sampling_frequency,bit_stream_identification:d.bit_stream_identification,low_frequency_effects_channel_on:d.low_frequency_effects_channel_on,num_blks:d.num_blks,channel_mode:d.channel_mode},this.dispatchAudioInitSegment(y)):this.detectAudioMetadataChange(y)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(y)),r=l;var f=Math.floor(l),g={unit:d.data,length:d.data.byteLength,pts:f,dts:f};this.audio_track_.samples.push(g),this.audio_track_.length+=d.data.byteLength,l+=a}r&&(this.audio_last_sample_pts_=r)}},i.prototype.parseOpusPayload=function(t,e){if(!this.has_video_||this.video_init_segment_dispatched_){var a,o;if(e!=null&&(o=e/this.timescale_),this.audio_metadata_.codec==="opus"){if(e==null&&this.audio_last_sample_pts_!=null)a=20,o=this.audio_last_sample_pts_+a;else if(e==null)return void _.default.w(this.TAG,"Opus: Unknown pts")}for(var r,s=o,d=0;d>>3&3,o=(6&t[1])>>1,r=(t[2],(12&t[2])>>>2),s=3&~(t[3]>>>6)?2:1,d=0,l=34;switch(a){case 0:d=[11025,12000,8000,0][r];break;case 2:d=[22050,24000,16000,0][r];break;case 3:d=[44100,48000,32000,0][r]}switch(o){case 1:l=34;break;case 2:l=33;break;case 3:l=32}var y=new Xt;y.object_type=l,y.sample_rate=d,y.channel_count=s,y.data=t;var f={codec:"mp3",data:y};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"mp3",object_type:l,sample_rate:d,channel_count:s},this.dispatchAudioInitSegment(f)):this.detectAudioMetadataChange(f)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(f));var g={unit:t,length:t.byteLength,pts:e/this.timescale_,dts:e/this.timescale_};this.audio_track_.samples.push(g),this.audio_track_.length+=t.byteLength}},i.prototype.detectAudioMetadataChange=function(t){if(t.codec!==this.audio_metadata_.codec)return _.default.v(this.TAG,"Audio: Audio Codecs changed from "+"".concat(this.audio_metadata_.codec," to ").concat(t.codec)),!0;if(t.codec==="aac"&&this.audio_metadata_.codec==="aac"){if((e=t.data).audio_object_type!==this.audio_metadata_.audio_object_type)return _.default.v(this.TAG,"AAC: AudioObjectType changed from "+"".concat(this.audio_metadata_.audio_object_type," to ").concat(e.audio_object_type)),!0;if(e.sampling_freq_index!==this.audio_metadata_.sampling_freq_index)return _.default.v(this.TAG,"AAC: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sampling_freq_index," to ").concat(e.sampling_freq_index)),!0;if(e.channel_config!==this.audio_metadata_.channel_config)return _.default.v(this.TAG,"AAC: Channel configuration changed from "+"".concat(this.audio_metadata_.channel_config," to ").concat(e.channel_config)),!0}else if(t.codec==="ac-3"&&this.audio_metadata_.codec==="ac-3"){var e;if((e=t.data).sampling_frequency!==this.audio_metadata_.sampling_frequency)return _.default.v(this.TAG,"AC3: Sampling Frequency changed from "+"".concat(this.audio_metadata_.sampling_frequency," to ").concat(e.sampling_frequency)),!0;if(e.bit_stream_identification!==this.audio_metadata_.bit_stream_identification)return _.default.v(this.TAG,"AC3: Bit Stream Identification changed from "+"".concat(this.audio_metadata_.bit_stream_identification," to ").concat(e.bit_stream_identification)),!0;if(e.bit_stream_mode!==this.audio_metadata_.bit_stream_mode)return _.default.v(this.TAG,"AC3: BitStream Mode changed from "+"".concat(this.audio_metadata_.bit_stream_mode," to ").concat(e.bit_stream_mode)),!0;if(e.channel_mode!==this.audio_metadata_.channel_mode)return _.default.v(this.TAG,"AC3: Channel Mode changed from "+"".concat(this.audio_metadata_.channel_mode," to ").concat(e.channel_mode)),!0;if(e.low_frequency_effects_channel_on!==this.audio_metadata_.low_frequency_effects_channel_on)return _.default.v(this.TAG,"AC3: Low Frequency Effects Channel On changed from "+"".concat(this.audio_metadata_.low_frequency_effects_channel_on," to ").concat(e.low_frequency_effects_channel_on)),!0}else if(t.codec==="opus"&&this.audio_metadata_.codec==="opus"){if((a=t.meta).sample_rate!==this.audio_metadata_.sample_rate)return _.default.v(this.TAG,"Opus: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sample_rate," to ").concat(a.sample_rate)),!0;if(a.channel_count!==this.audio_metadata_.channel_count)return _.default.v(this.TAG,"Opus: Channel count changed from "+"".concat(this.audio_metadata_.channel_count," to ").concat(a.channel_count)),!0}else if(t.codec==="mp3"&&this.audio_metadata_.codec==="mp3"){var a;if((a=t.data).object_type!==this.audio_metadata_.object_type)return _.default.v(this.TAG,"MP3: AudioObjectType changed from "+"".concat(this.audio_metadata_.object_type," to ").concat(a.object_type)),!0;if(a.sample_rate!==this.audio_metadata_.sample_rate)return _.default.v(this.TAG,"MP3: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sample_rate," to ").concat(a.sample_rate)),!0;if(a.channel_count!==this.audio_metadata_.channel_count)return _.default.v(this.TAG,"MP3: Channel count changed from "+"".concat(this.audio_metadata_.channel_count," to ").concat(a.channel_count)),!0}return!1},i.prototype.dispatchAudioInitSegment=function(t){var e={type:"audio"};if(e.id=this.audio_track_.id,e.timescale=1000,e.duration=this.duration_,this.audio_metadata_.codec==="aac"){var a=t.codec==="aac"?t.data:null,o=new Fe(a);e.audioSampleRate=o.sampling_rate,e.channelCount=o.channel_count,e.codec=o.codec_mimetype,e.originalCodec=o.original_codec_mimetype,e.config=o.config,e.refSampleDuration=1024/e.audioSampleRate*e.timescale}else if(this.audio_metadata_.codec==="ac-3"){var r=t.codec==="ac-3"?t.data:null,s=new Zt(r);e.audioSampleRate=s.sampling_rate,e.channelCount=s.channel_count,e.codec=s.codec_mimetype,e.originalCodec=s.original_codec_mimetype,e.config=s.config,e.refSampleDuration=1536/e.audioSampleRate*e.timescale}else if(this.audio_metadata_.codec==="ec-3"){var d=t.codec==="ec-3"?t.data:null,l=new ii(d);e.audioSampleRate=l.sampling_rate,e.channelCount=l.channel_count,e.codec=l.codec_mimetype,e.originalCodec=l.original_codec_mimetype,e.config=l.config,e.refSampleDuration=256*l.num_blks/e.audioSampleRate*e.timescale}else this.audio_metadata_.codec==="opus"?(e.audioSampleRate=this.audio_metadata_.sample_rate,e.channelCount=this.audio_metadata_.channel_count,e.channelConfigCode=this.audio_metadata_.channel_config_code,e.codec="opus",e.originalCodec="opus",e.config=void 0,e.refSampleDuration=20):this.audio_metadata_.codec==="mp3"&&(e.audioSampleRate=this.audio_metadata_.sample_rate,e.channelCount=this.audio_metadata_.channel_count,e.codec="mp3",e.originalCodec="mp3",e.config=void 0);this.audio_init_segment_dispatched_==0&&_.default.v(this.TAG,"Generated first AudioSpecificConfig for mimeType: ".concat(e.codec)),this.onTrackMetadata("audio",e),this.audio_init_segment_dispatched_=!0,this.video_metadata_changed_=!1;var y=this.media_info_;y.hasAudio=!0,y.audioCodec=e.originalCodec,y.audioSampleRate=e.audioSampleRate,y.audioChannelCount=e.channelCount,y.hasVideo&&y.videoCodec?y.mimeType='video/mp2t; codecs="'.concat(y.videoCodec,",").concat(y.audioCodec,'"'):y.mimeType='video/mp2t; codecs="'.concat(y.audioCodec,'"'),y.isComplete()&&this.onMediaInfo(y)},i.prototype.dispatchPESPrivateDataDescriptor=function(t,e,a){var o=new nt;o.pid=t,o.stream_type=e,o.descriptor=a,this.onPESPrivateDataDescriptor&&this.onPESPrivateDataDescriptor(o)},i.prototype.parsePESPrivateDataPayload=function(t,e,a,o,r){var s=new Xe;if(s.pid=o,s.stream_id=r,s.len=t.byteLength,s.data=t,e!=null){var d=Math.floor(e/this.timescale_);s.pts=d}else s.nearest_pts=this.getNearestTimestampMilliseconds();if(a!=null){var l=Math.floor(a/this.timescale_);s.dts=l}this.onPESPrivateData&&this.onPESPrivateData(s)},i.prototype.parseTimedID3MetadataPayload=function(t,e,a,o,r){var s=new Xe;if(s.pid=o,s.stream_id=r,s.len=t.byteLength,s.data=t,e!=null){var d=Math.floor(e/this.timescale_);s.pts=d}if(a!=null){var l=Math.floor(a/this.timescale_);s.dts=l}this.onTimedID3Metadata&&this.onTimedID3Metadata(s)},i.prototype.parsePGSPayload=function(t,e,a,o,r,s){var d=new ri;if(d.pid=o,d.lang=s,d.stream_id=r,d.len=t.byteLength,d.data=t,e!=null){var l=Math.floor(e/this.timescale_);d.pts=l}if(a!=null){var y=Math.floor(a/this.timescale_);d.dts=y}this.onPGSSubtitleData&&this.onPGSSubtitleData(d)},i.prototype.parseSynchronousKLVMetadataPayload=function(t,e,a,o,r){var s=new ni;if(s.pid=o,s.stream_id=r,s.len=t.byteLength,s.data=t,e!=null){var d=Math.floor(e/this.timescale_);s.pts=d}if(a!=null){var l=Math.floor(a/this.timescale_);s.dts=l}s.access_units=function(y){for(var f=[],g=0;g+5>>24&255,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=255&t,e.set(i,4);var s=8;for(r=0;r>>24&255,i>>>16&255,i>>>8&255,255&i,t>>>24&255,t>>>16&255,t>>>8&255,255&t,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]))},n.trak=function(i){return n.box(n.types.trak,n.tkhd(i),n.mdia(i))},n.tkhd=function(i){var{id:t,duration:e,presentWidth:a,presentHeight:o}=i;return n.box(n.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,0,0,0,0,e>>>24&255,e>>>16&255,e>>>8&255,255&e,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,a>>>8&255,255&a,0,0,o>>>8&255,255&o,0,0]))},n.mdia=function(i){return n.box(n.types.mdia,n.mdhd(i),n.hdlr(i),n.minf(i))},n.mdhd=function(i){var{timescale:t,duration:e}=i;return n.box(n.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,e>>>24&255,e>>>16&255,e>>>8&255,255&e,85,196,0,0]))},n.hdlr=function(i){var t;return t=i.type==="audio"?n.constants.HDLR_AUDIO:n.constants.HDLR_VIDEO,n.box(n.types.hdlr,t)},n.minf=function(i){var t;return t=i.type==="audio"?n.box(n.types.smhd,n.constants.SMHD):n.box(n.types.vmhd,n.constants.VMHD),n.box(n.types.minf,t,n.dinf(),n.stbl(i))},n.dinf=function(){return n.box(n.types.dinf,n.box(n.types.dref,n.constants.DREF))},n.stbl=function(i){return n.box(n.types.stbl,n.stsd(i),n.box(n.types.stts,n.constants.STTS),n.box(n.types.stsc,n.constants.STSC),n.box(n.types.stsz,n.constants.STSZ),n.box(n.types.stco,n.constants.STCO))},n.stsd=function(i){return i.type==="audio"?i.codec==="mp3"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.mp3(i)):i.codec==="ac-3"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.ac3(i)):i.codec==="ec-3"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.ec3(i)):i.codec==="opus"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.Opus(i)):i.codec=="flac"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.fLaC(i)):i.codec=="ipcm"?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.ipcm(i)):n.box(n.types.stsd,n.constants.STSD_PREFIX,n.mp4a(i)):i.type==="video"&&i.codec.startsWith("hvc1")?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.hvc1(i)):i.type==="video"&&i.codec.startsWith("av01")?n.box(n.types.stsd,n.constants.STSD_PREFIX,n.av01(i)):n.box(n.types.stsd,n.constants.STSD_PREFIX,n.avc1(i))},n.mp3=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types[".mp3"],a)},n.mp4a=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types.mp4a,a,n.esds(i))},n.ac3=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types["ac-3"],a,n.box(n.types.dac3,new Uint8Array(i.config)))},n.ec3=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types["ec-3"],a,n.box(n.types.dec3,new Uint8Array(i.config)))},n.esds=function(i){var t=i.config||[],e=t.length,a=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).concat([6,1,2]));return n.box(n.types.esds,a)},n.Opus=function(i){var{channelCount:t,audioSampleRate:e}=i,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types.Opus,a,n.dOps(i))},n.dOps=function(i){var{channelCount:t,channelConfigCode:e,audioSampleRate:a}=i;if(i.config)return n.box(n.types.dOps,i.config);var o=[];switch(e){case 1:case 2:o=[0];break;case 0:o=[255,1,1,0,1];break;case 128:o=[255,2,0,0,1];break;case 3:o=[1,2,1,0,2,1];break;case 4:o=[1,2,2,0,1,2,3];break;case 5:o=[1,3,2,0,4,1,2,3];break;case 6:o=[1,4,2,0,4,1,2,3,5];break;case 7:o=[1,4,2,0,4,1,2,3,5,6];break;case 8:o=[1,5,3,0,6,1,2,3,4,5,7];break;case 130:o=[1,1,2,0,1];break;case 131:o=[1,1,3,0,1,2];break;case 132:o=[1,1,4,0,1,2,3];break;case 133:o=[1,1,5,0,1,2,3,4];break;case 134:o=[1,1,6,0,1,2,3,4,5];break;case 135:o=[1,1,7,0,1,2,3,4,5,6];break;case 136:o=[1,1,8,0,1,2,3,4,5,6,7]}var r=new Uint8Array(pt([0,t,0,0,a>>>24&255,a>>>17&255,a>>>8&255,a>>>0&255,0,0],o,!0));return n.box(n.types.dOps,r)},n.fLaC=function(i){var t=i.channelCount,e=Math.min(i.audioSampleRate,65535),a=i.sampleSize,o=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,a,0,0,0,0,e>>>8&255,255&e,0,0]);return n.box(n.types.fLaC,o,n.dfLa(i))},n.dfLa=function(i){var t=new Uint8Array(pt([0,0,0,0],i.config,!0));return n.box(n.types.dfLa,t)},n.ipcm=function(i){var t=i.channelCount,e=Math.min(i.audioSampleRate,65535),a=i.sampleSize,o=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,a,0,0,0,0,e>>>8&255,255&e,0,0]);return i.channelCount===1?n.box(n.types.ipcm,o,n.pcmC(i)):n.box(n.types.ipcm,o,n.chnl(i),n.pcmC(i))},n.chnl=function(i){var t=new Uint8Array([0,0,0,0,1,i.channelCount,0,0,0,0,0,0,0,0]);return n.box(n.types.chnl,t)},n.pcmC=function(i){var t=i.littleEndian?1:0,e=i.sampleSize,a=new Uint8Array([0,0,0,0,t,e]);return n.box(n.types.pcmC,a)},n.avc1=function(i){var{avcc:t,codecWidth:e,codecHeight:a}=i,o=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,e>>>8&255,255&e,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return n.box(n.types.avc1,o,n.box(n.types.avcC,t))},n.hvc1=function(i){var{hvcc:t,codecWidth:e,codecHeight:a}=i,o=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,e>>>8&255,255&e,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return n.box(n.types.hvc1,o,n.box(n.types.hvcC,t))},n.av01=function(i){var t=i.av1c,e=i.codecWidth||192,a=i.codecHeight||108,o=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,e>>>8&255,255&e,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return n.box(n.types.av01,o,n.box(n.types.av1C,t))},n.mvex=function(i){return n.box(n.types.mvex,n.trex(i))},n.trex=function(i){var t=i.id,e=new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return n.box(n.types.trex,e)},n.moof=function(i,t){return n.box(n.types.moof,n.mfhd(i.sequenceNumber),n.traf(i,t))},n.mfhd=function(i){var t=new Uint8Array([0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i]);return n.box(n.types.mfhd,t)},n.traf=function(i,t){var e=i.id,a=n.box(n.types.tfhd,new Uint8Array([0,0,0,0,e>>>24&255,e>>>16&255,e>>>8&255,255&e])),o=n.box(n.types.tfdt,new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t])),r=n.sdtp(i),s=n.trun(i,r.byteLength+16+16+8+16+8+8);return n.box(n.types.traf,a,o,s,r)},n.sdtp=function(i){for(var t=i.samples||[],e=t.length,a=new Uint8Array(4+e),o=0;o>>24&255,a>>>16&255,a>>>8&255,255&a,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0);for(var s=0;s>>24&255,d>>>16&255,d>>>8&255,255&d,l>>>24&255,l>>>16&255,l>>>8&255,255&l,y.isLeading<<2|y.dependsOn,y.isDependedOn<<6|y.hasRedundancy<<4|y.isNonSync,0,0,f>>>24&255,f>>>16&255,f>>>8&255,255&f],12+16*s)}return n.box(n.types.trun,r)},n.mdat=function(i){return n.box(n.types.mdat,i)},n}();mt.init();var We=mt,gt=function(){function n(){}return n.getSilentFrame=function(i,t){if(i==="mp4a.40.2"){if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null},n}(),ze=D(47),yt=function(){function n(i){this.TAG="MP4Remuxer",this._config=i,this._isLive=i.isLive===!0,this._dtsBase=-1,this._dtsBaseInited=!1,this._audioDtsBase=1/0,this._videoDtsBase=1/0,this._audioNextDts=void 0,this._videoNextDts=void 0,this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList=new ze.MediaSegmentInfoList("audio"),this._videoSegmentInfoList=new ze.MediaSegmentInfoList("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!(!S.default.chrome||!(S.default.version.major<50||S.default.version.major===50&&S.default.version.build<2661)),this._fillSilentAfterSeek=S.default.msedge||S.default.msie,this._mp3UseMpegAudio=!S.default.firefox,this._fillAudioTimestampGap=this._config.fixAudioTimestampGap}return n.prototype.destroy=function(){this._dtsBase=-1,this._dtsBaseInited=!1,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList.clear(),this._audioSegmentInfoList=null,this._videoSegmentInfoList.clear(),this._videoSegmentInfoList=null,this._onInitSegment=null,this._onMediaSegment=null},n.prototype.bindDataSource=function(i){return i.onDataAvailable=this.remux.bind(this),i.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this},Object.defineProperty(n.prototype,"onInitSegment",{get:function(){return this._onInitSegment},set:function(i){this._onInitSegment=i},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"onMediaSegment",{get:function(){return this._onMediaSegment},set:function(i){this._onMediaSegment=i},enumerable:!1,configurable:!0}),n.prototype.insertDiscontinuity=function(){this._audioNextDts=this._videoNextDts=void 0},n.prototype.seek=function(i){this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()},n.prototype.remux=function(i,t){if(!this._onMediaSegment)throw new k.IllegalStateException("MP4Remuxer: onMediaSegment callback must be specificed!");this._dtsBaseInited||this._calculateDtsBase(i,t),t&&this._remuxVideo(t),i&&this._remuxAudio(i)},n.prototype._onTrackMetadataReceived=function(i,t){var e=null,a="mp4",o=t.codec;if(i==="audio")this._audioMeta=t,t.codec==="mp3"&&this._mp3UseMpegAudio?(a="mpeg",o="",e=new Uint8Array):e=We.generateInitSegment(t);else{if(i!=="video")return;this._videoMeta=t,e=We.generateInitSegment(t)}if(!this._onInitSegment)throw new k.IllegalStateException("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(i,{type:i,data:e.buffer,codec:o,container:"".concat(i,"/").concat(a),mediaDuration:t.duration})},n.prototype._calculateDtsBase=function(i,t){this._dtsBaseInited||(i&&i.samples&&i.samples.length&&(this._audioDtsBase=i.samples[0].dts),t&&t.samples&&t.samples.length&&(this._videoDtsBase=t.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)},n.prototype.getTimestampBase=function(){if(this._dtsBaseInited)return this._dtsBase},n.prototype.flushStashedSamples=function(){var i=this._videoStashedLastSample,t=this._audioStashedLastSample,e={type:"video",id:1,sequenceNumber:0,samples:[],length:0};i!=null&&(e.samples.push(i),e.length=i.length);var a={type:"audio",id:2,sequenceNumber:0,samples:[],length:0};t!=null&&(a.samples.push(t),a.length=t.length),this._videoStashedLastSample=null,this._audioStashedLastSample=null,this._remuxVideo(e,!0),this._remuxAudio(a,!0)},n.prototype._remuxAudio=function(i,t){if(this._audioMeta!=null){var e,a=i,o=a.samples,r=void 0,s=-1,d=this._audioMeta.refSampleDuration,l=this._audioMeta.codec==="mp3"&&this._mp3UseMpegAudio,y=this._dtsBaseInited&&this._audioNextDts===void 0,f=!1;if(o&&o.length!==0&&(o.length!==1||t)){var g=0,T=null,B=0;l?(g=0,B=a.length):(g=8,B=8+a.length);var F=null;if(o.length>1&&(B-=(F=o.pop()).length),this._audioStashedLastSample!=null){var q=this._audioStashedLastSample;this._audioStashedLastSample=null,o.unshift(q),B+=q.length}F!=null&&(this._audioStashedLastSample=F);var Z=o[0].dts-this._dtsBase;if(this._audioNextDts)r=Z-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())r=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&this._audioMeta.originalCodec!=="mp3"&&(f=!0);else{var N=this._audioSegmentInfoList.getLastSampleBefore(Z);if(N!=null){var H=Z-(N.originalDts+N.duration);H<=3&&(H=0),r=Z-(N.dts+N.duration+H)}else r=0}if(f){var he=Z-r,ve=this._videoSegmentInfoList.getLastSegmentBefore(Z);if(ve!=null&&ve.beginDts=3*d&&this._fillAudioTimestampGap){Ce=!0;var be,Be=Math.floor(r/d);_.default.w(this.TAG,`Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync. +`+"originalDts: ".concat(Se," ms, curRefDts: ").concat(pe," ms, ")+"dtsCorrection: ".concat(Math.round(r)," ms, generate: ").concat(Be," frames")),ne=Math.floor(pe),Te=Math.floor(pe+d)-ne,(be=gt.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount))==null&&(_.default.w(this.TAG,"Unable to generate silent frame for "+"".concat(this._audioMeta.originalCodec," with ").concat(this._audioMeta.channelCount," channels, repeat last frame")),be=De),we=[];for(var ye=0;ye=1?ge[ge.length-1].duration:Math.floor(d),this._audioNextDts=ne+Te;s===-1&&(s=ne),ge.push({dts:ne,pts:ne,cts:0,unit:q.unit,size:q.unit.byteLength,duration:Te,originalDts:Se,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}}),Ce&&ge.push.apply(ge,we)}}if(ge.length===0)return a.samples=[],void(a.length=0);for(l?T=new Uint8Array(B):((T=new Uint8Array(B))[0]=B>>>24&255,T[1]=B>>>16&255,T[2]=B>>>8&255,T[3]=255&B,T.set(We.types.mdat,4)),ce=0;ce1&&(g-=(T=r.pop()).length),this._videoStashedLastSample!=null){var B=this._videoStashedLastSample;this._videoStashedLastSample=null,r.unshift(B),g+=B.length}T!=null&&(this._videoStashedLastSample=T);var F=r[0].dts-this._dtsBase;if(this._videoNextDts)s=F-this._videoNextDts;else if(this._videoSegmentInfoList.isEmpty())s=0;else{var q=this._videoSegmentInfoList.getLastSampleBefore(F);if(q!=null){var Z=F-(q.originalDts+q.duration);Z<=3&&(Z=0),s=F-(q.dts+q.duration+Z)}else s=0}for(var N=new ze.MediaSegmentInfo,H=[],he=0;he=1?H[H.length-1].duration:Math.floor(this._videoMeta.refSampleDuration),ne){var Se=new ze.SampleInfo(ae,ce,De,B.dts,!0);Se.fileposition=B.fileposition,N.appendSyncPoint(Se)}H.push({dts:ae,pts:ce,cts:ge,units:B.units,size:B.length,isKeyframe:ne,duration:De,originalDts:ve,flags:{isLeading:0,dependsOn:ne?2:1,isDependedOn:ne?1:0,hasRedundancy:0,isNonSync:ne?0:1}})}for((f=new Uint8Array(g))[0]=g>>>24&255,f[1]=g>>>16&255,f[2]=g>>>8&255,f[3]=255&g,f.set(We.types.mdat,4),he=0;he0)this._demuxer.bindDataSource(this._ioctl),this._demuxer.timestampBase=this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase,a=this._demuxer.parseChunks(i,t);else{var o=null;(o=de.probe(i)).match&&(this._setupFLVDemuxerRemuxer(o),a=this._demuxer.parseChunks(i,t)),o.match||o.needMoreData||(o=ft.probe(i)).match&&(this._setupTSDemuxerRemuxer(o),a=this._demuxer.parseChunks(i,t)),o.match||o.needMoreData||(o=null,_.default.e(this.TAG,"Non MPEG-TS/FLV, Unsupported media type!"),Promise.resolve().then(function(){e._internalAbort()}),this._emitter.emit(Ie.default.DEMUX_ERROR,m.default.FORMAT_UNSUPPORTED,"Non MPEG-TS/FLV, Unsupported media type!"))}return a},n.prototype._setupFLVDemuxerRemuxer=function(i){this._demuxer=new de(i,this._config),this._remuxer||(this._remuxer=new yt(this._config));var t=this._mediaDataSource;t.duration==null||isNaN(t.duration)||(this._demuxer.overridedDuration=t.duration),typeof t.hasAudio=="boolean"&&(this._demuxer.overridedHasAudio=t.hasAudio),typeof t.hasVideo=="boolean"&&(this._demuxer.overridedHasVideo=t.hasVideo),this._demuxer.timestampBase=t.segments[this._currentSegmentIndex].timestampBase,this._demuxer.onError=this._onDemuxException.bind(this),this._demuxer.onMediaInfo=this._onMediaInfo.bind(this),this._demuxer.onMetaDataArrived=this._onMetaDataArrived.bind(this),this._demuxer.onScriptDataArrived=this._onScriptDataArrived.bind(this),this._demuxer.onSeiArrived=this._onSEI.bind(this),this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl)),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},n.prototype._setupTSDemuxerRemuxer=function(i){var t=this._demuxer=new ft(i,this._config);this._remuxer||(this._remuxer=new yt(this._config)),t.onError=this._onDemuxException.bind(this),t.onMediaInfo=this._onMediaInfo.bind(this),t.onMetaDataArrived=this._onMetaDataArrived.bind(this),t.onTimedID3Metadata=this._onTimedID3Metadata.bind(this),t.onPGSSubtitleData=this._onPGSSubtitle.bind(this),t.onSynchronousKLVMetadata=this._onSynchronousKLVMetadata.bind(this),t.onAsynchronousKLVMetadata=this._onAsynchronousKLVMetadata.bind(this),t.onSMPTE2038Metadata=this._onSMPTE2038Metadata.bind(this),t.onSEI=this._onSEI.bind(this),t.onSCTE35Metadata=this._onSCTE35Metadata.bind(this),t.onPESPrivateDataDescriptor=this._onPESPrivateDataDescriptor.bind(this),t.onPESPrivateData=this._onPESPrivateData.bind(this),this._remuxer.bindDataSource(this._demuxer),this._demuxer.bindDataSource(this._ioctl),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},n.prototype._onMediaInfo=function(i){var t=this;this._mediaInfo==null&&(this._mediaInfo=Object.assign({},i),this._mediaInfo.keyframesIndex=null,this._mediaInfo.segments=[],this._mediaInfo.segmentCount=this._mediaDataSource.segments.length,Object.setPrototypeOf(this._mediaInfo,R.default.prototype));var e=Object.assign({},i);Object.setPrototypeOf(e,R.default.prototype),this._mediaInfo.segments[this._currentSegmentIndex]=e,this._reportSegmentMediaInfo(this._currentSegmentIndex),this._pendingSeekTime!=null&&Promise.resolve().then(function(){var a=t._pendingSeekTime;t._pendingSeekTime=null,t.seek(a)})},n.prototype._onMetaDataArrived=function(i){this._emitter.emit(Ie.default.METADATA_ARRIVED,i)},n.prototype._onScriptDataArrived=function(i){this._emitter.emit(Ie.default.SCRIPTDATA_ARRIVED,i)},n.prototype._onTimedID3Metadata=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.dts!=null&&(i.dts-=t),this._emitter.emit(Ie.default.TIMED_ID3_METADATA_ARRIVED,i))},n.prototype._onPGSSubtitle=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.dts!=null&&(i.dts-=t),this._emitter.emit(Ie.default.PGS_SUBTITLE_ARRIVED,i))},n.prototype._onSynchronousKLVMetadata=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.dts!=null&&(i.dts-=t),this._emitter.emit(Ie.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,i))},n.prototype._onAsynchronousKLVMetadata=function(i){this._emitter.emit(Ie.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,i)},n.prototype._onSMPTE2038Metadata=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.dts!=null&&(i.dts-=t),i.nearest_pts!=null&&(i.nearest_pts-=t),this._emitter.emit(Ie.default.SMPTE2038_METADATA_ARRIVED,i))},n.prototype._onSEI=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),this._emitter.emit(Ie.default.SEI_ARRIVED,i))},n.prototype._onSCTE35Metadata=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.nearest_pts!=null&&(i.nearest_pts-=t),this._emitter.emit(Ie.default.SCTE35_METADATA_ARRIVED,i))},n.prototype._onPESPrivateDataDescriptor=function(i){this._emitter.emit(Ie.default.PES_PRIVATE_DATA_DESCRIPTOR,i)},n.prototype._onPESPrivateData=function(i){var t=this._remuxer.getTimestampBase();t!=null&&(i.pts!=null&&(i.pts-=t),i.nearest_pts!=null&&(i.nearest_pts-=t),i.dts!=null&&(i.dts-=t),this._emitter.emit(Ie.default.PES_PRIVATE_DATA_ARRIVED,i))},n.prototype._onIOSeeked=function(){this._remuxer.insertDiscontinuity()},n.prototype._onIOComplete=function(i){var t=i+1;t0&&e[0].originalDts===a&&(a=e[0].pts),this._emitter.emit(Ie.default.RECOMMEND_SEEKPOINT,a)}},n.prototype._enableStatisticsReporter=function(){this._statisticsReporter==null&&(this._statisticsReporter=self.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval))},n.prototype._disableStatisticsReporter=function(){this._statisticsReporter&&(self.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},n.prototype._reportSegmentMediaInfo=function(i){var t=this._mediaInfo.segments[i],e=Object.assign({},t);e.duration=this._mediaInfo.duration,e.segmentCount=this._mediaInfo.segmentCount,delete e.segments,delete e.keyframesIndex,this._emitter.emit(Ie.default.MEDIA_INFO,e)},n.prototype._reportStatisticsInfo=function(){var i={};i.url=this._ioctl.currentURL,i.hasRedirect=this._ioctl.hasRedirect,i.hasRedirect&&(i.redirectedURL=this._ioctl.currentRedirectedURL),i.speed=this._ioctl.currentSpeed,i.loaderType=this._ioctl.loaderType,i.currentSegmentIndex=this._currentSegmentIndex,i.totalSegmentCount=this._mediaDataSource.segments.length,this._emitter.emit(Ie.default.STATISTICS_INFO,i)},n}())},137:function(le,Q,D){D.r(Q),D(856);var X=D(947),P=D(811),_=D(886),S=D(726);Q.default=function(R){var v=null,I=function(te,ee){R.postMessage({msg:"logcat_callback",data:{type:te,logcat:ee}})}.bind(this);function b(te,ee){var Re={msg:S.default.INIT_SEGMENT,data:{type:te,data:ee}};R.postMessage(Re,[ee.data])}function k(te,ee){var Re={msg:S.default.MEDIA_SEGMENT,data:{type:te,data:ee}};R.postMessage(Re,[ee.data])}function w(){var te={msg:S.default.LOADING_COMPLETE};R.postMessage(te)}function O(){var te={msg:S.default.RECOVERED_EARLY_EOF};R.postMessage(te)}function A(te){var ee={msg:S.default.MEDIA_INFO,data:te};R.postMessage(ee)}function G(te){var ee={msg:S.default.METADATA_ARRIVED,data:te};R.postMessage(ee)}function m(te){var ee={msg:S.default.SCRIPTDATA_ARRIVED,data:te};R.postMessage(ee)}function U(te){var ee={msg:S.default.TIMED_ID3_METADATA_ARRIVED,data:te};R.postMessage(ee)}function x(te){var ee={msg:S.default.PGS_SUBTITLE_ARRIVED,data:te};R.postMessage(ee)}function K(te){var ee={msg:S.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,data:te};R.postMessage(ee)}function M(te){var ee={msg:S.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,data:te};R.postMessage(ee)}function u(te){var ee={msg:S.default.SMPTE2038_METADATA_ARRIVED,data:te};R.postMessage(ee)}function h(te){var ee={msg:S.default.SEI_ARRIVED,data:te};R.postMessage(ee)}function p(te){var ee={msg:S.default.SCTE35_METADATA_ARRIVED,data:te};R.postMessage(ee)}function E(te){var ee={msg:S.default.PES_PRIVATE_DATA_DESCRIPTOR,data:te};R.postMessage(ee)}function W(te){var ee={msg:S.default.PES_PRIVATE_DATA_ARRIVED,data:te};R.postMessage(ee)}function z(te){var ee={msg:S.default.STATISTICS_INFO,data:te};R.postMessage(ee)}function se(te,ee){R.postMessage({msg:S.default.IO_ERROR,data:{type:te,info:ee}})}function de(te,ee){R.postMessage({msg:S.default.DEMUX_ERROR,data:{type:te,info:ee}})}function me(te){R.postMessage({msg:S.default.RECOMMEND_SEEKPOINT,data:te})}P.default.install(),R.addEventListener("message",function(te){switch(te.data.cmd){case"init":(v=new _.default(te.data.param[0],te.data.param[1])).on(S.default.IO_ERROR,se.bind(this)),v.on(S.default.DEMUX_ERROR,de.bind(this)),v.on(S.default.INIT_SEGMENT,b.bind(this)),v.on(S.default.MEDIA_SEGMENT,k.bind(this)),v.on(S.default.LOADING_COMPLETE,w.bind(this)),v.on(S.default.RECOVERED_EARLY_EOF,O.bind(this)),v.on(S.default.MEDIA_INFO,A.bind(this)),v.on(S.default.METADATA_ARRIVED,G.bind(this)),v.on(S.default.SCRIPTDATA_ARRIVED,m.bind(this)),v.on(S.default.TIMED_ID3_METADATA_ARRIVED,U.bind(this)),v.on(S.default.PGS_SUBTITLE_ARRIVED,x.bind(this)),v.on(S.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,K.bind(this)),v.on(S.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,M.bind(this)),v.on(S.default.SMPTE2038_METADATA_ARRIVED,u.bind(this)),v.on(S.default.SEI_ARRIVED,h.bind(this)),v.on(S.default.SCTE35_METADATA_ARRIVED,p.bind(this)),v.on(S.default.PES_PRIVATE_DATA_DESCRIPTOR,E.bind(this)),v.on(S.default.PES_PRIVATE_DATA_ARRIVED,W.bind(this)),v.on(S.default.STATISTICS_INFO,z.bind(this)),v.on(S.default.RECOMMEND_SEEKPOINT,me.bind(this));break;case"destroy":v&&(v.destroy(),v=null),R.postMessage({msg:"destroyed"});break;case"start":v.start();break;case"stop":v.stop();break;case"seek":v.seek(te.data.param);break;case"pause":v.pause();break;case"resume":v.resume();break;case"logging_config":var ee=te.data.param;X.default.applyConfig(ee),ee.enableCallback===!0?X.default.addLogListener(I):X.default.removeLogListener(I)}})}},827:function(le,Q,D){D.r(Q),Q.default={OK:"OK",FORMAT_ERROR:"FormatError",FORMAT_UNSUPPORTED:"FormatUnsupported",CODEC_UNSUPPORTED:"CodecUnsupported"}},976:function(le,Q,D){le.exports=D(311).default},653:function(le,Q,D){D.r(Q),D.d(Q,{default:function(){return K}});var X,P=D(856),_=function(){function M(){this._firstCheckpoint=0,this._lastCheckpoint=0,this._intervalBytes=0,this._totalBytes=0,this._lastSecondBytes=0,self.performance&&self.performance.now?this._now=self.performance.now.bind(self.performance):this._now=Date.now}return M.prototype.reset=function(){this._firstCheckpoint=this._lastCheckpoint=0,this._totalBytes=this._intervalBytes=0,this._lastSecondBytes=0},M.prototype.addBytes=function(u){this._firstCheckpoint===0?(this._firstCheckpoint=this._now(),this._lastCheckpoint=this._firstCheckpoint,this._intervalBytes+=u,this._totalBytes+=u):this._now()-this._lastCheckpoint<1000?(this._intervalBytes+=u,this._totalBytes+=u):(this._lastSecondBytes=this._intervalBytes,this._intervalBytes=u,this._totalBytes+=u,this._lastCheckpoint=this._now())},Object.defineProperty(M.prototype,"currentKBps",{get:function(){this.addBytes(0);var u=(this._now()-this._lastCheckpoint)/1000;return u==0&&(u=1),this._intervalBytes/u/1024},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"lastSecondKBps",{get:function(){return this.addBytes(0),this._lastSecondBytes!==0?this._lastSecondBytes/1024:this._now()-this._lastCheckpoint>=500?this.currentKBps:0},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"averageKBps",{get:function(){var u=(this._now()-this._firstCheckpoint)/1000;return this._totalBytes/u/1024},enumerable:!1,configurable:!0}),M}(),S=D(470),R=D(994),v=D(867),I=(X=function(M,u){return X=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,p){h.__proto__=p}||function(h,p){for(var E in p)Object.prototype.hasOwnProperty.call(p,E)&&(h[E]=p[E])},X(M,u)},function(M,u){if(typeof u!="function"&&u!==null)throw TypeError("Class extends value "+String(u)+" is not a constructor or null");function h(){this.constructor=M}X(M,u),M.prototype=u===null?Object.create(u):(h.prototype=u.prototype,new h)}),b=function(M){function u(h,p){var E=M.call(this,"fetch-stream-loader")||this;return E.TAG="FetchStreamLoader",E._seekHandler=h,E._config=p,E._needStash=!0,E._requestAbort=!1,E._abortController=null,E._contentLength=null,E._receivedLength=0,E}return I(u,M),u.isSupported=function(){try{var h=R.default.msedge&&R.default.version.minor>=15048,p=!R.default.msedge||h;return self.fetch&&self.ReadableStream&&p}catch(E){return!1}},u.prototype.destroy=function(){this.isWorking()&&this.abort(),M.prototype.destroy.call(this)},u.prototype.open=function(h,p){var E=this;this._dataSource=h,this._range=p;var W=h.url;this._config.reuseRedirectedURL&&h.redirectedURL!=null&&(W=h.redirectedURL);var z=this._seekHandler.getConfig(W,p),se=new self.Headers;if(typeof z.headers=="object"){var de=z.headers;for(var me in de)de.hasOwnProperty(me)&&se.append(me,de[me])}var te={method:"GET",headers:se,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};if(typeof this._config.headers=="object")for(var me in this._config.headers)se.append(me,this._config.headers[me]);h.cors===!1&&(te.mode="same-origin"),h.withCredentials&&(te.credentials="include"),h.referrerPolicy&&(te.referrerPolicy=h.referrerPolicy),self.AbortController&&(this._abortController=new self.AbortController,te.signal=this._abortController.signal),this._status=S.LoaderStatus.kConnecting,self.fetch(z.url,te).then(function(ee){if(E._requestAbort)return E._status=S.LoaderStatus.kIdle,void ee.body.cancel();if(ee.ok&&ee.status>=200&&ee.status<=299){if(ee.url!==z.url&&E._onURLRedirect){var Re=E._seekHandler.removeURLParameters(ee.url);E._onURLRedirect(Re)}var J=ee.headers.get("Content-Length");return J!=null&&(E._contentLength=parseInt(J),E._contentLength!==0&&E._onContentLengthKnown&&E._onContentLengthKnown(E._contentLength)),E._pump.call(E,ee.body.getReader())}if(E._status=S.LoaderStatus.kError,!E._onError)throw new v.RuntimeException("FetchStreamLoader: Http code invalid, "+ee.status+" "+ee.statusText);E._onError(S.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:ee.status,msg:ee.statusText})}).catch(function(ee){if(!E._abortController||!E._abortController.signal.aborted){if(E._status=S.LoaderStatus.kError,!E._onError)throw ee;E._onError(S.LoaderErrors.EXCEPTION,{code:-1,msg:ee.message})}})},u.prototype.abort=function(){if(this._requestAbort=!0,(this._status!==S.LoaderStatus.kBuffering||!R.default.chrome)&&this._abortController)try{this._abortController.abort()}catch(h){}},u.prototype._pump=function(h){var p=this;return h.read().then(function(E){if(E.done)if(p._contentLength!==null&&p._receivedLength299)){if(this._status=S.LoaderStatus.kError,!this._onError)throw new v.RuntimeException("MozChunkedLoader: Http code invalid, "+p.status+" "+p.statusText);this._onError(S.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:p.status,msg:p.statusText})}else this._status=S.LoaderStatus.kBuffering}},u.prototype._onProgress=function(h){if(this._status!==S.LoaderStatus.kError){this._contentLength===null&&h.total!==null&&h.total!==0&&(this._contentLength=h.total,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength));var p=h.target.response,E=this._range.from+this._receivedLength;this._receivedLength+=p.byteLength,this._onDataArrival&&this._onDataArrival(p,E,this._receivedLength)}},u.prototype._onLoadEnd=function(h){this._requestAbort!==!0?this._status!==S.LoaderStatus.kError&&(this._status=S.LoaderStatus.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1)):this._requestAbort=!1},u.prototype._onXhrError=function(h){this._status=S.LoaderStatus.kError;var p=0,E=null;if(this._contentLength&&h.loaded=this._contentLength&&(E=this._range.from+this._contentLength-1),this._currentRequestRange={from:p,to:E},this._internalOpen(this._dataSource,this._currentRequestRange)},u.prototype._internalOpen=function(h,p){this._lastTimeLoaded=0;var E=h.url;this._config.reuseRedirectedURL&&(this._currentRedirectedURL!=null?E=this._currentRedirectedURL:h.redirectedURL!=null&&(E=h.redirectedURL));var W=this._seekHandler.getConfig(E,p);this._currentRequestURL=W.url;var z=this._xhr=new XMLHttpRequest;if(z.open("GET",W.url,!0),z.responseType="arraybuffer",z.onreadystatechange=this._onReadyStateChange.bind(this),z.onprogress=this._onProgress.bind(this),z.onload=this._onLoad.bind(this),z.onerror=this._onXhrError.bind(this),h.withCredentials&&(z.withCredentials=!0),typeof W.headers=="object"){var se=W.headers;for(var de in se)se.hasOwnProperty(de)&&z.setRequestHeader(de,se[de])}if(typeof this._config.headers=="object")for(var de in se=this._config.headers)se.hasOwnProperty(de)&&z.setRequestHeader(de,se[de]);z.send()},u.prototype.abort=function(){this._requestAbort=!0,this._internalAbort(),this._status=S.LoaderStatus.kComplete},u.prototype._internalAbort=function(){this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr.abort(),this._xhr=null)},u.prototype._onReadyStateChange=function(h){var p=h.target;if(p.readyState===2){if(p.responseURL!=null){var E=this._seekHandler.removeURLParameters(p.responseURL);p.responseURL!==this._currentRequestURL&&E!==this._currentRedirectedURL&&(this._currentRedirectedURL=E,this._onURLRedirect&&this._onURLRedirect(E))}if(p.status>=200&&p.status<=299){if(this._waitForTotalLength)return;this._status=S.LoaderStatus.kBuffering}else{if(this._status=S.LoaderStatus.kError,!this._onError)throw new v.RuntimeException("RangeLoader: Http code invalid, "+p.status+" "+p.statusText);this._onError(S.LoaderErrors.HTTP_STATUS_CODE_INVALID,{code:p.status,msg:p.statusText})}}},u.prototype._onProgress=function(h){if(this._status!==S.LoaderStatus.kError){if(this._contentLength===null){var p=!1;if(this._waitForTotalLength){this._waitForTotalLength=!1,this._totalLengthReceived=!0,p=!0;var E=h.total;this._internalAbort(),E!=null&E!==0&&(this._totalLength=E)}if(this._range.to===-1?this._contentLength=this._totalLength-this._range.from:this._contentLength=this._range.to-this._range.from+1,p)return void this._openSubRange();this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength)}var W=h.loaded-this._lastTimeLoaded;this._lastTimeLoaded=h.loaded,this._speedSampler.addBytes(W)}},u.prototype._normalizeSpeed=function(h){var p=this._chunkSizeKBList,E=p.length-1,W=0,z=0,se=E;if(h=p[W]&&h=3&&(p=this._speedSampler.currentKBps)),p!==0){var E=this._normalizeSpeed(p);this._currentSpeedNormalized!==E&&(this._currentSpeedNormalized=E,this._currentChunkSizeKB=E)}var W=h.target.response,z=this._range.from+this._receivedLength;this._receivedLength+=W.byteLength;var se=!1;this._contentLength!=null&&this._receivedLength0&&this._receivedLength0)for(var z=p.split("&"),se=0;se0;de[0]!==this._startName&&de[0]!==this._endName&&(me&&(W+="&"),W+=z[se])}return W.length===0?h:h+"?"+W},M}(),K=function(){function M(u,h,p){this.TAG="IOController",this._config=h,this._extraData=p,this._stashInitialSize=65536,h.stashInitialSize!=null&&h.stashInitialSize>0&&(this._stashInitialSize=h.stashInitialSize),this._stashUsed=0,this._stashSize=this._stashInitialSize,this._bufferSize=Math.max(this._stashSize,3145728),this._stashBuffer=new ArrayBuffer(this._bufferSize),this._stashByteStart=0,this._enableStash=!0,h.enableStashBuffer===!1&&(this._enableStash=!1),this._loader=null,this._loaderClass=null,this._seekHandler=null,this._dataSource=u,this._isWebSocketURL=/wss?:\/\/(.+?)/.test(u.url),this._refTotalLength=u.filesize?u.filesize:null,this._totalLength=this._refTotalLength,this._fullRequestFlag=!1,this._currentRange=null,this._redirectedURL=null,this._speedNormalized=0,this._speedSampler=new _,this._speedNormalizeList=[32,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096],this._isEarlyEofReconnecting=!1,this._paused=!1,this._resumeFrom=0,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._selectSeekHandler(),this._selectLoader(),this._createLoader()}return M.prototype.destroy=function(){this._loader.isWorking()&&this._loader.abort(),this._loader.destroy(),this._loader=null,this._loaderClass=null,this._dataSource=null,this._stashBuffer=null,this._stashUsed=this._stashSize=this._bufferSize=this._stashByteStart=0,this._currentRange=null,this._speedSampler=null,this._isEarlyEofReconnecting=!1,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._extraData=null},M.prototype.isWorking=function(){return this._loader&&this._loader.isWorking()&&!this._paused},M.prototype.isPaused=function(){return this._paused},Object.defineProperty(M.prototype,"status",{get:function(){return this._loader.status},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"extraData",{get:function(){return this._extraData},set:function(u){this._extraData=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(u){this._onDataArrival=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onSeeked",{get:function(){return this._onSeeked},set:function(u){this._onSeeked=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onError",{get:function(){return this._onError},set:function(u){this._onError=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onComplete",{get:function(){return this._onComplete},set:function(u){this._onComplete=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onRedirect",{get:function(){return this._onRedirect},set:function(u){this._onRedirect=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"onRecoveredEarlyEof",{get:function(){return this._onRecoveredEarlyEof},set:function(u){this._onRecoveredEarlyEof=u},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"currentURL",{get:function(){return this._dataSource.url},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"hasRedirect",{get:function(){return this._redirectedURL!=null||this._dataSource.redirectedURL!=null},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"currentRedirectedURL",{get:function(){return this._redirectedURL||this._dataSource.redirectedURL},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"currentSpeed",{get:function(){return this._loaderClass===A?this._loader.currentSpeed:this._speedSampler.lastSecondKBps},enumerable:!1,configurable:!0}),Object.defineProperty(M.prototype,"loaderType",{get:function(){return this._loader.type},enumerable:!1,configurable:!0}),M.prototype._selectSeekHandler=function(){var u=this._config;if(u.seekType==="range")this._seekHandler=new U(this._config.rangeLoadZeroStart);else if(u.seekType==="param"){var h=u.seekParamStart||"bstart",p=u.seekParamEnd||"bend";this._seekHandler=new x(h,p)}else{if(u.seekType!=="custom")throw new v.InvalidArgumentException("Invalid seekType in config: ".concat(u.seekType));if(typeof u.customSeekHandler!="function")throw new v.InvalidArgumentException("Custom seekType specified in config but invalid customSeekHandler!");this._seekHandler=new u.customSeekHandler}},M.prototype._selectLoader=function(){if(this._config.customLoader!=null)this._loaderClass=this._config.customLoader;else if(this._isWebSocketURL)this._loaderClass=m;else if(b.isSupported())this._loaderClass=b;else if(w.isSupported())this._loaderClass=w;else{if(!A.isSupported())throw new v.RuntimeException("Your browser doesn't support xhr with arraybuffer responseType!");this._loaderClass=A}},M.prototype._createLoader=function(){this._loader=new this._loaderClass(this._seekHandler,this._config),this._loader.needStashBuffer===!1&&(this._enableStash=!1),this._loader.onContentLengthKnown=this._onContentLengthKnown.bind(this),this._loader.onURLRedirect=this._onURLRedirect.bind(this),this._loader.onDataArrival=this._onLoaderChunkArrival.bind(this),this._loader.onComplete=this._onLoaderComplete.bind(this),this._loader.onError=this._onLoaderError.bind(this)},M.prototype.open=function(u){this._currentRange={from:0,to:-1},u&&(this._currentRange.from=u),this._speedSampler.reset(),u||(this._fullRequestFlag=!0),this._loader.open(this._dataSource,Object.assign({},this._currentRange))},M.prototype.abort=function(){this._loader.abort(),this._paused&&(this._paused=!1,this._resumeFrom=0)},M.prototype.pause=function(){this.isWorking()&&(this._loader.abort(),this._stashUsed!==0?(this._resumeFrom=this._stashByteStart,this._currentRange.to=this._stashByteStart-1):this._resumeFrom=this._currentRange.to+1,this._stashUsed=0,this._stashByteStart=0,this._paused=!0)},M.prototype.resume=function(){if(this._paused){this._paused=!1;var u=this._resumeFrom;this._resumeFrom=0,this._internalSeek(u,!0)}},M.prototype.seek=function(u){this._paused=!1,this._stashUsed=0,this._stashByteStart=0,this._internalSeek(u,!0)},M.prototype._internalSeek=function(u,h){this._loader.isWorking()&&this._loader.abort(),this._flushStashBuffer(h),this._loader.destroy(),this._loader=null;var p={from:u,to:-1};this._currentRange={from:p.from,to:-1},this._speedSampler.reset(),this._stashSize=this._stashInitialSize,this._createLoader(),this._loader.open(this._dataSource,p),this._onSeeked&&this._onSeeked()},M.prototype.updateUrl=function(u){if(!u||typeof u!="string"||u.length===0)throw new v.InvalidArgumentException("Url must be a non-empty string!");this._dataSource.url=u},M.prototype._expandBuffer=function(u){for(var h=this._stashSize;h+10485760){var E=new Uint8Array(this._stashBuffer,0,this._stashUsed);new Uint8Array(p,0,h).set(E,0)}this._stashBuffer=p,this._bufferSize=h}},M.prototype._normalizeSpeed=function(u){var h=this._speedNormalizeList,p=h.length-1,E=0,W=0,z=p;if(u=h[E]&&u=512&&u<=1024?Math.floor(1.5*u):2*u)>8192&&(h=8192);var p=1024*h+1048576;this._bufferSize0){var z=this._stashBuffer.slice(0,this._stashUsed);(me=this._dispatchChunks(z,this._stashByteStart))0&&(te=new Uint8Array(z,me),de.set(te,0),this._stashUsed=te.byteLength,this._stashByteStart+=me):(this._stashUsed=0,this._stashByteStart+=me),this._stashUsed+u.byteLength>this._bufferSize&&(this._expandBuffer(this._stashUsed+u.byteLength),de=new Uint8Array(this._stashBuffer,0,this._bufferSize)),de.set(new Uint8Array(u),this._stashUsed),this._stashUsed+=u.byteLength}else(me=this._dispatchChunks(u,h))this._bufferSize&&(this._expandBuffer(se),de=new Uint8Array(this._stashBuffer,0,this._bufferSize)),de.set(new Uint8Array(u,me),0),this._stashUsed+=se,this._stashByteStart=h+me);else if(this._stashUsed===0){var se;(me=this._dispatchChunks(u,h))this._bufferSize&&this._expandBuffer(se),(de=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(u,me),0),this._stashUsed+=se,this._stashByteStart=h+me)}else{var de,me;if(this._stashUsed+u.byteLength>this._bufferSize&&this._expandBuffer(this._stashUsed+u.byteLength),(de=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(u),this._stashUsed),this._stashUsed+=u.byteLength,(me=this._dispatchChunks(this._stashBuffer.slice(0,this._stashUsed),this._stashByteStart))0){var te=new Uint8Array(this._stashBuffer,me);de.set(te,0)}this._stashUsed-=me,this._stashByteStart+=me}}},M.prototype._flushStashBuffer=function(u){if(this._stashUsed>0){var h=this._stashBuffer.slice(0,this._stashUsed),p=this._dispatchChunks(h,this._stashByteStart),E=h.byteLength-p;if(p0){var W=new Uint8Array(this._stashBuffer,0,this._bufferSize),z=new Uint8Array(h,p);W.set(z,0),this._stashUsed=z.byteLength,this._stashByteStart+=p}return 0}P.default.w(this.TAG,"".concat(E," bytes unconsumed data remain when flush buffer, dropped"))}return this._stashUsed=0,this._stashByteStart=0,E}return 0},M.prototype._onLoaderComplete=function(u,h){this._flushStashBuffer(!0),this._onComplete&&this._onComplete(this._extraData)},M.prototype._onLoaderError=function(u,h){switch(P.default.e(this.TAG,"Loader error, code = ".concat(h.code,", msg = ").concat(h.msg)),this._flushStashBuffer(!1),this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,u=S.LoaderErrors.UNRECOVERABLE_EARLY_EOF),u){case S.LoaderErrors.EARLY_EOF:if(!this._config.isLive&&this._totalLength){var p=this._currentRange.to+1;return void(p0){var fe=this._media_element.buffered.start(0);(fe<1&&c0){var fe=j.start(0);if(fe<1&&C=fe&&c0&&this._suspendTransmuxerIfBufferedPositionExceeded(j)},L.prototype._suspendTransmuxerIfBufferedPositionExceeded=function(c){c>=this._media_element.currentTime+this._config.lazyLoadMaxDuration&&!this._paused&&(b.default.v(this.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),this.suspendTransmuxer(),this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate))},L.prototype.suspendTransmuxer=function(){this._paused=!0,this._on_pause_transmuxer()},L.prototype._resumeTransmuxerIfNeeded=function(){for(var c=this._media_element.buffered,C=this._media_element.currentTime,j=this._config.lazyLoadRecoverDuration,fe=!1,re=0;re=V&&C=Y-j&&(fe=!0);break}}fe&&(b.default.v(this.TAG,"Continue loading from paused position"),this.resumeTransmuxer(),this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate))},L.prototype.resumeTransmuxer=function(){this._paused=!1,this._on_resume_transmuxer()},L}(),E=function(){function L(c,C){this.TAG="StartupStallJumper",this._media_element=null,this._on_direct_seek=null,this._canplay_received=!1,this.e=null,this._media_element=c,this._on_direct_seek=C,this.e={onMediaCanPlay:this._onMediaCanPlay.bind(this),onMediaStalled:this._onMediaStalled.bind(this),onMediaProgress:this._onMediaProgress.bind(this)},this._media_element.addEventListener("canplay",this.e.onMediaCanPlay),this._media_element.addEventListener("stalled",this.e.onMediaStalled),this._media_element.addEventListener("progress",this.e.onMediaProgress)}return L.prototype.destroy=function(){this._media_element.removeEventListener("canplay",this.e.onMediaCanPlay),this._media_element.removeEventListener("stalled",this.e.onMediaStalled),this._media_element.removeEventListener("progress",this.e.onMediaProgress),this._media_element=null,this._on_direct_seek=null},L.prototype._onMediaCanPlay=function(c){this._canplay_received=!0,this._media_element.removeEventListener("canplay",this.e.onMediaCanPlay)},L.prototype._onMediaStalled=function(c){this._detectAndFixStuckPlayback(!0)},L.prototype._onMediaProgress=function(c){this._detectAndFixStuckPlayback()},L.prototype._detectAndFixStuckPlayback=function(c){var C=this._media_element,j=C.buffered;c||!this._canplay_received||C.readyState<2?j.length>0&&C.currentTimethis._config.liveBufferLatencyMaxLatency&&fe-C>this._config.liveBufferLatencyMaxLatency){var re=fe-this._config.liveBufferLatencyMinRemain;this._on_direct_seek(re)}}},L}(),z=function(){function L(c,C){this._config=null,this._media_element=null,this.e=null,this._config=c,this._media_element=C,this.e={onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this)},this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate)}return L.prototype.destroy=function(){this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element=null,this._config=null},L.prototype._onMediaTimeUpdate=function(c){if(this._config.isLive&&this._config.liveSync){var C=this._getCurrentLatency();if(C>this._config.liveSyncMaxLatency){var j=Math.min(2,Math.max(1,this._config.liveSyncPlaybackRate));this._media_element.playbackRate=j}else C>this._config.liveSyncTargetLatency||this._media_element.playbackRate!==1&&this._media_element.playbackRate!==0&&(this._media_element.playbackRate=1)}},L.prototype._getCurrentLatency=function(){if(!this._media_element)return 0;var c=this._media_element.buffered,C=this._media_element.currentTime;return c.length==0?0:c.end(c.length-1)-C},L}(),se=function(){function L(c,C){this.TAG="PlayerEngineMainThread",this._emitter=new k,this._media_element=null,this._mse_controller=null,this._transmuxer=null,this._pending_seek_time=null,this._seeking_handler=null,this._loading_controller=null,this._startup_stall_jumper=null,this._live_latency_chaser=null,this._live_latency_synchronizer=null,this._mse_source_opened=!1,this._has_pending_load=!1,this._loaded_metadata_received=!1,this._media_info=null,this._statistics_info=null,this.e=null,this._media_data_source=c,this._config=S(),typeof C=="object"&&Object.assign(this._config,C),c.isLive===!0&&(this._config.isLive=!0),this.e={onMediaLoadedMetadata:this._onMediaLoadedMetadata.bind(this)}}return L.prototype.destroy=function(){this._emitter.emit(A.default.DESTROYING),this._transmuxer&&this.unload(),this._media_element&&this.detachMediaElement(),this.e=null,this._media_data_source=null,this._emitter.removeAllListeners(),this._emitter=null},L.prototype.on=function(c,C){var j=this;this._emitter.addListener(c,C),c===A.default.MEDIA_INFO&&this._media_info?Promise.resolve().then(function(){return j._emitter.emit(A.default.MEDIA_INFO,j.mediaInfo)}):c==A.default.STATISTICS_INFO&&this._statistics_info&&Promise.resolve().then(function(){return j._emitter.emit(A.default.STATISTICS_INFO,j.statisticsInfo)})},L.prototype.off=function(c,C){this._emitter.removeListener(c,C)},L.prototype.attachMediaElement=function(c){var C=this;this._media_element=c,c.src="",c.removeAttribute("src"),c.srcObject=null,c.load(),c.addEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._mse_controller=new O.default(this._config),this._mse_controller.on(m.default.UPDATE_END,this._onMSEUpdateEnd.bind(this)),this._mse_controller.on(m.default.BUFFER_FULL,this._onMSEBufferFull.bind(this)),this._mse_controller.on(m.default.SOURCE_OPEN,this._onMSESourceOpen.bind(this)),this._mse_controller.on(m.default.ERROR,this._onMSEError.bind(this)),this._mse_controller.on(m.default.START_STREAMING,this._onMSEStartStreaming.bind(this)),this._mse_controller.on(m.default.END_STREAMING,this._onMSEEndStreaming.bind(this)),this._mse_controller.initialize({getCurrentTime:function(){return C._media_element.currentTime},getReadyState:function(){return C._media_element.readyState}}),this._mse_controller.isManagedMediaSource()?(c.disableRemotePlayback=!0,c.srcObject=this._mse_controller.getObject()):c.src=this._mse_controller.getObjectURL()},L.prototype.detachMediaElement=function(){this._media_element&&(this._mse_controller.shutdown(),this._media_element.removeEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element=null,this._mse_controller.revokeObjectURL()),this._mse_controller&&(this._mse_controller.destroy(),this._mse_controller=null)},L.prototype.load=function(){var c=this;if(!this._media_element)throw new x.IllegalStateException("HTMLMediaElement must be attached before load()!");if(this._transmuxer)throw new x.IllegalStateException("load() has been called, please call unload() first!");this._has_pending_load||(!this._config.deferLoadAfterSourceOpen||this._mse_source_opened?(this._transmuxer=new G.default(this._media_data_source,this._config),this._transmuxer.on(K.default.INIT_SEGMENT,function(C,j){c._mse_controller.appendInitSegment(j)}),this._transmuxer.on(K.default.MEDIA_SEGMENT,function(C,j){c._mse_controller.appendMediaSegment(j),!c._config.isLive&&C==="video"&&j.data&&j.data.byteLength>0&&"info"in j&&c._seeking_handler.appendSyncPoints(j.info.syncPoints),c._loading_controller.notifyBufferedPositionChanged(j.info.endDts/1000)}),this._transmuxer.on(K.default.LOADING_COMPLETE,function(){c._mse_controller.endOfStream(),c._emitter.emit(A.default.LOADING_COMPLETE)}),this._transmuxer.on(K.default.RECOVERED_EARLY_EOF,function(){c._emitter.emit(A.default.RECOVERED_EARLY_EOF)}),this._transmuxer.on(K.default.IO_ERROR,function(C,j){c._emitter.emit(A.default.ERROR,U.ErrorTypes.NETWORK_ERROR,C,j)}),this._transmuxer.on(K.default.DEMUX_ERROR,function(C,j){c._emitter.emit(A.default.ERROR,U.ErrorTypes.MEDIA_ERROR,C,j)}),this._transmuxer.on(K.default.MEDIA_INFO,function(C){c._media_info=C,c._emitter.emit(A.default.MEDIA_INFO,Object.assign({},C))}),this._transmuxer.on(K.default.STATISTICS_INFO,function(C){c._statistics_info=c._fillStatisticsInfo(C),c._emitter.emit(A.default.STATISTICS_INFO,Object.assign({},C))}),this._transmuxer.on(K.default.RECOMMEND_SEEKPOINT,function(C){c._media_element&&!c._config.accurateSeek&&c._seeking_handler.directSeek(C/1000)}),this._transmuxer.on(K.default.METADATA_ARRIVED,function(C){c._emitter.emit(A.default.METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.SCRIPTDATA_ARRIVED,function(C){c._emitter.emit(A.default.SCRIPTDATA_ARRIVED,C)}),this._transmuxer.on(K.default.TIMED_ID3_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.TIMED_ID3_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.PGS_SUBTITLE_ARRIVED,function(C){c._emitter.emit(A.default.PGS_SUBTITLE_ARRIVED,C)}),this._transmuxer.on(K.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.SYNCHRONOUS_KLV_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.ASYNCHRONOUS_KLV_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.SMPTE2038_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.SMPTE2038_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.SEI_ARRIVED,function(C){c._emitter.emit(A.default.SEI_ARRIVED,C)}),this._transmuxer.on(K.default.SCTE35_METADATA_ARRIVED,function(C){c._emitter.emit(A.default.SCTE35_METADATA_ARRIVED,C)}),this._transmuxer.on(K.default.PES_PRIVATE_DATA_DESCRIPTOR,function(C){c._emitter.emit(A.default.PES_PRIVATE_DATA_DESCRIPTOR,C)}),this._transmuxer.on(K.default.PES_PRIVATE_DATA_ARRIVED,function(C){c._emitter.emit(A.default.PES_PRIVATE_DATA_ARRIVED,C)}),this._seeking_handler=new h(this._config,this._media_element,this._onRequiredUnbufferedSeek.bind(this)),this._loading_controller=new p(this._config,this._media_element,this._onRequestPauseTransmuxer.bind(this),this._onRequestResumeTransmuxer.bind(this)),this._startup_stall_jumper=new E(this._media_element,this._onRequestDirectSeek.bind(this)),this._config.isLive&&this._config.liveBufferLatencyChasing&&(this._live_latency_chaser=new W(this._config,this._media_element,this._onRequestDirectSeek.bind(this))),this._config.isLive&&this._config.liveSync&&(this._live_latency_synchronizer=new z(this._config,this._media_element)),this._media_element.readyState>0&&this._seeking_handler.directSeek(0),this._transmuxer.open()):this._has_pending_load=!0)},L.prototype.unload=function(){var c,C,j,fe,re,V,Y,ie,oe;(c=this._media_element)===null||c===void 0||c.pause(),(C=this._live_latency_synchronizer)===null||C===void 0||C.destroy(),this._live_latency_synchronizer=null,(j=this._live_latency_chaser)===null||j===void 0||j.destroy(),this._live_latency_chaser=null,(fe=this._startup_stall_jumper)===null||fe===void 0||fe.destroy(),this._startup_stall_jumper=null,(re=this._loading_controller)===null||re===void 0||re.destroy(),this._loading_controller=null,(V=this._seeking_handler)===null||V===void 0||V.destroy(),this._seeking_handler=null,(Y=this._mse_controller)===null||Y===void 0||Y.flush(),(ie=this._transmuxer)===null||ie===void 0||ie.close(),(oe=this._transmuxer)===null||oe===void 0||oe.destroy(),this._transmuxer=null},L.prototype.play=function(){return this._media_element.play()},L.prototype.pause=function(){this._media_element.pause()},L.prototype.seek=function(c){this._media_element&&this._seeking_handler?this._seeking_handler.seek(c):this._pending_seek_time=c},Object.defineProperty(L.prototype,"mediaInfo",{get:function(){return Object.assign({},this._media_info)},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"statisticsInfo",{get:function(){return Object.assign({},this._statistics_info)},enumerable:!1,configurable:!0}),L.prototype._onMSESourceOpen=function(){this._mse_source_opened=!0,this._has_pending_load&&(this._has_pending_load=!1,this.load())},L.prototype._onMSEUpdateEnd=function(){this._config.isLive&&this._config.liveBufferLatencyChasing&&this._live_latency_chaser&&this._live_latency_chaser.notifyBufferedRangeUpdate(),this._loading_controller.notifyBufferedPositionChanged()},L.prototype._onMSEBufferFull=function(){b.default.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._loading_controller.suspendTransmuxer()},L.prototype._onMSEError=function(c){this._emitter.emit(A.default.ERROR,U.ErrorTypes.MEDIA_ERROR,U.ErrorDetails.MEDIA_MSE_ERROR,c)},L.prototype._onMSEStartStreaming=function(){this._loaded_metadata_received&&(this._config.isLive||(b.default.v(this.TAG,"Resume transmuxing task due to ManagedMediaSource onStartStreaming"),this._loading_controller.resumeTransmuxer()))},L.prototype._onMSEEndStreaming=function(){this._config.isLive||(b.default.v(this.TAG,"Suspend transmuxing task due to ManagedMediaSource onEndStreaming"),this._loading_controller.suspendTransmuxer())},L.prototype._onMediaLoadedMetadata=function(c){this._loaded_metadata_received=!0,this._pending_seek_time!=null&&(this._seeking_handler.seek(this._pending_seek_time),this._pending_seek_time=null)},L.prototype._onRequestDirectSeek=function(c){this._seeking_handler.directSeek(c)},L.prototype._onRequiredUnbufferedSeek=function(c){this._mse_controller.flush(),this._transmuxer.seek(c)},L.prototype._onRequestPauseTransmuxer=function(){this._transmuxer.pause()},L.prototype._onRequestResumeTransmuxer=function(){this._transmuxer.resume()},L.prototype._fillStatisticsInfo=function(c){if(c.playerType="MSEPlayer",!(this._media_element instanceof HTMLVideoElement))return c;var C=!0,j=0,fe=0;if(this._media_element.getVideoPlaybackQuality){var re=this._media_element.getVideoPlaybackQuality();j=re.totalVideoFrames,fe=re.droppedVideoFrames}else this._media_element.webkitDecodedFrameCount!=null?(j=this._media_element.webkitDecodedFrameCount,fe=this._media_element.webkitDroppedFrameCount):C=!1;return C&&(c.decodedFrames=j,c.droppedFrames=fe),c},L}(),de=D(861),me=D(947),te=function(){function L(c,C){this.TAG="PlayerEngineDedicatedThread",this._emitter=new k,this._media_element=null,this._worker_destroying=!1,this._seeking_handler=null,this._loading_controller=null,this._startup_stall_jumper=null,this._live_latency_chaser=null,this._live_latency_synchronizer=null,this._pending_seek_time=null,this._media_info=null,this._statistics_info=null,this.e=null,this._media_data_source=c,this._config=S(),typeof C=="object"&&Object.assign(this._config,C),c.isLive===!0&&(this._config.isLive=!0),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this),onMediaLoadedMetadata:this._onMediaLoadedMetadata.bind(this),onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this),onMediaReadyStateChanged:this._onMediaReadyStateChange.bind(this)},me.default.registerListener(this.e.onLoggingConfigChanged),this._worker=de(877,{all:!0}),this._worker.addEventListener("message",this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:"init",media_data_source:this._media_data_source,config:this._config}),this._worker.postMessage({cmd:"logging_config",logging_config:me.default.getConfig()})}return L.isSupported=function(){return!!(self.Worker&&(self.MediaSource&&("canConstructInDedicatedWorker"in self.MediaSource)&&self.MediaSource.canConstructInDedicatedWorker===!0||self.ManagedMediaSource&&("canConstructInDedicatedWorker"in self.ManagedMediaSource)&&self.ManagedMediaSource.canConstructInDedicatedWorker===!0))},L.prototype.destroy=function(){this._emitter.emit(A.default.DESTROYING),this.unload(),this.detachMediaElement(),this._worker_destroying=!0,this._worker.postMessage({cmd:"destroy"}),me.default.removeListener(this.e.onLoggingConfigChanged),this.e=null,this._media_data_source=null,this._emitter.removeAllListeners(),this._emitter=null},L.prototype.on=function(c,C){var j=this;this._emitter.addListener(c,C),c===A.default.MEDIA_INFO&&this._media_info?Promise.resolve().then(function(){return j._emitter.emit(A.default.MEDIA_INFO,j.mediaInfo)}):c==A.default.STATISTICS_INFO&&this._statistics_info&&Promise.resolve().then(function(){return j._emitter.emit(A.default.STATISTICS_INFO,j.statisticsInfo)})},L.prototype.off=function(c,C){this._emitter.removeListener(c,C)},L.prototype.attachMediaElement=function(c){this._media_element=c,this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element.addEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element.addEventListener("readystatechange",this.e.onMediaReadyStateChanged),this._worker.postMessage({cmd:"initialize_mse"})},L.prototype.detachMediaElement=function(){this._worker.postMessage({cmd:"shutdown_mse"}),this._media_element&&(this._media_element.removeEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element.removeEventListener("readystatechange",this.e.onMediaReadyStateChanged),this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element=null)},L.prototype.load=function(){this._worker.postMessage({cmd:"load"}),this._seeking_handler=new h(this._config,this._media_element,this._onRequiredUnbufferedSeek.bind(this)),this._loading_controller=new p(this._config,this._media_element,this._onRequestPauseTransmuxer.bind(this),this._onRequestResumeTransmuxer.bind(this)),this._startup_stall_jumper=new E(this._media_element,this._onRequestDirectSeek.bind(this)),this._config.isLive&&this._config.liveBufferLatencyChasing&&(this._live_latency_chaser=new W(this._config,this._media_element,this._onRequestDirectSeek.bind(this))),this._config.isLive&&this._config.liveSync&&(this._live_latency_synchronizer=new z(this._config,this._media_element)),this._media_element.readyState>0&&this._seeking_handler.directSeek(0)},L.prototype.unload=function(){var c,C,j,fe,re,V;(c=this._media_element)===null||c===void 0||c.pause(),this._worker.postMessage({cmd:"unload"}),(C=this._live_latency_synchronizer)===null||C===void 0||C.destroy(),this._live_latency_synchronizer=null,(j=this._live_latency_chaser)===null||j===void 0||j.destroy(),this._live_latency_chaser=null,(fe=this._startup_stall_jumper)===null||fe===void 0||fe.destroy(),this._startup_stall_jumper=null,(re=this._loading_controller)===null||re===void 0||re.destroy(),this._loading_controller=null,(V=this._seeking_handler)===null||V===void 0||V.destroy(),this._seeking_handler=null},L.prototype.play=function(){return this._media_element.play()},L.prototype.pause=function(){this._media_element.pause()},L.prototype.seek=function(c){this._media_element&&this._seeking_handler?this._seeking_handler.seek(c):this._pending_seek_time=c},Object.defineProperty(L.prototype,"mediaInfo",{get:function(){return Object.assign({},this._media_info)},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"statisticsInfo",{get:function(){return Object.assign({},this._statistics_info)},enumerable:!1,configurable:!0}),L.prototype._onLoggingConfigChanged=function(c){var C;(C=this._worker)===null||C===void 0||C.postMessage({cmd:"logging_config",logging_config:c})},L.prototype._onMSEUpdateEnd=function(){this._config.isLive&&this._config.liveBufferLatencyChasing&&this._live_latency_chaser&&this._live_latency_chaser.notifyBufferedRangeUpdate(),this._loading_controller.notifyBufferedPositionChanged()},L.prototype._onMSEBufferFull=function(){b.default.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._loading_controller.suspendTransmuxer()},L.prototype._onMediaLoadedMetadata=function(c){this._pending_seek_time!=null&&(this._seeking_handler.seek(this._pending_seek_time),this._pending_seek_time=null)},L.prototype._onRequestDirectSeek=function(c){this._seeking_handler.directSeek(c)},L.prototype._onRequiredUnbufferedSeek=function(c){this._worker.postMessage({cmd:"unbuffered_seek",milliseconds:c})},L.prototype._onRequestPauseTransmuxer=function(){this._worker.postMessage({cmd:"pause_transmuxer"})},L.prototype._onRequestResumeTransmuxer=function(){this._worker.postMessage({cmd:"resume_transmuxer"})},L.prototype._onMediaTimeUpdate=function(c){this._worker.postMessage({cmd:"timeupdate",current_time:c.target.currentTime})},L.prototype._onMediaReadyStateChange=function(c){this._worker.postMessage({cmd:"readystatechange",ready_state:c.target.readyState})},L.prototype._onWorkerMessage=function(c){var C,j=c.data,fe=j.msg;if(fe=="destroyed"||this._worker_destroying)return this._worker_destroying=!1,(C=this._worker)===null||C===void 0||C.terminate(),void(this._worker=null);switch(fe){case"mse_init":var re=j;typeof self.ManagedMediaSource=="function"&&typeof self.MediaSource!="function"&&(this._media_element.disableRemotePlayback=!0),this._media_element.srcObject=re.handle;break;case"mse_event":(re=j).event==m.default.UPDATE_END?this._onMSEUpdateEnd():re.event==m.default.BUFFER_FULL&&this._onMSEBufferFull();break;case"transmuxing_event":if((re=j).event==K.default.MEDIA_INFO){var V=j;this._media_info=V.info,this._emitter.emit(A.default.MEDIA_INFO,Object.assign({},V.info))}else if(re.event==K.default.STATISTICS_INFO){var Y=j;this._statistics_info=this._fillStatisticsInfo(Y.info),this._emitter.emit(A.default.STATISTICS_INFO,Object.assign({},Y.info))}else if(re.event==K.default.RECOMMEND_SEEKPOINT){var ie=j;this._media_element&&!this._config.accurateSeek&&this._seeking_handler.directSeek(ie.milliseconds/1000)}break;case"player_event":if((re=j).event==A.default.ERROR){var oe=j;this._emitter.emit(A.default.ERROR,oe.error_type,oe.error_detail,oe.info)}else if("extraData"in re){var ue=j;this._emitter.emit(ue.event,ue.extraData)}break;case"logcat_callback":re=j,b.default.emitter.emit("log",re.type,re.logcat);break;case"buffered_position_changed":re=j,this._loading_controller.notifyBufferedPositionChanged(re.buffered_position_milliseconds/1000)}},L.prototype._fillStatisticsInfo=function(c){if(c.playerType="MSEPlayer",!(this._media_element instanceof HTMLVideoElement))return c;var C=!0,j=0,fe=0;if(this._media_element.getVideoPlaybackQuality){var re=this._media_element.getVideoPlaybackQuality();j=re.totalVideoFrames,fe=re.droppedVideoFrames}else this._media_element.webkitDecodedFrameCount!=null?(j=this._media_element.webkitDecodedFrameCount,fe=this._media_element.webkitDroppedFrameCount):C=!1;return C&&(c.decodedFrames=j,c.droppedFrames=fe),c},L}(),ee=function(){function L(c,C){this.TAG="MSEPlayer",this._type="MSEPlayer",this._media_element=null,this._player_engine=null;var j=c.type.toLowerCase();if(j!=="mse"&&j!=="mpegts"&&j!=="m2ts"&&j!=="flv")throw new x.InvalidArgumentException("MSEPlayer requires an mpegts/m2ts/flv MediaDataSource input!");if(C&&C.enableWorkerForMSE&&te.isSupported())try{this._player_engine=new te(c,C)}catch(fe){b.default.e(this.TAG,"Error while initializing PlayerEngineDedicatedThread, fallback to PlayerEngineMainThread"),this._player_engine=new se(c,C)}else this._player_engine=new se(c,C)}return L.prototype.destroy=function(){this._player_engine.destroy(),this._player_engine=null,this._media_element=null},L.prototype.on=function(c,C){this._player_engine.on(c,C)},L.prototype.off=function(c,C){this._player_engine.off(c,C)},L.prototype.attachMediaElement=function(c){this._media_element=c,this._player_engine.attachMediaElement(c)},L.prototype.detachMediaElement=function(){this._media_element=null,this._player_engine.detachMediaElement()},L.prototype.load=function(){this._player_engine.load()},L.prototype.unload=function(){this._player_engine.unload()},L.prototype.play=function(){return this._player_engine.play()},L.prototype.pause=function(){this._player_engine.pause()},Object.defineProperty(L.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"buffered",{get:function(){return this._media_element.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"duration",{get:function(){return this._media_element.duration},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"volume",{get:function(){return this._media_element.volume},set:function(c){this._media_element.volume=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"muted",{get:function(){return this._media_element.muted},set:function(c){this._media_element.muted=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"currentTime",{get:function(){return this._media_element?this._media_element.currentTime:0},set:function(c){this._player_engine.seek(c)},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"mediaInfo",{get:function(){return this._player_engine.mediaInfo},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"statisticsInfo",{get:function(){return this._player_engine.statisticsInfo},enumerable:!1,configurable:!0}),L}(),Re=function(){function L(c,C){this.TAG="NativePlayer",this._type="NativePlayer",this._emitter=new(w()),this._config=S(),typeof C=="object"&&Object.assign(this._config,C);var j=c.type.toLowerCase();if(j==="mse"||j==="mpegts"||j==="m2ts"||j==="flv")throw new x.InvalidArgumentException("NativePlayer does't support mse/mpegts/m2ts/flv MediaDataSource input!");if(c.hasOwnProperty("segments"))throw new x.InvalidArgumentException("NativePlayer(".concat(c.type,") doesn't support multipart playback!"));this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this)},this._pendingSeekTime=null,this._statisticsReporter=null,this._mediaDataSource=c,this._mediaElement=null}return L.prototype.destroy=function(){this._emitter.emit(A.default.DESTROYING),this._mediaElement&&(this.unload(),this.detachMediaElement()),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null},L.prototype.on=function(c,C){var j=this;c===A.default.MEDIA_INFO?this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(function(){j._emitter.emit(A.default.MEDIA_INFO,j.mediaInfo)}):c===A.default.STATISTICS_INFO&&this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(function(){j._emitter.emit(A.default.STATISTICS_INFO,j.statisticsInfo)}),this._emitter.addListener(c,C)},L.prototype.off=function(c,C){this._emitter.removeListener(c,C)},L.prototype.attachMediaElement=function(c){if(this._mediaElement=c,c.addEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._pendingSeekTime!=null)try{c.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch(C){}},L.prototype.detachMediaElement=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src"),this._mediaElement.removeEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._mediaElement=null),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},L.prototype.load=function(){if(!this._mediaElement)throw new x.IllegalStateException("HTMLMediaElement must be attached before load()!");this._mediaElement.src=this._mediaDataSource.url,this._mediaElement.readyState>0&&(this._mediaElement.currentTime=0),this._mediaElement.preload="auto",this._mediaElement.load(),this._statisticsReporter=window.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval)},L.prototype.unload=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src")),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},L.prototype.play=function(){return this._mediaElement.play()},L.prototype.pause=function(){this._mediaElement.pause()},Object.defineProperty(L.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"buffered",{get:function(){return this._mediaElement.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"duration",{get:function(){return this._mediaElement.duration},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"volume",{get:function(){return this._mediaElement.volume},set:function(c){this._mediaElement.volume=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"muted",{get:function(){return this._mediaElement.muted},set:function(c){this._mediaElement.muted=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"currentTime",{get:function(){return this._mediaElement?this._mediaElement.currentTime:0},set:function(c){this._mediaElement?this._mediaElement.currentTime=c:this._pendingSeekTime=c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"mediaInfo",{get:function(){var c={mimeType:(this._mediaElement instanceof HTMLAudioElement?"audio/":"video/")+this._mediaDataSource.type};return this._mediaElement&&(c.duration=Math.floor(1000*this._mediaElement.duration),this._mediaElement instanceof HTMLVideoElement&&(c.width=this._mediaElement.videoWidth,c.height=this._mediaElement.videoHeight)),c},enumerable:!1,configurable:!0}),Object.defineProperty(L.prototype,"statisticsInfo",{get:function(){var c={playerType:this._type,url:this._mediaDataSource.url};if(!(this._mediaElement instanceof HTMLVideoElement))return c;var C=!0,j=0,fe=0;if(this._mediaElement.getVideoPlaybackQuality){var re=this._mediaElement.getVideoPlaybackQuality();j=re.totalVideoFrames,fe=re.droppedVideoFrames}else this._mediaElement.webkitDecodedFrameCount!=null?(j=this._mediaElement.webkitDecodedFrameCount,fe=this._mediaElement.webkitDroppedFrameCount):C=!1;return C&&(c.decodedFrames=j,c.droppedFrames=fe),c},enumerable:!1,configurable:!0}),L.prototype._onvLoadedMetadata=function(c){this._pendingSeekTime!=null&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null),this._emitter.emit(A.default.MEDIA_INFO,this.mediaInfo)},L.prototype._reportStatisticsInfo=function(){this._emitter.emit(A.default.STATISTICS_INFO,this.statisticsInfo)},L}();X.default.install();var J={createPlayer:function(L,c){var C=L;if(C==null||typeof C!="object")throw new x.InvalidArgumentException("MediaDataSource must be an javascript object!");if(!C.hasOwnProperty("type"))throw new x.InvalidArgumentException("MediaDataSource must has type field to indicate video file type!");switch(C.type){case"mse":case"mpegts":case"m2ts":case"flv":return new ee(C,c);default:return new Re(C,c)}},isSupported:function(){return v.supportMSEH264Playback()},getFeatureList:function(){return v.getFeatureList()}};J.BaseLoader=I.BaseLoader,J.LoaderStatus=I.LoaderStatus,J.LoaderErrors=I.LoaderErrors,J.Events=A.default,J.ErrorTypes=U.ErrorTypes,J.ErrorDetails=U.ErrorDetails,J.MSEPlayer=ee,J.NativePlayer=Re,J.LoggingControl=me.default,Object.defineProperty(J,"version",{enumerable:!0,get:function(){return"1.8.2"}});var ke=J},355:function(le,Q,D){D.r(Q),D.d(Q,{ErrorDetails:function(){return S},ErrorTypes:function(){return _}});var X=D(470),P=D(827),_={NETWORK_ERROR:"NetworkError",MEDIA_ERROR:"MediaError",OTHER_ERROR:"OtherError"},S={NETWORK_EXCEPTION:X.LoaderErrors.EXCEPTION,NETWORK_STATUS_CODE_INVALID:X.LoaderErrors.HTTP_STATUS_CODE_INVALID,NETWORK_TIMEOUT:X.LoaderErrors.CONNECTING_TIMEOUT,NETWORK_UNRECOVERABLE_EARLY_EOF:X.LoaderErrors.UNRECOVERABLE_EARLY_EOF,MEDIA_MSE_ERROR:"MediaMSEError",MEDIA_FORMAT_ERROR:P.default.FORMAT_ERROR,MEDIA_FORMAT_UNSUPPORTED:P.default.FORMAT_UNSUPPORTED,MEDIA_CODEC_UNSUPPORTED:P.default.CODEC_UNSUPPORTED}},994:function(le,Q,D){D.r(Q);var X={};(function(){var P=self.navigator.userAgent.toLowerCase(),_=/(edge)\/([\w.]+)/.exec(P)||/(opr)[\/]([\w.]+)/.exec(P)||/(chrome)[ \/]([\w.]+)/.exec(P)||/(iemobile)[\/]([\w.]+)/.exec(P)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(P)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(P)||/(webkit)[ \/]([\w.]+)/.exec(P)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(P)||/(msie) ([\w.]+)/.exec(P)||P.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(P)||P.indexOf("compatible")<0&&/(firefox)[ \/]([\w.]+)/.exec(P)||[],S=/(ipad)/.exec(P)||/(ipod)/.exec(P)||/(windows phone)/.exec(P)||/(iphone)/.exec(P)||/(kindle)/.exec(P)||/(android)/.exec(P)||/(windows)/.exec(P)||/(mac)/.exec(P)||/(linux)/.exec(P)||/(cros)/.exec(P)||[],R={browser:_[5]||_[3]||_[1]||"",version:_[2]||_[4]||"0",majorVersion:_[4]||_[2]||"0",platform:S[0]||""},v={};if(R.browser){v[R.browser]=!0;var I=R.majorVersion.split(".");v.version={major:parseInt(R.majorVersion,10),string:R.version},I.length>1&&(v.version.minor=parseInt(I[1],10)),I.length>2&&(v.version.build=parseInt(I[2],10))}if(R.platform&&(v[R.platform]=!0),(v.chrome||v.opr||v.safari)&&(v.webkit=!0),v.rv||v.iemobile){v.rv&&delete v.rv;var b="msie";R.browser=b,v[b]=!0}if(v.edge){delete v.edge;var k="msedge";R.browser=k,v[k]=!0}if(v.opr){var w="opera";R.browser=w,v[w]=!0}if(v.safari&&v.android){var O="android";R.browser=O,v[O]=!0}for(var A in v.name=R.browser,v.platform=R.platform,X)X.hasOwnProperty(A)&&delete X[A];Object.assign(X,v)})(),Q.default=X},867:function(le,Q,D){D.r(Q),D.d(Q,{IllegalStateException:function(){return S},InvalidArgumentException:function(){return R},NotImplementedException:function(){return v},RuntimeException:function(){return _}});var X,P=(X=function(I,b){return X=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(k,w){k.__proto__=w}||function(k,w){for(var O in w)Object.prototype.hasOwnProperty.call(w,O)&&(k[O]=w[O])},X(I,b)},function(I,b){if(typeof b!="function"&&b!==null)throw TypeError("Class extends value "+String(b)+" is not a constructor or null");function k(){this.constructor=I}X(I,b),I.prototype=b===null?Object.create(b):(k.prototype=b.prototype,new k)}),_=function(){function I(b){this._message=b}return Object.defineProperty(I.prototype,"name",{get:function(){return"RuntimeException"},enumerable:!1,configurable:!0}),Object.defineProperty(I.prototype,"message",{get:function(){return this._message},enumerable:!1,configurable:!0}),I.prototype.toString=function(){return this.name+": "+this.message},I}(),S=function(I){function b(k){return I.call(this,k)||this}return P(b,I),Object.defineProperty(b.prototype,"name",{get:function(){return"IllegalStateException"},enumerable:!1,configurable:!0}),b}(_),R=function(I){function b(k){return I.call(this,k)||this}return P(b,I),Object.defineProperty(b.prototype,"name",{get:function(){return"InvalidArgumentException"},enumerable:!1,configurable:!0}),b}(_),v=function(I){function b(k){return I.call(this,k)||this}return P(b,I),Object.defineProperty(b.prototype,"name",{get:function(){return"NotImplementedException"},enumerable:!1,configurable:!0}),b}(_)},856:function(le,Q,D){D.r(Q);var X=D(7),P=D.n(X),_=function(){function S(){}return S.e=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","error",I),S.ENABLE_ERROR&&(console.error?console.error(I):console.warn?console.warn(I):console.log(I))},S.i=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","info",I),S.ENABLE_INFO&&(console.info?console.info(I):console.log(I))},S.w=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","warn",I),S.ENABLE_WARN&&(console.warn?console.warn(I):console.log(I))},S.d=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","debug",I),S.ENABLE_DEBUG&&(console.debug?console.debug(I):console.log(I))},S.v=function(R,v){R&&!S.FORCE_GLOBAL_TAG||(R=S.GLOBAL_TAG);var I="[".concat(R,"] > ").concat(v);S.ENABLE_CALLBACK&&S.emitter.emit("log","verbose",I),S.ENABLE_VERBOSE&&console.log(I)},S}();_.GLOBAL_TAG="mpegts.js",_.FORCE_GLOBAL_TAG=!1,_.ENABLE_ERROR=!0,_.ENABLE_INFO=!0,_.ENABLE_WARN=!0,_.ENABLE_DEBUG=!0,_.ENABLE_VERBOSE=!0,_.ENABLE_CALLBACK=!1,_.emitter=new(P()),Q.default=_},947:function(le,Q,D){D.r(Q);var X=D(7),P=D.n(X),_=D(856),S=function(){function R(){}return Object.defineProperty(R,"forceGlobalTag",{get:function(){return _.default.FORCE_GLOBAL_TAG},set:function(v){_.default.FORCE_GLOBAL_TAG=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"globalTag",{get:function(){return _.default.GLOBAL_TAG},set:function(v){_.default.GLOBAL_TAG=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableAll",{get:function(){return _.default.ENABLE_VERBOSE&&_.default.ENABLE_DEBUG&&_.default.ENABLE_INFO&&_.default.ENABLE_WARN&&_.default.ENABLE_ERROR},set:function(v){_.default.ENABLE_VERBOSE=v,_.default.ENABLE_DEBUG=v,_.default.ENABLE_INFO=v,_.default.ENABLE_WARN=v,_.default.ENABLE_ERROR=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableDebug",{get:function(){return _.default.ENABLE_DEBUG},set:function(v){_.default.ENABLE_DEBUG=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableVerbose",{get:function(){return _.default.ENABLE_VERBOSE},set:function(v){_.default.ENABLE_VERBOSE=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableInfo",{get:function(){return _.default.ENABLE_INFO},set:function(v){_.default.ENABLE_INFO=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableWarn",{get:function(){return _.default.ENABLE_WARN},set:function(v){_.default.ENABLE_WARN=v,R._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(R,"enableError",{get:function(){return _.default.ENABLE_ERROR},set:function(v){_.default.ENABLE_ERROR=v,R._notifyChange()},enumerable:!1,configurable:!0}),R.getConfig=function(){return{globalTag:_.default.GLOBAL_TAG,forceGlobalTag:_.default.FORCE_GLOBAL_TAG,enableVerbose:_.default.ENABLE_VERBOSE,enableDebug:_.default.ENABLE_DEBUG,enableInfo:_.default.ENABLE_INFO,enableWarn:_.default.ENABLE_WARN,enableError:_.default.ENABLE_ERROR,enableCallback:_.default.ENABLE_CALLBACK}},R.applyConfig=function(v){_.default.GLOBAL_TAG=v.globalTag,_.default.FORCE_GLOBAL_TAG=v.forceGlobalTag,_.default.ENABLE_VERBOSE=v.enableVerbose,_.default.ENABLE_DEBUG=v.enableDebug,_.default.ENABLE_INFO=v.enableInfo,_.default.ENABLE_WARN=v.enableWarn,_.default.ENABLE_ERROR=v.enableError,_.default.ENABLE_CALLBACK=v.enableCallback},R._notifyChange=function(){var v=R.emitter;if(v.listenerCount("change")>0){var I=R.getConfig();v.emit("change",I)}},R.registerListener=function(v){R.emitter.addListener("change",v)},R.removeListener=function(v){R.emitter.removeListener("change",v)},R.addLogListener=function(v){_.default.emitter.addListener("log",v),_.default.emitter.listenerCount("log")>0&&(_.default.ENABLE_CALLBACK=!0,R._notifyChange())},R.removeLogListener=function(v){_.default.emitter.removeListener("log",v),_.default.emitter.listenerCount("log")===0&&(_.default.ENABLE_CALLBACK=!1,R._notifyChange())},R}();S.emitter=new(P()),Q.default=S},811:function(le,Q,D){D.r(Q);var X=function(){function P(){}return P.install=function(){Object.setPrototypeOf=Object.setPrototypeOf||function(_,S){return _.__proto__=S,_},Object.assign=Object.assign||function(_){if(_==null)throw TypeError("Cannot convert undefined or null to object");for(var S=Object(_),R=1;R0?0|S:0;return this.substring(R,R+_.length)===_}}),typeof self.Promise!="function"&&D(964).polyfill()},P}();X.install(),Q.default=X},861:function(le,Q,D){function X(b){var k={};function w(A){if(k[A])return k[A].exports;var G=k[A]={i:A,id:A,l:!1,loaded:!1,exports:{}};return b[A].call(G.exports,G,G.exports,w),G.l=!0,G.loaded=!0,G.exports}w.m=b,w.c=k,w.d=function(A,G){for(var m in G)w.o(G,m)&&!w.o(A,m)&&Object.defineProperty(A,m,{enumerable:!0,get:G[m]})},w.r=function(A){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(A,"__esModule",{value:!0})},w.n=function(A){var G=A&&A.__esModule?function(){return A.default}:function(){return A};return w.d(G,{a:G}),G},w.o=function(A,G){return Object.prototype.hasOwnProperty.call(A,G)},w.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||Function("return this")()}catch(A){if(typeof self=="object")return self}}(),w.p="/";var O=w(ENTRY_MODULE);return O.default||O}var P="[\\.|\\-|\\+|\\w|/|@]+",_="\\(\\s*(/\\*.*?\\*/)?\\s*.*?("+P+").*?\\)";function S(b){return(b+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function R(b){return!isNaN(1*b)}function v(b,k,w){var O={};O[w]=[];var A=k.toString(),G=A.match(/^(?:function\s*\w*\s*)?\(\s*\w+\s*,\s*\w+\s*,\s*(\w+)\s*\)/);if(!G)return O;for(var m,U=G[1],x=new RegExp("(\\\\n|\\W)"+S(U)+_,"g");m=x.exec(A);)m[3]!=="dll-reference"&&O[w].push(m[3]);for(x=new RegExp("\\("+S(U)+'\\("(dll-reference\\s('+P+'))"\\)\\)'+_,"g");m=x.exec(A);)b[m[2]]||(O[w].push(m[1]),b[m[2]]=D(m[1]).m),O[m[2]]=O[m[2]]||[],O[m[2]].push(m[4]);for(var K=Object.keys(O),M=0;M0},!1)}le.exports=function(b,k){k=k||{};var w={main:D.m},O=k.all?{main:Object.keys(w.main)}:function(x,K){for(var M={main:[K]},u={main:[]},h={main:{}};I(M);)for(var p=Object.keys(M),E=0;E{try{return Ae(R)}catch{return!1}})){let R=_t(_);if(R)D.push(R)}}if(D.length===0)return null;let X=D.length===1?D[0]:`${String(D[0])} and ${String(D[1])}`;return`This ${le} is ${String(X)}, which this browser cannot decode.${Me?` ${Me}`:""}`}var bi="VLC can — the button is beside Play.";function Ct(_e,Ae){return ct(_e,Ae,bi,"channel")}var Ai=[[/\bAFT[A-Z0-9]+\b/i,"firetv"],[/\bKF[A-Z]+\b/,"silk"],[/\bSilk\b/i,"silk"],[/\bAndroid TV\b/i,"androidtv"],[/\bGoogleTV\b/i,"googletv"],[/\bTizen\b/i,"tizen"],[/\bWeb0S\b/i,"webos"],[/\bRoku\b/i,"roku"],[/AppleTV/i,"appletv"],[/\bCrKey\b/i,"chromecast"],[/\bSMART-TV\b/i,"smarttv"],[/\bSmartTV\b/i,"smarttv"]];function Ri(_e){if(!_e)return null;for(let[Ae,Me]of Ai)if(Ae.test(_e))return Me;return null}function wt(_e){return Ri(_e)!==null}function It(_e){return{enableWorker:!1,enableStashBuffer:!0,stashInitialSize:393216,liveBufferLatencyChasing:!1,liveBufferLatencyMaxLatency:5,liveBufferLatencyMinRemain:1,autoCleanupSourceBuffer:!0,autoCleanupMaxBackwardDuration:30,autoCleanupMinBackwardDuration:10,lazyLoad:!1,lazyLoadMaxDuration:60,lazyLoadRecoverDuration:30,seekType:"range"}}function Ti(){try{return Boolean(Ye.default.getFeatureList().mseLivePlayback)}catch{return!1}}var Bt=5,Li=2000,ki=6000,Di=5000,Mi=3;function Ci(_e,Ae,Me,le=()=>{}){let Q=It(wt(navigator.userAgent)),D=null,X=!1,P=0,_=null,S=null,R=-1,v=0,I=()=>{if(_)clearTimeout(_);if(S)clearInterval(S);_=null,S=null},b=()=>{if(!D)return;let m=D;D=null;try{m.destroy()}catch{}},k=(m)=>{if(X)return;X=!0,I(),b(),Me(m)},w=(m,U=Li)=>{if(X)return;if(P>=Bt)return k(m);P+=1,I(),b(),le(`Reconnecting… (${P}/${Bt})`),_=setTimeout(()=>{if(_=null,!X)A()},U*2**(P-1))},O=()=>{if(S)clearInterval(S);R=_e.currentTime,v=0,S=setInterval(()=>{if(X||!D)return;if(_e.paused||_e.ended||_e.seeking){v=0,R=_e.currentTime;return}if(_e.currentTime===R){if(v+=1,v>=Mi)v=0,w("The stream stopped sending. Try VLC, or press Play again.");return}R=_e.currentTime,v=0},Di)};function A(){D=Ye.default.createPlayer({type:"mpegts",isLive:!0,url:Ae,withCredentials:!0},Q),D.on(Ye.default.Events.MEDIA_INFO,(m)=>{let U=Ct(m,(x)=>window.MediaSource?.isTypeSupported?.(x)??!1);if(U)k(U)}),D.on(Ye.default.Events.ERROR,(m,U,x)=>{let K=x?.code;if(K===429)return k("The line was busy. Try that again.");if(K===409)return k("Somebody else is watching that line right now. Try again in a bit.");if(K===404)return k("That channel is no longer on your list.");if(K===415)return k("That channel needs a different player. Try VLC.");if(K===502)return k("Your provider did not send a stream for that channel.");if(K===503)return w("Your provider kept the line busy. Try again in a minute.",ki);if(K===504)return w("Your provider did not send a stream for that channel.");if(m===Ye.default.ErrorTypes.NETWORK_ERROR)return w("The stream stopped. Your provider may have dropped it, or you started another channel somewhere else.");w(U?`That stream could not be played here (${U}). Try VLC.`:"That stream could not be played here. Try VLC.")}),D.attachMediaElement(_e),D.load(),D.play()?.catch(()=>{}),O()}let G=()=>{P=0,le(null)};return _e.addEventListener("playing",G),A(),()=>{X=!0,I(),_e.removeEventListener("playing",G),b(),_e.removeAttribute("src"),_e.load()}}window.__tipoffPlayer={supported:Ti,attach:Ci}; diff --git a/apps/web/public/vendor-player.css b/apps/web/public/vendor-player.css new file mode 100644 index 0000000..ddea550 --- /dev/null +++ b/apps/web/public/vendor-player.css @@ -0,0 +1,503 @@ +/* =============================================================== the player == + Styles for lib/player/player.ts. + + Plain class names and no build-tool syntax on purpose: this file is meant to + be pasted into genrewatch.com's and tipoffwatch.com's `styles.css` unchanged. + No Tailwind, no nesting, no custom properties borrowed from the host site -- + the player has to look the same in three codebases that share no design + tokens, and the one thing every player agrees on is that it is dark. + + Everything is scoped under .pux-player so it cannot leak into a host page. */ + +.pux-player { + position: relative; + width: 100%; + height: 100%; + background: #000; + overflow: hidden; + /* The container is focusable so keyboard control works after a click on the + picture. Its focus ring would otherwise sit around the whole video. */ + outline: none; + font-family: + ui-sans-serif, + system-ui, + -apple-system, + 'Segoe UI', + Roboto, + Helvetica, + Arial, + sans-serif; + -webkit-user-select: none; + user-select: none; +} +.pux-player:focus-visible { + outline: 2px solid #fff; + outline-offset: -2px; +} + +.pux-player video { + display: block; + width: 100%; + height: 100%; + /* contain, not cover: cover crops, and cropping the top off a screen share + removes the menu bar somebody was demonstrating. */ + object-fit: contain; + background: #000; +} + +/* ------------------------------------------------------------- big play -- */ + +.pux-player__overlay { + position: absolute; + inset: 0; + display: grid; + place-items: center; + margin: 0; + padding: 0; + border: 0; + background: transparent; + color: #fff; + cursor: pointer; + transition: opacity 150ms ease; +} +.pux-player__overlay svg { + width: 4rem; + height: 4rem; + fill: currentColor; + border-radius: 999px; + background: rgba(0, 0, 0, 0.55); + padding: 1rem; +} +/* While it is playing the overlay must not sit between the reader and the + picture -- but it stays clickable, because clicking the picture to pause is + the single most used control there is. */ +.pux-player--playing .pux-player__overlay { + opacity: 0; +} +.pux-player--playing:hover .pux-player__overlay svg, +.pux-player--playing .pux-player__overlay:focus-visible svg { + opacity: 1; +} +.pux-player--playing .pux-player__overlay:focus-visible { + opacity: 1; +} +.pux-player--failed .pux-player__overlay { + display: none; +} + +/* ------------------------------------------------------------ buffering -- */ + +.pux-player__spinner { + position: absolute; + top: 50%; + left: 50%; + width: 2.5rem; + height: 2.5rem; + margin: -1.25rem 0 0 -1.25rem; + border: 3px solid rgba(255, 255, 255, 0.25); + border-top-color: #fff; + border-radius: 999px; + display: none; + animation: pux-spin 800ms linear infinite; +} +.pux-player--buffering .pux-player__spinner { + display: block; +} +@keyframes pux-spin { + to { + transform: rotate(360deg); + } +} +@media (prefers-reduced-motion: reduce) { + .pux-player__spinner { + animation-duration: 2s; + } +} + +/* --------------------------------------------------------------- notice -- */ + +/* Resume, copied links, and the reason a recording will not play. Top-left so + it never covers the controls the reader is reaching for. */ +.pux-player__notice { + position: absolute; + top: 0.75rem; + left: 0.75rem; + right: 0.75rem; + display: flex; + align-items: center; + gap: 0.75rem; + max-width: 34rem; + padding: 0.5rem 0.75rem; + border-radius: 0.5rem; + background: rgba(15, 23, 42, 0.92); + color: #f8fafc; + font-size: 0.8125rem; + line-height: 1.4; +} +.pux-player__notice[hidden] { + display: none; +} +.pux-player__notice-text { + flex: 1 1 auto; + /* An error message can be long; a URL can be very long and has no spaces. */ + overflow-wrap: anywhere; +} +.pux-player__notice-action { + flex: 0 0 auto; + padding: 0.25rem 0.6rem; + border: 1px solid rgba(248, 250, 252, 0.4); + border-radius: 0.375rem; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; +} +.pux-player__notice-action:hover { + background: rgba(248, 250, 252, 0.12); +} +.pux-player__notice-action[hidden] { + display: none; +} + +/* ------------------------------------------------------------------ bar -- */ + +.pux-player__bar { + position: absolute; + left: 0; + right: 0; + bottom: 0; + padding: 2.5rem 0.75rem 0.6rem; + /* The gradient is what keeps white controls legible over a white slide. */ + background: linear-gradient(to top, rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0)); + opacity: 0; + transform: translateY(0.5rem); + transition: + opacity 150ms ease, + transform 150ms ease; + pointer-events: none; +} +.pux-player--controls .pux-player__bar { + opacity: 1; + transform: none; + pointer-events: auto; +} +/* A paused or failed player keeps its controls: there is nothing to watch, and + hiding them is how a reader concludes the page is broken. */ +.pux-player:not(.pux-player--playing) .pux-player__bar, +.pux-player--failed .pux-player__bar { + opacity: 1; + transform: none; + pointer-events: auto; +} + +/* ---------------------------------------------------------------- scrub -- */ + +.pux-player__scrub { + position: relative; + height: 1.25rem; + display: flex; + align-items: center; + cursor: pointer; + touch-action: none; +} +.pux-player__scrub:focus-visible { + outline: 2px solid #fff; + outline-offset: 2px; + border-radius: 0.25rem; +} +.pux-player__track { + position: relative; + width: 100%; + height: 0.25rem; + border-radius: 999px; + background: rgba(255, 255, 255, 0.28); + transition: height 120ms ease; +} +.pux-player__scrub:hover .pux-player__track, +.pux-player__scrub:focus-visible .pux-player__track { + height: 0.4rem; +} +.pux-player__buffered, +.pux-player__played { + position: absolute; + top: 0; + left: 0; + height: 100%; + border-radius: 999px; +} +.pux-player__buffered { + width: 0; + background: rgba(255, 255, 255, 0.4); +} +.pux-player__played { + width: 0; + background: #6366f1; +} +.pux-player__handle { + position: absolute; + top: 50%; + left: 0; + width: 0.85rem; + height: 0.85rem; + margin: -0.425rem 0 0 -0.425rem; + border-radius: 999px; + background: #fff; + opacity: 0; + transition: opacity 120ms ease; +} +.pux-player__scrub:hover .pux-player__handle, +.pux-player__scrub:focus-visible .pux-player__handle, +.pux-player--tv .pux-player__handle { + opacity: 1; +} + +/* Chapter marks. Buttons rather than decorations, so they can be clicked and + reached, but small enough not to become the bar's main feature. */ +.pux-player__marks { + position: absolute; + inset: 0; + pointer-events: none; +} +.pux-player__mark { + position: absolute; + top: 50%; + width: 0.2rem; + height: 0.7rem; + margin: -0.35rem 0 0 -0.1rem; + padding: 0; + border: 0; + border-radius: 1px; + background: rgba(255, 255, 255, 0.9); + cursor: pointer; + pointer-events: auto; +} +.pux-player__mark:hover, +.pux-player__mark:focus-visible { + background: #fff; + height: 1rem; + margin-top: -0.5rem; + outline: none; +} + +.pux-player__tooltip { + position: absolute; + bottom: 1.4rem; + transform: translateX(-50%); + padding: 0.1rem 0.4rem; + border-radius: 0.25rem; + background: rgba(15, 23, 42, 0.92); + color: #f8fafc; + font-size: 0.7rem; + font-variant-numeric: tabular-nums; + opacity: 0; + pointer-events: none; +} +.pux-player__scrub:hover .pux-player__tooltip { + opacity: 1; +} + +/* ------------------------------------------------------------------ row -- */ + +.pux-player__row { + display: flex; + align-items: center; + gap: 0.15rem; + color: #fff; +} +.pux-player__btn { + display: inline-grid; + place-items: center; + flex: 0 0 auto; + width: 2.25rem; + height: 2.25rem; + padding: 0; + border: 0; + border-radius: 0.375rem; + background: transparent; + color: #fff; + cursor: pointer; +} +.pux-player__btn svg { + width: 1.35rem; + height: 1.35rem; + fill: currentColor; +} +.pux-player__btn:hover { + background: rgba(255, 255, 255, 0.16); +} +.pux-player__btn:focus-visible { + outline: 2px solid #fff; + outline-offset: -2px; +} +.pux-player__btn[hidden] { + display: none; +} +.pux-player__btn--text { + width: auto; + min-width: 2.5rem; + padding: 0 0.4rem; + font-size: 0.8125rem; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.pux-player__volume { + display: flex; + align-items: center; + flex: 0 0 auto; +} +/* The slider is revealed on hover so the bar is not half volume control on a + narrow player, but it stays reachable by keyboard at all times. */ +.pux-player__volume-input { + width: 0; + opacity: 0; + margin: 0; + accent-color: #6366f1; + transition: + width 140ms ease, + opacity 140ms ease; +} +.pux-player__volume:hover .pux-player__volume-input, +.pux-player__volume-input:focus-visible { + width: 4.5rem; + opacity: 1; + margin-left: 0.25rem; +} +.pux-player__volume-input[hidden] { + display: none; +} + +.pux-player__time { + flex: 0 0 auto; + padding: 0 0.5rem; + font-size: 0.8125rem; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} +.pux-player__chapter { + flex: 0 1 auto; + min-width: 0; + padding-right: 0.5rem; + font-size: 0.8125rem; + color: rgba(255, 255, 255, 0.75); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.pux-player__spacer { + flex: 1 1 auto; +} + +/* A phone has no room for every control. The ones that go are the ones with a + keyboard shortcut or a system equivalent: volume is on the device, and + picture-in-picture is in the browser's own menu. */ +@media (max-width: 32rem) { + .pux-player__volume-input, + .pux-player__chapter { + display: none; + } + .pux-player__btn { + width: 2rem; + height: 2rem; + } +} + +/* ----------------------------------------------------------------- a tv -- */ + +/* Everything grows: a control aimed at from three metres with a D-pad needs to + be visible from there, and the focus ring is the only cursor a television + has, so it is never subtle and never hidden. */ +.pux-player--tv .pux-player__bar { + padding: 3.5rem 1.5rem 1.25rem; +} +.pux-player--tv .pux-player__btn { + width: 3rem; + height: 3rem; +} +.pux-player--tv .pux-player__btn svg { + width: 1.75rem; + height: 1.75rem; +} +.pux-player--tv .pux-player__btn--text { + width: auto; + min-width: 3.25rem; + font-size: 1rem; +} +.pux-player--tv .pux-player__time, +.pux-player--tv .pux-player__chapter { + font-size: 1rem; +} +.pux-player--tv .pux-player__track { + height: 0.4rem; +} +.pux-player--tv .pux-player__btn:focus, +.pux-player--tv .pux-player__mark:focus, +.pux-player--tv .pux-player__scrub:focus { + outline: 3px solid #fff; + outline-offset: 2px; +} + +/* ================================================================== live == */ + +/* A live stream has no end, so it has no scrub bar, no clock, no speed and no + position worth remembering. What it has instead is a badge saying so -- the + absence of a progress bar reads as a broken player unless something explains + it. */ +.pux-player__live { + flex: 0 0 auto; + margin-left: 0.5rem; + padding: 0.1rem 0.45rem; + border: 1px solid #ef4444; + border-radius: 999px; + color: #ef4444; + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.04em; + line-height: 1.6; +} +.pux-player__live[hidden] { + display: none; +} +.pux-player__live::before { + content: '●'; + margin-right: 0.3rem; + font-size: 0.8em; + vertical-align: 0.05em; +} +.pux-player--live .pux-player__scrub[hidden], +.pux-player__time[hidden], +.pux-player__chapter[hidden] { + display: none; +} + +/* ================================================================= audio == */ + +/* No picture, so no stage: the bar IS the player. It sits in the normal flow + rather than floating over a video, is always visible, and keeps its own + background because there is no gradient over a frame to make it legible. */ +.pux-player--audio { + height: auto; + background: #0f172a; + border-radius: 0.5rem; + overflow: visible; +} +.pux-player--audio audio { + display: none; +} +.pux-player--audio .pux-player__bar { + position: static; + padding: 0.5rem 0.75rem; + background: none; + opacity: 1; + transform: none; + pointer-events: auto; +} +.pux-player--audio .pux-player__overlay, +.pux-player--audio .pux-player__spinner { + display: none; +} +.pux-player--audio .pux-player__notice { + position: static; + margin-bottom: 0.5rem; + max-width: none; +} diff --git a/apps/web/public/vendor-player.js b/apps/web/public/vendor-player.js new file mode 100644 index 0000000..f33ffeb --- /dev/null +++ b/apps/web/public/vendor-player.js @@ -0,0 +1,27 @@ +var oo=Object.defineProperty;var lo=(e)=>e;function uo(e,t){this[e]=lo.bind(null,t)}var qt=(e,t)=>{for(var i in t)oo(e,i,{get:t[i],enumerable:!0,configurable:!0,set:uo.bind(t,i)})};var It=(e,t)=>()=>(e&&(t=e(e=0)),t);var co=((e)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ka={};qt(ka,{AbrController:()=>bs,AttrList:()=>ce,AudioStreamController:()=>cn,AudioTrackController:()=>cn,BaseLoader:()=>wi,BasePlaylistController:()=>Ds,BaseSegment:()=>bi,BaseStreamController:()=>ks,BufferController:()=>Ps,CMCDController:()=>cn,CapLevelController:()=>Pi,ChunkMetadata:()=>ki,ContentSteeringController:()=>ws,Cues:()=>cn,DateRange:()=>Di,EMEController:()=>cn,ErrorActionFlags:()=>ye,ErrorController:()=>Is,ErrorDetails:()=>R,ErrorTypes:()=>Q,Events:()=>y,FPSController:()=>Os,FetchLoader:()=>Li,Fragment:()=>yt,Hls:()=>tt,HlsSkip:()=>wt,HlsUrlParameters:()=>vi,KeySystemFormats:()=>td,KeySystems:()=>id,Level:()=>_i,LevelDetails:()=>_s,LevelKey:()=>xt,LoadStats:()=>Ai,LoaderContextType:()=>se,M3U8Parser:()=>Ge,MetadataSchema:()=>Re,NetworkErrorAction:()=>Ee,Part:()=>Es,PlaylistLevelType:()=>J,SubtitleStreamController:()=>sd,SubtitleTrackController:()=>cn,TimelineController:()=>rd,XhrLoader:()=>Oi,default:()=>tt,fetchSupported:()=>Aa,getMediaSource:()=>it,isMSESupported:()=>Bs,isSupported:()=>Ta,requestMediaKeySystemAccess:()=>nd});function nn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function go(){if(er)return $i.exports;return er=1,function(e,t){(function(i){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,l={buildAbsoluteURL:function(o,u,d){if(d=d||{},o=o.trim(),u=u.trim(),!u){if(!d.alwaysNormalize)return o;var c=l.parseURL(o);if(!c)throw Error("Error trying to parse base URL.");return c.path=l.normalizePath(c.path),l.buildURLFromParts(c)}var h=l.parseURL(u);if(!h)throw Error("Error trying to parse relative URL.");if(h.scheme){if(!d.alwaysNormalize)return u;return h.path=l.normalizePath(h.path),l.buildURLFromParts(h)}var g=l.parseURL(o);if(!g)throw Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var m=r.exec(g.path);g.netLoc=m[1],g.path=m[2]}if(g.netLoc&&!g.path)g.path="/";var f={scheme:g.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc){if(f.netLoc=g.netLoc,h.path[0]!=="/")if(!h.path){if(f.path=g.path,!h.params){if(f.params=g.params,!h.query)f.query=g.query}}else{var v=g.path,E=v.substring(0,v.lastIndexOf("/")+1)+h.path;f.path=l.normalizePath(E)}}if(f.path===null)f.path=d.alwaysNormalize?l.normalizePath(h.path):h.path;return l.buildURLFromParts(f)},parseURL:function(o){var u=s.exec(o);if(!u)return null;return{scheme:u[1]||"",netLoc:u[2]||"",path:u[3]||"",params:u[4]||"",query:u[5]||"",fragment:u[6]||""}},normalizePath:function(o){o=o.split("").reverse().join("").replace(n,"");while(o.length!==(o=o.replace(a,"")).length);return o.split("").reverse().join("")},buildURLFromParts:function(o){return o.scheme+o.netLoc+o.path+o.params+o.query+o.fragment}};e.exports=l})()}($i),$i.exports}class Ai{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}class bi{constructor(e){if(this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e==="string")e={url:e};this.base=e,mo(this,"stats")}setByteRange(e,t){let i=e.split("@",2),s;if(i.length===1)s=(t==null?void 0:t.byteRangeEndOffset)||0;else s=parseInt(i[1]);this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){if(this._byteRange===null)return[];return this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){if(this._streams===null)this._streams={[he.AUDIO]:null,[he.VIDEO]:null,[he.AUDIOVIDEO]:null};return this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){if(this._stats===null)this._stats=new Ai;return this._stats}set stats(e){this._stats=e}get url(){if(!this._url&&this.relurl)this._url=ys.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0});return this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[he.AUDIO]=null,e[he.VIDEO]=null,e[he.AUDIOVIDEO]=null,this.url=null}}function Fe(e){return e.sn!=="initSegment"}function zt(e,t){return e.sn===(t==null?void 0:t.sn)&&e.level===t.level}function ss(e,t){return e.sn===(t==null?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}function an(e,t){let i=Object.getPrototypeOf(e);if(i){let s=Object.getOwnPropertyDescriptor(i,t);if(s)return s;return an(i,t)}}function mo(e,t){let i=an(e,t);if(i)i.enumerable=!0,Object.defineProperty(e,t,i)}function po(e,t,i){return(t=yo(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Te(){return Te=Object.assign?Object.assign.bind():function(e){for(var t=1;t499)}function Nt(e){return e===0&&navigator.onLine===!1}function un(e,t){return t>0&&e.loadError>0&&e.loadErrorTime!==0&&self.performance.now()-e.loadErrorTime>t}class gt{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(0.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class dn{constructor(e,t,i,s=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_=i,this.minWeight_=0.001,this.minDelayMs_=50,this.slow_=new gt(e),this.fast_=new gt(t),this.defaultTTFB_=s,this.ttfb_=new gt(e)}update(e,t){let{slow_:i,fast_:s,ttfb_:r}=this;if(i.halfLife!==e)this.slow_=new gt(e,i.getEstimate(),i.getTotalWeight());if(s.halfLife!==t)this.fast_=new gt(t,s.getEstimate(),s.getTotalWeight());if(r.halfLife!==e)this.ttfb_=new gt(e,r.getEstimate(),r.getTotalWeight())}sample(e,t){if(t<=0)return;let i=Math.min(this.minDelayMs_,t/1e5),s=8*t,r=Math.max(e,i)/1000,n=s/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){let t=e/1000,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){if(this.canEstimate())return Math.min(this.fast_.getEstimate(),this.slow_.getEstimate());else return this.defaultEstimate_}getEstimateTTFB(){if(this.ttfb_.getTotalWeight()>=this.minWeight_)return this.ttfb_.getEstimate();else return this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class Qe{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=nt,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}function rs(){return Te({},So)}function To(e,t){let i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):nt}function rr(e,t,i){return t[e]?t[e].bind(t):To(e,i)}function xo(e,t,i){let s=rs();if(typeof console==="object"&&e===!0||typeof e==="object"){let r=["debug","log","info","warn","error"];r.forEach((n)=>{s[n]=rr(n,e,i)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.7.2`)}catch(n){return rs()}r.forEach((n)=>{ns[n]=rr(n,e)})}else Te(ns,s);return s}function Lo(){if(nr)return Bi;return nr=1,Bi={},Bi}function it(e=!0){if(typeof self>"u")return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ao(e){return typeof self<"u"&&e===self.ManagedMediaSource}function bo(e,t){let i=Object.keys(e),s=Object.keys(t),r=i.length,n=s.length;return!r||!n||r===n&&!i.some((a)=>s.indexOf(a)===-1)}function Ri(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function Io(e,t={}){let i;if(Ri(e))i=new DataView(e);else i=new DataView(e.buffer,e.byteOffset,e.byteLength);let s=0,{encoding:r}=t;if(!r){let u=i.getUint8(0),d=i.getUint8(1);if(u==239&&d==187&&i.getUint8(2)==191)r=ai,s=3;else if(u==254&&d==255)r=Ui,s=2;else if(u==255&&d==254)r=ar,s=2;else r=ai}if(typeof TextDecoder<"u")return new TextDecoder(r).decode(i);let{byteLength:n}=i,a=r!==Ui,l="",o;while(s=194&&o<=223)if(s+1=128&&u<=191)o=(o&31)<<6|u&63,s+=2;else s++}else s++;else if(o>=224&&o<=239)if(s+2<=n-1){let u=i.getUint8(s+1),d=i.getUint8(s+2);if(u>=128&&u<=191&&d>=128&&d<=191)o=(o&15)<<12|(u&63)<<6|d&63,s+=3;else s++}else s++;else if(o>=240&&o<=244)if(s+3<=n-1){let u=i.getUint8(s+1),d=i.getUint8(s+2),c=i.getUint8(s+3);if(u>=128&&u<=191&&d>=128&&d<=191&&c>=128&&c<=191)o=(o&7)<<18|(u&63)<<12|(d&63)<<6|c&63,s+=4;else s++}else s++;else s++;break;case Ui:case Ro:case ar:o=i.getUint16(s,a),s+=2;break}l+=String.fromCodePoint(o)}return l}function _o(){try{return crypto.randomUUID()}catch(e){try{let t=URL.createObjectURL(new Blob),i=t.toString();return URL.revokeObjectURL(t),i.slice(i.lastIndexOf("/")+1)}catch(t){let i=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(s)=>{let r=(i+Math.random()*16)%16|0;return i=Math.floor(i/16),(s=="x"?r:r&3|8).toString(16)})}}}function Ts(e,t){if(t+10<=e.length){if(e[t]===73&&e[t+1]===68&&e[t+2]===51){if(e[t+3]<255&&e[t+4]<255){if(e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128)return!0}}}return!1}function Ii(e,t){let i=0;return i=(e[t]&127)<<21,i|=(e[t+1]&127)<<14,i|=(e[t+2]&127)<<7,i|=e[t+3]&127,i}function Do(e,t){return Ts(e,t)&&Ii(e,t+6)+10<=e.length-t}function hn(e,t){if(t+10<=e.length){if(e[t]===51&&e[t+1]===68&&e[t+2]===73){if(e[t+3]<255&&e[t+4]<255){if(e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128)return!0}}}return!1}function hi(e,t){let i=t,s=0;while(Ts(e,t)){s+=10;let r=Ii(e,t+6);if(s+=r,hn(e,t+10))s+=10;t+=s}if(s>0)return e.subarray(i,i+s)}function Co(e){if(Ri(e))return e;else{if(e.byteOffset==0&&e.byteLength==e.buffer.byteLength)return e.buffer;return new Uint8Array(e).buffer}}function Gi(e,t=0,i=1/0){return ko(e,t,i,Uint8Array)}function ko(e,t,i,s){let r=Po(e),n=1;if("BYTES_PER_ELEMENT"in s)n=s.BYTES_PER_ELEMENT;let a=wo(e)?e.byteOffset:0,l=(a+e.byteLength)/n,o=(a+t)/n,u=Math.floor(Math.max(0,Math.min(o,l)));return new s(r,u,Math.floor(Math.min(u+Math.max(i,0),l))-u)}function Po(e){if(Ri(e))return e;else return e.buffer}function wo(e){return e&&Ri(e.buffer)&&e.byteLength!==void 0&&e.byteOffset!==void 0}function Ve(e,t=!1){let i=t?e.indexOf(0):e.length,s=Io(new DataView(e.buffer,e.byteOffset,i),{encoding:ai});return t?s:s.replace(/\0/g,"")}function Oo(e){let t={key:e.type,description:"",data:"",mimeType:null,pictureType:null},i=3;if(e.size<2)return;if(e.data[0]!==3){console.log("Ignore frame with unrecognized character encoding");return}let s=e.data.subarray(1).indexOf(0);if(s===-1)return;let r=Ve(Gi(e.data,1,s)),n=e.data[2+s],a=e.data.subarray(3+s).indexOf(0);if(a===-1)return;let l=Ve(Gi(e.data,3+s,a)),o;if(r==="-->")o=Ve(Gi(e.data,4+s+a));else o=Co(e.data.subarray(4+s+a));return t.mimeType=r,t.pictureType=n,t.description=l,t.data=o,t}function Fo(e){if(e.size<2)return;let t=Ve(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}function Mo(e){if(e.size<2)return;if(e.type==="TXXX"){let i=1,{data:s}=e,r=Ve(s.subarray(i),!0);i+=r.length+1;let n=Ve(s.subarray(i));return{key:e.type,info:r,data:n}}let t=Ve(e.data.subarray(1));return{key:e.type,info:"",data:t}}function No(e){if(e.type==="WXXX"){if(e.size<2)return;let i=1,s=Ve(e.data.subarray(i),!0);i+=s.length+1;let r=Ve(e.data.subarray(i));return{key:e.type,info:s,data:r}}let t=Ve(e.data);return{key:e.type,info:"",data:t}}function $o(e){if(e.type==="PRIV")return Fo(e);else if(e.type[0]==="W")return No(e);else if(e.type==="APIC")return Oo(e);return Mo(e)}function Bo(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Ii(e,4),s=10;return{type:t,size:i,data:e.subarray(10,10+i)}}function fn(e){let t=0,i=[];while(Ts(e,t)){let s=Ii(e,t+6);if(e[t+5]>>6&1)t+=Xt;t+=Xt;let r=t+s;while(t+Uo>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=i&255}function Vo(e,t){let i=e.byteLength;for(let s=0;s8&&W(e,s+4)===ee[t])return!0;s=r>1?s+r:i}return!1}function ne(e,t){let i=[];if(!t.length)return i;return En(e,t,0,0,e.byteLength,i),i}function En(e,t,i,s,r,n){let a=t[i];if((a==null?void 0:a.length)!==4)return;let l=a.charCodeAt(0),o=a.charCodeAt(1),u=a.charCodeAt(2),d=a.charCodeAt(3),c=t.length-1;for(let h=s;h1?h+m:r;if(g&&e[h+4]===l&&e[h+5]===o&&e[h+6]===u&&e[h+7]===d){let v=Math.min(f,r);if(i===c)n.push(e.subarray(h+8,v));else En(e,t,i+1,h+8,v,n)}h=f}}function Ho(e){let t=[],i=e[0],s=8,r=W(e,s);s+=4;let n=0,a=0;if(i===0)n=W(e,s),a=W(e,s+4),s+=8;else n=or(e,s),a=or(e,s+8),s+=16;s+=2;let l=e.length+a,o=yn(e,s);s+=2;for(let u=0;u>>31===1)return ae.warn("SIDX has hierarchical references (not supported)"),null;let m=W(e,d);d+=4,t.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:l,end:l+h-1}}),l+=h,d+=4,s=d}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:o,references:t}}function Sn(e){let t=[],i=ne(e,["moov","trak"]);for(let r=0;r{let n=W(r,4),a=t[n];if(a)a.default={duration:W(r,12),sampleSize:W(r,16),flags:W(r,20)}}),t}function Ko(e){let t=e.subarray(8),i=t.subarray(86),s=kt(t.subarray(4,8)),r=s,n,a=s==="enca"||s==="encv";if(a){let u=ne(t,[s])[0].subarray(s==="enca"?28:78);ne(u,["sinf"]).forEach((c)=>{let h=ne(c,["schm"])[0];if(h){let g=kt(h.subarray(4,8));if(g==="cbcs"||g==="cenc"){let m=ne(c,["frma"])[0];if(m)r=kt(m)}}})}let l=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let o=ne(i,["avcC"])[0];if(o&&o.length>3)r+="."+Jt(o[1])+Jt(o[2])+Jt(o[3]),n=Zt(l==="avc1"?"dva1":"dvav",i);break}case"mp4a":{let o=ne(t,[s])[0],u=ne(o.subarray(28),["esds"])[0];if(u&&u.length>7){let d=4;if(u[d++]!==3)break;d=Vi(u,d),d+=2;let c=u[d++];if(c&128)d+=2;if(c&64)d+=u[d++];if(u[d++]!==4)break;d=Vi(u,d);let h=u[d++];if(h===64)r+="."+Jt(h);else break;if(d+=12,u[d++]!==5)break;d=Vi(u,d);let g=u[d++],m=(g&248)>>3;if(m===31)m+=1+((g&7)<<3)+((u[d]&224)>>5);r+="."+m}break}case"hvc1":case"hev1":{let o=ne(i,["hvcC"])[0];if(o&&o.length>12){let u=o[1],d=["","A","B","C"][u>>6],c=u&31,h=W(o,2),g=(u&32)>>5?"H":"L",m=o[12],f=o.subarray(6,12);r+="."+d+c,r+="."+Wo(h).toString(16).toUpperCase(),r+="."+g+m;let v="";for(let E=f.length;E--;){let p=f[E];if(p||v)v="."+p.toString(16).toUpperCase()+v}r+=v}n=Zt(l=="hev1"?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=Zt(r,i)||r;break}case"vp09":{let o=ne(i,["vpcC"])[0];if(o&&o.length>6){let u=o[4],d=o[5],c=o[6]>>4&15;r+="."+ze(u)+"."+ze(d)+"."+ze(c)}break}case"av01":{let o=ne(i,["av1C"])[0];if(o&&o.length>2){let u=o[1]>>>5,d=o[1]&31,c=o[2]>>>7?"H":"M",h=(o[2]&64)>>6,g=(o[2]&32)>>5,m=u===2&&h?g?12:10:h?10:8,f=(o[2]&16)>>4,v=(o[2]&8)>>3,E=(o[2]&4)>>2,p=o[2]&3,S=1,T=1,L=1,x=0;r+="."+u+"."+ze(d)+c+"."+ze(m)+"."+f+"."+v+E+p+"."+ze(1)+"."+ze(1)+"."+ze(1)+".0",n=Zt("dav1",i)}break}}return{codec:r,encrypted:a,supplemental:n}}function Zt(e,t){let i=ne(t,["dvvC"]),s=i.length?i[0]:ne(t,["dvcC"])[0];if(s){let r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return e+"."+ze(r)+"."+ze(n)}}function Wo(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}function Vi(e,t){let i=t+5;while(e[t++]&128&&t{let n=s.subarray(8,24);if(!n.some((a)=>a!==0))ae.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Et(n)} -> ${Et(i)}`),s.set(i,8)})}function jo(e){let t=[];return Tn(e,(i)=>t.push(i.subarray(8,24))),t}function Tn(e,t){ne(e,["moov","trak"]).forEach((s)=>{let r=ne(s,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=ne(n,["enca"]),l=a.length>0;if(!l)a=ne(n,["encv"]);a.forEach((o)=>{let u=l?o.subarray(28):o.subarray(78);ne(u,["sinf"]).forEach((c)=>{let h=qo(c);if(h)t(h,l)})})})}function qo(e){let t=ne(e,["schm"])[0];if(t){let i=kt(t.subarray(4,8));if(i==="cbcs"||i==="cenc"){let s=ne(e,["schi","tenc"])[0];if(s)return s}}}function zo(e){if(typeof TextDecoder>"u")return Ve(e);return(lr||(lr=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function Xo(e){let t=e.byteLength,i=[];for(let s=0;s1?s+n:t;if(r&&e[s+4]===109&&e[s+5]===111&&e[s+6]===111&&e[s+7]===102){let l=Math.min(a,t);for(let o=s+8;o1?o+d:l;if(u&&e[o+4]===116&&e[o+5]===114&&e[o+6]===97&&e[o+7]===102){let h=Math.min(c,l),g,m,f=[];for(let v=o+8;v1?v+p:h;if(E&&e[v+4]===116){let T=Math.min(S,h);if(e[v+5]===102&&e[v+6]===104&&e[v+7]===100)m||(m=e.subarray(v+8,T));else if(e[v+5]===102&&e[v+6]===100&&e[v+7]===116)g||(g=e.subarray(v+8,T));else if(e[v+5]===114&&e[v+6]===117&&e[v+7]===110)f.push(e.subarray(v+8,T))}v=S}i.push({moofOffset:e.byteOffset+s,tfdt:g,tfhd:m,truns:f})}o=c}}s=a}return i}function Qo(e,t,i,s,r=!0){return xn(e,t,s,r)}function Zo(e,t,i,s,r=!1){let n=[],a=t.samples,l=xn(a,i,s,r,{isHEVCFlavor:xs(t.codec),samples:n,timeOffset:e,timescale:t.timescale,trackId:t.id});return{samples:n,sampleData:{includeSampleDetails:r,tracks:l}}}function xn(e,t,i,s,r){let n={},a=!1,l=Xo(e),o=e.byteLength;for(let c=0;c0){let Pe=re;do{let pt=e[Pe]===0?e[Pe+1]<<16|e[Pe+2]<<8|e[Pe+3]:W(e,Pe);Pe+=4;let we=e[Pe],ct=ut?we>>1&63:we&31;if(ut?ct===39||ct===40:ct===6)fi(e.subarray(Pe,Pe+pt),Kt,ie,r.samples);Pe+=pt}while(Peo)break;ge=We+1,ve+=8}}if(T)r.timeOffset=ie;if(ke!==-1&&xe<=o&&p.keyFrameIndex===void 0)p.keyFrameIndex=ke,p.keyFrameStart=le+ke*b;if(ge){if(!H(p.ptsMin)||lep.ptsMax)p.ptsMax=_e}let Wt=b*U;O=le+Wt,C+=Wt;continue}let Le,Ne;if(s){if(Le=[],Ne={sampleOffset:re,samples:Le,defaultSampleDurationOffset:I},re<=o)p.trun.push(Ne)}let me;for(let le=0;lep.ptsMax)p.ptsMax=ge+k;if(Le)Le[le]={cts:xe,duration:k,flags:Ke,size:me}}O+=k,C+=k}if(!C&&b)C+=b*U}if(p.duration+=C,p.duration)a=!0}if(!a){let c=1/0,h=0,g=ne(e,["sidx"]);for(let m=0;mE+p.info.duration||0,0);h=Math.max(h,v+f.earliestPresentationTime/f.timescale)}}if(h&&H(h))Object.keys(n).forEach((m)=>{if(!n[m].duration)n[m].duration=h*n[m].timescale-n[m].start})}return n}function Jo(e){let t={valid:null,remainder:null},i=ne(e,["moof"]);if(i.length<2)return t.remainder=e,t;let s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}function He(e,t){let i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function el(e,t){let i=[],s=t.samples,r=t.timescale,n=t.id,a=!1;return ne(s,["moof"]).map((o)=>{let u=o.byteOffset-8;ne(o,["traf"]).map((c)=>{let h=ne(c,["tfdt"]).map((g)=>{let m=g[0],f=W(g,4);if(m===1)f*=Math.pow(2,32),f+=W(g,8);return f/r})[0];if(h!==void 0)e=h;return ne(c,["tfhd"]).map((g)=>{let m=W(g,4),f=W(g,0)&16777215,v=(f&1)!==0,E=0,p=(f&2)!==0,S=(f&8)!==0,T=0,L=(f&16)!==0,x=0,b=(f&32)!==0,I=!v&&(f&131072)!==0,A=8;if(m===n){if(v)E=W(g,A),A+=4,E*=Math.pow(2,32),E+=W(g,A),A+=4;else if(I)E=u;if(p)A+=4;if(S)T=W(g,A),A+=4;if(L)x=W(g,A),A+=4;if(b)A+=4;if(t.type==="video")a=xs(t.codec);ne(c,["trun"]).map((_)=>{let P=_[0],w=W(_,0)&16777215,Y=(w&1)!==0,O=0,C=(w&4)!==0,k=(w&256)!==0,G=0,D=(w&512)!==0,U=0,F=(w&1024)!==0,M=(w&2048)!==0,q=0,X=W(_,4),z=8;if(Y)O=W(_,z),z+=4;if(C)z+=4;let j=E+O;for(let oe=0;oe>1&63;return i===39||i===40}else return(t&31)===6}function fi(e,t,i,s){let r=An(e),n=0;n+=t;let a=0,l=0,o=0;while(n=r.length)break;o=r[n++],a+=o}while(o===255);l=0;do{if(n>=r.length)break;o=r[n++],l+=o}while(o===255);let u=r.length-n,d=n;if(lu){ae.error(`Malformed SEI payload. ${l} is too small, only ${u} bytes left to parse.`);break}if(a===4){if(r[d++]===181){let h=yn(r,d);if(d+=2,h===49){let g=W(r,d);if(d+=4,g===1195456820){let m=r[d++];if(m===3){let f=r[d++],v=31&f,E=64&f,p=E?2+v*3:0,S=new Uint8Array(p);if(E){S[0]=f;for(let T=1;T16){let c=[];for(let m=0;m<16;m++){let f=r[d++].toString(16);if(c.push(f.length==1?"0"+f:f),m===3||m===5||m===7||m===9)c.push("-")}let h=l-16,g=new Uint8Array(h);for(let m=0;m!As(s,t,i))}function As(e,t,i=!0){var s;let r=it(i);return(s=r==null?void 0:r.isTypeSupported(os(e,t)))!=null?s:!1}function os(e,t){return`${t}/mp4;codecs=${e}`}function ur(e){if(e){let t=e.substring(0,4);return Tt.video[t]}return 2}function gi(e){let t=rl();return e.split(",").reduce((i,s)=>{let n=t&&xs(s)?9:Tt.video[s];if(n)return(n*2+i)/(i?3:2);return(Tt.audio[s]+i)/(i?2:1)},0)}function al(e,t=!0){if(Yi[e])return Yi[e];let i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;ral(i.toLowerCase(),t))}function ll(e,t){let i=[];if(e){let s=e.split(",");for(let r=0;r4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)!==-1)){if(dr(e,"audio")||dr(e,"video"))return e}if(t){let i=t.split(",");if(i.length>1){if(e){for(let s=i.length;s--;)if(i[s].substring(0,4)===e.substring(0,4))return i[s]}return i[0]}}return t||e}function dr(e,t){return Ls(e,t)&&As(e,t)}function ul(e){let t=e.split(",");for(let i=0;i2&&s[0]==="avc1")t[i]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`}return t.join(",")}function cr(e){let t=it(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function dl(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function St(e,t,i){let s=encodeURIComponent(t),r=`${s}=${encodeURIComponent(i)}`,n=!1,a=[];if(e.search.substring(1).split("&").forEach((l)=>{if(l===s||l.startsWith(s+"=")){if(!n)a.push(r),n=!0}else if(l)a.push(l)}),!n)a.push(r);e.search=a.join("&")}function cl(e){return ls.indexOf(e)>-1}function hl(e){return!!e&&pi.indexOf(e)>-1}function hr(e){let{canSkipUntil:t,canSkipDateRanges:i,age:s}=e,r=s!!i).map((i)=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;if(i&&i!==e.videoCodec)this.codecSet+=`,${i.substring(0,4)}`}if("iframes"in e&&e.iframes)this.iframes=!0;else this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return fr(this._audioGroups,e)}hasSubtitleGroup(e){return fr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(!t)return;if(e==="audio"){let i=this._audioGroups;if(!i)i=this._audioGroups=[];if(i.indexOf(t)===-1)i.push(t)}else if(e==="text"){let i=this._subtitleGroups;if(!i)i=this._subtitleGroups=[];if(i.indexOf(t)===-1)i.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function fr(e,t){if(!t||!e)return!1;return e.indexOf(t)!==-1}function fl(){if(typeof matchMedia==="function"){let e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return e.matches===!0}return!1}function gl(e,t){let i=!1,s=[];if(e)i=e!=="SDR",s=[e];if(t){s=t.allowedVideoRanges||pi.slice(0);let r=s.join("")!=="SDR"&&!t.videoCodec;if(i=t.preferHDR!==void 0?t.preferHDR:r&&fl(),!i)s=["SDR"]}return{preferHDR:i,allowedVideoRanges:s}}function pl(e,t,i,s,r){let n=Object.keys(e),a=s==null?void 0:s.channels,l=s==null?void 0:s.audioCodec,o=r==null?void 0:r.videoCodec,u=a&&parseInt(a)===2,d=!1,c=!1,h=1/0,g=1/0,m=1/0,f=1/0,v=0,E=[],{preferHDR:p,allowedVideoRanges:S}=gl(t,r);for(let I=n.length;I--;){let A=e[n[I]];if(d||(d=A.channels[2]>0),h=Math.min(h,A.minHeight),g=Math.min(g,A.minFramerate),m=Math.min(m,A.minBitrate),S.filter((P)=>A.videoRanges[P]>0).length>0)c=!0}h=H(h)?h:0,g=H(g)?g:0;let T=Math.max(1080,h),L=Math.max(30,g);if(m=H(m)?m:i,i=Math.max(m,i),!c)t=void 0;let x=n.length>1;return{codecSet:n.reduce((I,A)=>{let _=e[A];if(A===I)return I;if(E=c?S.filter((P)=>_.videoRanges[P]>0):[],x){if(_.minBitrate>i)return Ye(A,`min bitrate of ${_.minBitrate} > current estimate of ${i}`),I;if(!_.hasDefaultAudio)return Ye(A,"no renditions with default or auto-select sound found"),I;if(l&&A.indexOf(l.substring(0,4))%5!==0)return Ye(A,`audio codec preference "${l}" not found`),I;if(a&&!u){if(!_.channels[a])return Ye(A,`no renditions with ${a} channel sound found (channels options: ${Object.keys(_.channels)})`),I}else if((!l||u)&&d&&_.channels["2"]===0)return Ye(A,"no renditions with stereo sound found"),I;if(_.minHeight>T)return Ye(A,`min resolution of ${_.minHeight} > maximum of ${T}`),I;if(_.minFramerate>L)return Ye(A,`min framerate of ${_.minFramerate} > maximum of ${L}`),I;if(!E.some((P)=>_.videoRanges[P]>0))return Ye(A,`no variants with VIDEO-RANGE of ${De(E)} found`),I;if(o&&A.indexOf(o.substring(0,4))%5!==0)return Ye(A,`video codec preference "${o}" not found`),I;if(_.maxScore=gi(I)||_.fragmentError>e[I].fragmentError))return I;return f=_.minIndex,v=_.maxScore,A},void 0),videoRanges:E,preferHDR:p,minFramerate:g,minBitrate:m,minIndex:f}}function Ye(e,t){ae.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Rn(e){return e.reduce((t,i)=>{let s=t.groups[i.groupId];if(!s)s=t.groups[i.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1};s.tracks.push(i);let r=i.channels||"2";if(s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||i.default,s.hasAutoSelect=s.hasAutoSelect||i.autoselect,s.hasDefault)t.hasDefaultAudio=!0;if(s.hasAutoSelect)t.hasAutoSelectAudio=!0;return t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function vl(e,t,i,s){return e.slice(i,s+1).reduce((r,n,a)=>{if(!n.codecSet)return r;let l=n.audioGroups,o=r[n.codecSet];if(!o)r[n.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{"2":0},hasDefaultAudio:!l,fragmentError:0};o.minBitrate=Math.min(o.minBitrate,n.bitrate);let u=Math.min(n.height,n.width);return o.minHeight=Math.min(o.minHeight,u),o.minFramerate=Math.min(o.minFramerate,n.frameRate),o.minIndex=Math.min(o.minIndex,a),o.maxScore=Math.max(o.maxScore,n.score),o.fragmentError+=n.fragmentError,o.videoRanges[n.videoRange]=(o.videoRanges[n.videoRange]||0)+1,r},{})}function gr(e,t){var i;return!!e&&e!==((i=t.loadLevelObj)==null?void 0:i.uri)}function yl(e,t,i){if(t===null||!Array.isArray(e)||!e.length||!H(t))return null;let s=e[0].programDateTime;if(t<(s||0))return null;let r=e[e.length-1].endProgramDateTime;if(t>=(r||0))return null;for(let n=0;n0&&l<0.0000015)i+=0.0000015;if(n&&e.level!==n.level&&n.end<=e.end)n=t[2+e.sn-t[0].sn]||null}else if(i===0&&t[0].start===0)n=t[0];if(n&&((!e||e.level===n.level)&&mr(i,s,n)===0||El(n,e,Math.min(r,s))))return n;let a=In.search(t,mr.bind(null,i,s));if(a&&(a!==e||!n))return a;return n}function El(e,t,i){if((t==null?void 0:t.start)===0&&t.level0){let s=t.tagList.reduce((r,n)=>{if(n[0]==="INF")r+=parseFloat(n[1]);return r},i);return e.start<=s}return!1}function mr(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;let s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));if(i.start+i.duration-s<=e)return 1;else if(i.start-s>e&&i.start)return-1;return 0}function Sl(e,t,i){let s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0))*1000;return(i.endProgramDateTime||0)-s>e}function Tl(e,t,i){if(e){if(e.startCC<=t&&e.endCC>=t){let s=e.fragments,{fragmentHint:r}=e;if(r)s=s.concat(r);let n;return In.search(s,(a)=>{if(a.cct)return-1;if(n=a,a.end<=i)return 1;if(a.start>i)return-1;return 0}),n||null}}return null}function xl(e,t){if(t===e.endSN&&e.fragmentHint)return e.fragmentHint;return e.fragments[1+t-e.startSN]||null}function pr(e){let t=e.details;if(t===R.BUFFER_ADD_CODEC_ERROR||t===R.MEDIA_SOURCE_REQUIRES_RESET)return!0;if(t===R.BUFFER_APPEND_ERROR){if(!_n(e))return!0}return!1}function _n(e){return e.details===R.BUFFER_APPEND_ERROR&&(e.error.name==="QuotaExceededError"||e.error.name==="InvalidStateError")}function li(e){let t={action:Ee.DoNothing,flags:ye.None};if(e)t.resolved=!0;return t}class ce{constructor(e,t){if(typeof e==="string")e=ce.parseAttrList(e,t);Te(this,e)}get clientAttrs(){return Object.keys(this).filter((e)=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);if(t>Number.MAX_SAFE_INTEGER)return 1/0;return t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let i=new Uint8Array(t.length/2);for(let s=0;sNumber.MAX_SAFE_INTEGER)return 1/0;return t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((s,r)=>(s[r.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=Ll.exec(this[e]);if(t===null)return;return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,s={},r='"';vr.lastIndex=0;while((i=vr.exec(e))!==null){let n=i[1].trim(),a=i[2],l=a.indexOf('"')===0&&a.lastIndexOf('"')===a.length-1,o=!1;if(l)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(l||o));else if(!o&&!l)switch(n){case"CLOSED-CAPTIONS":if(a==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ae.warn(`${e}: attribute ${n} is missing quotes`)}s[n]=a}return s}}function bl(e){return e!=="ID"&&e!=="CLASS"&&e!=="CUE"&&e!=="START-DATE"&&e!=="DURATION"&&e!=="END-DATE"&&e!=="END-ON-NEXT"}function Rl(e){return e==="SCTE35-OUT"||e==="SCTE35-IN"||e==="SCTE35-CMD"}class Di{constructor(e,t,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(s=t==null?void 0:t.tagOrder)!=null?s:i,t){let r=t.attr;for(let n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){ae.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=Te(new ce({}),r,e)}if(this.attr=e,t)this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd;else this._startDate=new Date(e["START-DATE"]);if("END-DATE"in e){let r=(t==null?void 0:t.endDate)||new Date(e["END-DATE"]);if(H(r.getTime()))this._endDate=r}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;if(e===void 0)return this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1});return e}get startTime(){let{tagAnchor:e}=this;if(e===null||e.programDateTime===null)return ae.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN;return e.start+(this.startDate.getTime()-e.programDateTime)/1000}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;if(t!==null)return this._dateAtEnd=new Date(this._startDate.getTime()+t*1000);return null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(H(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1000;return null}get plannedDuration(){if("PLANNED-DURATION"in this.attr)return this.attr.decimalFloatingPoint("PLANNED-DURATION");return null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Al}get isValid(){return!!this.id&&!this._badValueForSameId&&H(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||("X-ASSET-URI"in this.attr)||("X-ASSET-LIST"in this.attr))}get invalidReason(){if(!this.id)return"Missing ID";if(this._badValueForSameId)return`Date range ${this._badValueForSameId} mismatch`;if(!H(this.startDate.getTime()))return"Date range invalid start date";if(this.isInterstitial&&!(("X-ASSET-URI"in this.attr)||("X-ASSET-LIST"in this.attr)))return"Interstitial Date range missing X-ASSET-(LIST|URI)";if(!this.isValid)return"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)";return null}}class _s{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;if(this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced)this.misses=0;else this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some((t)=>{let i=t.decryptdata;if(!i)t.setKeyFormat(e.keyFormat),i=t.decryptdata;return!!i&&e.matches(i)})}get hasProgramDateTime(){if(this.fragments.length)return H(this.fragments[this.fragments.length-1].programDateTime);return!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Dn}get drift(){let e=this.driftEndTime-this.driftStartTime;if(e>0)return(this.driftEnd-this.driftStart)*1000/e;return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;if((e=this.partList)!=null&&e.length)return this.partList[this.partList.length-1].end;return this.fragmentEnd}get fragmentEnd(){if(this.fragments.length)return this.fragments[this.fragments.length-1].end;return 0}get fragmentStart(){if(this.fragments.length)return this.fragments[0].start;return 0}get age(){if(this.advancedDateTime)return Math.max(Date.now()-this.advancedDateTime,0)/1000;return 0}get lastPartIndex(){var e;if((e=this.partList)!=null&&e.length)return this.partList[this.partList.length-1].index;return-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;if((e=this.partList)!=null&&e.length)return this.partList[this.partList.length-1].fragment.sn;return this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Cn(e,t){if(e.length===t.length)return!e.some((i,s)=>i!==t[s]);return!1}function yr(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;return Cn(e,t)}function Ot(e){return e==="AES-128"||e==="AES-256"||e==="AES-256-CTR"}function kn(e){switch(e){case"AES-128":case"AES-256":return ot.cbc;case"AES-256-CTR":return ot.ctr;default:throw Error(`invalid full segment method ${e}`)}}class xt{static clearKeyUriToKeyIdMap(){ei={}}static setKeyIdForUri(e,t){ei[e]=t}static addKeyIdForUri(e){let t=Object.keys(ei).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),ei[e]=i,i}constructor(e,t,i,s=[1],r=null,n){if(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.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Ot(e),n!=null&&n.startsWith("0x"))this.keyId=new Uint8Array(pn(n))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Cn(e.keyFormatVersions,this.keyFormatVersions)&&yr(e.iv,this.iv)&&yr(e.keyId,this.keyId)}isSupported(){if(this.method){if(Ot(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES"}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Ot(this.method)){let i=this.iv;if(!i){if(typeof e!=="number")ae.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0;i=Il(e)}return new xt(this.method,this.uri,"identity",this.keyFormatVersions,i)}return this}}function Il(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}class Ge{static findGroup(e,t){for(let i=0;i0&&r.length({id:o.attrs.AUDIO,audioCodec:o.audioCodec})),SUBTITLES:n.map((o)=>({id:o.attrs.SUBTITLES,textCodec:o.textCodec})),"CLOSED-CAPTIONS":[]},l=0;Sr.lastIndex=0;while((s=Sr.exec(e))!==null){let o=new ce(s[1],i),u=o.TYPE;if(u){let d=a[u],c=r[u]||[];r[u]=c;let h=o.LANGUAGE,g=o["ASSOC-LANGUAGE"],m=o.CHANNELS,f=o.CHARACTERISTICS,v=o["INSTREAM-ID"],E={attrs:o,bitrate:0,id:l++,groupId:o["GROUP-ID"]||"",name:o.NAME||h||"",type:u,default:o.bool("DEFAULT"),autoselect:o.bool("AUTOSELECT"),forced:o.bool("FORCED"),lang:h,url:o.URI?Ge.resolve(o.URI,t):""};if(g)E.assocLang=g;if(m)E.channels=m;if(f)E.characteristics=f;if(v)E.instreamId=v;if(d!=null&&d.length){let p=Ge.findGroup(d,E.groupId)||d[0];br(E,p,"audioCodec"),br(E,p,"textCodec")}c.push(E)}}return r}static parseLevelPlaylist(e,t,i,s,r,n){var a;let l={url:t},o=new _s(t),u=o.fragments,d=[],c=null,h=0,g=0,m=0,f=0,v=0,E=null,p=new yt(s,l),S,T,L,x=-1,b=!1,I=null,A;if(ji.lastIndex=0,o.m3u8=e,o.hasVariableRefs=!1,((a=ji.exec(e))==null?void 0:a[0])!=="#EXTM3U")return o.playlistParsingError=Error("Missing format identifier #EXTM3U"),o;while((S=ji.exec(e))!==null){if(b){if(b=!1,p=new yt(s,l),p.playlistOffset=m,p.setStart(m),p.sn=h,p.cc=f,v)p.bitrate=v;if(p.level=i,c){if(p.initSegment=c,c.rawProgramDateTime)p.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null;if(I)p.setByteRange(I),I=null}}let O=S[1];if(O){p.duration=parseFloat(O);let C=(" "+S[2]).slice(1);p.title=C||null,p.tagList.push(C?["INF",O,C]:["INF",O])}else if(S[3]){if(H(p.duration)){var _;if(p.playlistOffset=m,p.setStart(m),L)Ir(p,L,o);p.sn=h,p.level=i,p.cc=f;let C=(" "+S[3]).slice(1);p.relurl=C,us(p,E,d),E=p,m+=p.duration,h++,g=0;let k=p.byteRange;if(k.length===2)p.bitrate=(k[1]-k[0])*8/p.duration|0;if(o.iframesOnly&&k[0]&&((_=c)==null?void 0:_.cc)!==f){let G=new yt(s,l);if(G.relurl=p.relurl,G.setByteRange(`${Math.min(k[0],1316)}@0`),G.level=i,G.sn="initSegment",L){if(G.levelkeys=L,L.identity)G._decryptdata=L.identity.getDecryptData(0)}c=G,p.initSegment=c}u.push(p),b=!0}}else{if(S=S[0].match(Dl),!S){ae.warn("No matches on slow regex match for level playlist!");continue}for(T=1;TD&&(D.cc=f));break;case"KEY":{let D=xr(k,t,o);if(D.isSupported()){if(D.method==="NONE"){L=void 0;break}if(!L)L={};let U=L[D.keyFormat];if(!(U!=null&&U.matches(D))){if(U)L=Te({},L);L[D.keyFormat]=D}}else ae.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${k}" (light build)`);break}case"START":o.startTimeOffset=Lr(k);break;case"MAP":{let D=new ce(k,o);if(p.duration){let U=new yt(s,l);if(Rr(U,D,i,L),c=U,p.initSegment=c,c.rawProgramDateTime&&!p.rawProgramDateTime)p.rawProgramDateTime=c.rawProgramDateTime}else{let U=p.byteRangeEndOffset;if(U){let F=p.byteRangeStartOffset;I=`${U-F}@${F}`}else I=null;Rr(p,D,i,L),c=p,b=!0}c.cc=f;break}case"SERVER-CONTROL":{if(A)Je(o,C,S);A=new ce(k),o.canBlockReload=A.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=A.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&A.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=A.optionalFloat("PART-HOLD-BACK",0),o.holdBack=A.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{if(o.partTarget)Je(o,C,S);let D=new ce(k);o.partTarget=D.decimalFloatingPoint("PART-TARGET");break}case"PART":{let D=o.partList;if(!D)D=o.partList=[];let U=g>0?D[D.length-1]:void 0,F=g++,M=new ce(k,o),q=new Es(M,p,l,F,U);D.push(q),p.duration+=q.duration;break}case"PRELOAD-HINT":{let D=new ce(k,o);o.preloadHint=D;break}case"RENDITION-REPORT":{let D=new ce(k,o);o.renditionReports=o.renditionReports||[],o.renditionReports.push(D);break}default:ae.warn(`line parsed but not handled: ${S}`);break}}}if(E&&!E.relurl){if(u.pop(),m-=E.duration,o.partList)o.fragmentHint=E}else if(o.partList){if(us(p,E,d),p.cc=f,o.fragmentHint=p,L)Ir(p,L,o)}if(!o.targetduration)o.playlistParsingError=Error("Missing Target Duration");let P=u.length,w=u[0],Y=u[P-1];if(m+=o.skippedSegments*o.targetduration,m>0&&P&&Y){o.averagetargetduration=m/P;let O=Y.sn;if(o.endSN=O!=="initSegment"?O:0,!o.live)Y.endList=!0;if(x>0){if(kl(u,x,x>P-1?p:null),w)d.unshift(w)}}if(o.fragmentHint)m+=o.fragmentHint.duration;if(o.totalduration=m,d.length&&o.dateRangeTagCount&&w)Pn(d,o);return o.endCC=f,o}}function Tr(e,t,i,s,r,n){var a;if(t===void 0)return null;let l=t,o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Ge.resolve(l,i)},u=e.decimalResolution("RESOLUTION");if(u)o.width=u.width,o.height=u.height;Ar(e.CODECS,o);let d=e["SUPPLEMENTAL-CODECS"];if(d)o.supplemental={},Ar(d,o.supplemental);if(!((a=o.unknownCodecs)!=null&&a.length))r.push(o);if(n)o.iframes=!0;return o}function Pn(e,t){let i=e.length;if(!i)if(t.hasProgramDateTime){let l=t.fragments[t.fragments.length-1];e.push(l),i++}else return;let s=e[i-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let l=n.length;l--;){let o=t.dateRanges[n[l]],u=o.startDate.getTime();o.tagAnchor=s.ref;for(let d=i;d--;){var a;if(((a=e[d])==null?void 0:a.sn)=l||s===0){var a;let o=(((a=i[s+1])==null?void 0:a.start)||r)-n.start;if(t<=l+o*1000){let u=n.sn-e.startSN,d=e.fragments;if(u>=0&&ui.length){let c=i[s+1]||d[d.length-1],h=Math.min(c.sn-e.startSN,d.length-1);for(let g=h;g>u;g--){let m=d[g].programDateTime;if(t>=m&&ts);["video","audio","text","image"].forEach((s)=>{let r=i.filter((n)=>Ls(n,s));if(r.length)t[`${s}Codec`]=r.map((n)=>n.split("/")[0]).join(","),i=i.filter((n)=>r.indexOf(n)===-1)}),t.unknownCodecs=i}function br(e,t,i){let s=t[i];if(s)e[i]=s}function kl(e,t,i){if(i||(i=e[t]),!i)return;for(let s=t;s--;){let r=e[s];if(!r)return;r.programDateTime=i.programDateTime-r.duration*1000,i=r}}function us(e,t,i){if(e.rawProgramDateTime)i.push(e);else if(t!=null&&t.programDateTime)e.programDateTime=t.endProgramDateTime}function Rr(e,t,i,s){if(e.relurl=t.URI,t.BYTERANGE)e.setByteRange(t.BYTERANGE);if(e.level=i,e.sn="initSegment",s)e.levelkeys=s;e.initSegment=null}function Ir(e,t,i){e.levelkeys=t;let{encryptedFragments:s}=i;if((!s.length||s[s.length-1].levelkeys!==t)&&Object.keys(t).some((r)=>t[r].isCommonEncryption))s.push(e)}function Je(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function Pl(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function qi(e,t){let i=t.startPTS;if(H(i)){let s=0,r;if(t.sn>e.sn)s=i-e.start,r=e;else s=e.start-i,r=t;if(r.duration!==s)r.setDuration(s)}else if(t.sn>e.sn)if(e.cc===t.cc&&e.minEndPTS)t.setStart(e.start+(e.minEndPTS-e.start));else t.setStart(e.start+e.duration);else t.setStart(Math.max(e.start-t.duration,0))}function wn(e,t,i,s,r,n,a,l){if(s-i<=0)l.warn("Fragment should have a positive duration",t),s=i+t.duration,n=r+t.duration;let u=i,d=s,c=t.startPTS,h=t.endPTS;if(H(c)){let p=Math.abs(c-i);if(e&&p>e.totalduration)l.warn(`media timestamps and playlist times differ by ${p}s for level ${t.level} ${e.url}`);else if(!H(t.deltaPTS))t.deltaPTS=p;else t.deltaPTS=Math.max(p,t.deltaPTS);u=Math.max(i,c),i=Math.min(i,c),r=t.startDTS!==void 0?Math.min(r,t.startDTS):r,d=Math.min(s,h),s=Math.max(s,h),n=t.endDTS!==void 0?Math.max(n,t.endDTS):n}let g=i-t.start;if(t.start!==0)t.setStart(i);t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=u,t.startDTS=r,t.endPTS=s,t.minEndPTS=d,t.endDTS=n;let m=t.sn;if(!e||me.endSN)return 0;let f,v=m-e.startSN,E=e.fragments;E[v]=t;for(f=v;f>0;f--)qi(E[f],E[f-1]);for(f=v;f=0;d--){let c=r[d].initSegment;if(c){s=c;break}}if(e.fragmentHint)delete e.fragmentHint.endPTS;let n;Ml(e,t,(d,c,h,g)=>{if((!t.startCC||t.skippedSegments)&&c.cc!==d.cc){let m=d.cc-c.cc;for(let f=h;f{var c;if(d&&(!d.initSegment||d.initSegment.relurl===((c=s)==null?void 0:c.relurl)))d.initSegment=s});if(t.skippedSegments){if(t.deltaUpdateFailed=a.some((d)=>!d),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=t.skippedSegments;d--;)a.shift();t.startSN=a[0].sn}else{if(t.canSkipDateRanges)t.dateRanges=Ol(e.dateRanges,t,i);let d=e.fragments.filter((c)=>c.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime){for(let c=1;c{c.elementaryStreams=d.elementaryStreams,c.stats=d.stats,c.gap=d.gap||c.gap}),n){let d=t.iframesOnly&&n.type===J.MAIN;wn(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,d,i)}else On(e,t);if(a.length)t.totalduration=t.edge-a[0].start;t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let u=t.advancedDateTime;if(t.advanced&&u){let d=t.edge;if(!t.driftStart)t.driftStartTime=u,t.driftStart=d;t.driftEndTime=u,t.driftEnd=d}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;if(t.requestScheduled===-1)t.requestScheduled=e.requestScheduled}function Ol(e,t,i){let{dateRanges:s,recentlyRemovedDateranges:r}=t,n=Te({},e);if(r)r.forEach((o)=>{delete n[o]});let l=Object.keys(n).length;if(!l)return s;return Object.keys(s).forEach((o)=>{let u=n[o],d=new Di(s[o].attr,u);if(d.isValid){if(n[o]=d,!u)d.tagOrder+=l}else i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${De(s[o].attr)}"`)}),n}function Fl(e,t,i){if(e&&t){let s=0;for(let r=0,n=e.length;r=0,l=0;if(a&&rt){let n=s[s.length-1].duration*1000;if(n{var s;(s=t.details)==null||s.fragments.forEach((r)=>{if(r.level=i,r.initSegment)r.initSegment.level=i})})}function $l(e,t){if(e!==t&&t)return Cr(e)!==Cr(t);return!1}function Cr(e){return e.replace(/\?[^?]*$/,"")}class Bn{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=0.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;if(e)e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){let{hls:e}=this;if(e)e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let s=i.length;s--;){let r=i[s];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){let{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){let a=s[r[n]];if((a==null?void 0:a.body.type)===t&&(!i||a.buffered)){let l=a.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,s,r,n){if(this.timeRanges)this.timeRanges[e]=t;let a=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((l)=>{let o=this.fragments[l];if(!o||!this.hls)return;let u=o.body;if(a>=u.sn)return;if(!o.buffered&&(!o.loaded||n)){if(u.type===i)this.removeFragment(u);return}let d=o.range[e];if(!d)return;if(d.time.length===0){this.removeFragment(u);return}if(d.time.some((c)=>{let h=!this.isTimeBuffered(c.startPTS,c.endPTS,t);if(h)this.removeFragment(u);return h}),s&&s!==u&&Pt()){let c=s.endPTS,h=u.startPTS;if(c&&h&&o.range.video){let g=h-c;if(g<0&&g>-0.1)this.removeFragment(u),this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:c+0.004,endOffset:1/0,type:"video"})}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:i,part:s,id:r}=e;if(!t||!Fe(i))return;let n=vt(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;let l=!i.relurl;Object.keys(t).forEach((u)=>{let d=i.elementaryStreams[u];if(!d)return;let c=t[u],h=l||d.partial===!0;a.range[u]=this.getBufferedTimes(i,s,h,c),this.detectEvictedFragments(u,c,r,i,s)}),a.loaded=null;let o=Object.keys(a.range);if(o.length){if(this.bufferedEnd(a,i),!ti(a))this.removeParts(i.sn-1,i.type);if(!s){let u=Math.min(0.004,i.duration);o.some((d)=>{var c;let h=(c=a.range[d])==null?void 0:c.time,g=h.length===0||h.length===1&&h[0].endPTS-h[0].startPTSs.fragment.sn>=e)}fragBuffered(e,t){let i=vt(e),s=this.fragments[i];if(!s&&t){if(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap)this.hasGaps=!0}if(s)s.loaded=null,this.bufferedEnd(s,e);return s}getBufferedTimes(e,t,i,s){let r={time:[],partial:i},n=e.start,a=e.end,l=e.minEndPTS||a,o=e.maxStartPTS||n;for(let u=0;u=d&&l<=c){r.time.push({startPTS:Math.max(n,s.start(u)),endPTS:Math.min(a,s.end(u))});break}else if(nd){let h=Math.max(n,s.start(u)),g=Math.min(a,s.end(u));if(g>h)r.partial=!0,r.time.push({startPTS:h,endPTS:g})}else if(a<=d)break}return r}getPartialFragment(e){let t=null,i,s,r,n=0,{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach((o)=>{let u=l[o];if(!u)return;if(ti(u)){if(s=u.body.start-a,r=u.body.end+a,e>=s&&e<=r){if(i=Math.min(e-s,r-e),n<=i)t=u.body,n=i}}}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||ti(t))}getState(e){let t=vt(e),i=this.fragments[t];if(i)if(!i.buffered)return Ae.APPENDING;else if(ti(i))return Ae.PARTIAL;else return Ae.OK;return Ae.NOT_LOADED}isTimeBuffered(e,t,i){let s,r;for(let n=0;n=s&&t<=r)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Fe(t.frag)||t.frag.bitrateTest)return;let i=t.frag,s=t.part?null:t,r=vt(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:s,timeRanges:r}=t;if(!Fe(i))return;let n=i.type;if(s){let a=this.activePartLists[n];if(!a)this.activePartLists[n]=a=[];a.push(s)}this.timeRanges=r}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=vt(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){let r=t[i[s]];if((r==null?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,i){let{fragments:s}=this,r=0,n=0,a=Object.keys(s);for(let l=0;l=i)return n}}return n>0?n:0}removeFragmentsInRange(e,t,i,s,r){if(s&&!this.hasGaps)return;Object.keys(this.fragments).forEach((n)=>{let a=this.fragments[n];if(!a)return;let l=a.body;if(l.type!==i||s&&!l.gap)return;if(l.starte&&(a.buffered||r))this.removeFragment(l)})}removeFragment(e){let t=vt(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let s=e.sn;this.activePartLists[e.type]=kr(i,(r)=>r.fragment.sn!==s)}if(delete this.fragments[t],e.endList)delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;if(t)t.forEach((i)=>i.clearElementaryStreamInfo())}}function ti(e){var t,i,s,r;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(i=e.range.audio)!=null&&i.partial||(s=e.range.audiovideo)!=null&&s.partial||(r=e.range.subs)!=null&&r.partial)}function vt(e){return`${e.type}_${e.level}_${e.sn}`}function kr(e,t){return e.filter((i)=>{let s=t(i);if(!s)i.clearElementaryStreamInfo();return s})}class Un{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case ot.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ot.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Bl(e){let t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);if(i)return e.slice(0,t-i);return e}class Gn{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],l=this.invSubMix,o=l[0],u=l[1],d=l[2],c=l[3],h=new Uint32Array(256),g=0,m=0,f=0;for(f=0;f<256;f++)if(f<128)h[f]=f<<1;else h[f]=f<<1^283;for(f=0;f<256;f++){let v=m^m<<1^m<<2^m<<3^m<<4;v=v>>>8^v&255^99,e[g]=v,t[v]=g;let E=h[g],p=h[E],S=h[p],T=h[v]*257^v*16843008;if(s[g]=T<<24|T>>>8,r[g]=T<<16|T>>>16,n[g]=T<<8|T>>>24,a[g]=T,T=S*16843009^p*65537^E*257^g*16843008,o[v]=T<<24|T>>>8,u[v]=T<<16|T>>>16,d[v]=T<<8|T>>>24,c[v]=T,!g)g=m=1;else g=E^h[h[h[S^E]]],m^=h[h[m]]}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=!0,s=0;while(s=i.length)return i;return i.slice(s.start,s.end)}return Bl(i)}reset(){if(this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter)this.softwareDecrypter=null}decrypt(e,t,i,s,r){if(this.decryptRange=r,this.useSoftware||r)return new Promise((n,a)=>{let l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,i,s);let o=this.flush();if(o)n(o.buffer);else a(Error("[softwareDecrypt] Failed to decrypt data"))});return this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){let{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==ot.cbc||t.byteLength!==16)return ae.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;if(this.logOnce("JS AES decrypt"),a)e=He(a,e),this.remainderData=null;let l=this.getValidChunk(e);if(!l.length)return null;if(r)i=r;let o=this.softwareDecrypter;if(!o)o=this.softwareDecrypter=new Gn;o.expandKey(t);let u=n;if(this.currentResult=o.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,!u)return null;return u}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new Vn(this.subtle,t,s)}return this.fastAesKey.expandKey().then((r)=>{if(!this.subtle)return Promise.reject(Error("web crypto not initialized"));return this.logOnce("WebCrypto AES decrypt"),new Un(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,r)}).catch((r)=>(ae.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){let r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);let n=this.flush();if(n)return n.buffer}throw Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%Gl;if(i!==e.length)t=e.slice(0,i),this.remainderData=e.slice(i);return t}logOnce(e){if(!this.logEnabled)return;ae.log(`[decrypter]: ${e}`),this.logEnabled=!1}}class ds{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){if(this.loader)this.loader.destroy(),this.loader=null}abort(){if(this.loader)this.loader.abort()}load(e,t,i,s){let r=e.url;if(!r)return Promise.reject(new Ue({type:Q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();let n=this.config,a=n.fLoader,l=n.loader;return new Promise((o,u)=>{if(this.loader)this.loader.destroy();if(e.gap)if(e.tagList.some((f)=>f[0]==="GAP")){u(Or(e));return}else e.gap=!1;let d=this.loader=a?new a(n):new l(n),c=wr(e,null,t);e.loader=d;let h=sr(n.fragLoadPolicy.default),g={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Pr};d.stats.retry=e.stats.retry,e.stats=d.stats;let m={onSuccess:(f,v,E,p)=>{this.resetLoader(e,d);let S=f.data;if(E.resetIV&&e.decryptdata)e.decryptdata.iv=new Uint8Array(S.slice(0,16)),S=S.slice(16);o({frag:e,part:null,payload:S,networkDetails:p})},onError:(f,v,E,p)=>{this.resetLoader(e,d),u(new Ue({type:Q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Me({url:r,data:void 0},f),error:Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:E,stats:p}))},onAbort:(f,v,E)=>{this.resetLoader(e,d),u(new Ue({type:Q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error("Aborted"),networkDetails:E,stats:f}))},onTimeout:(f,v,E)=>{this.resetLoader(e,d),u(new Ue({type:Q.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${g.timeout}ms`),networkDetails:E,stats:f}))}};if(i){let f=this.gateProgress(i,s);m.onProgress=(v,E,p,S)=>f({frag:e,part:null,payload:p,networkDetails:S})}d.load(c,g,m)})}gateProgress(e,t){let i=e;if(t){let s=[],r=!1;t.then(()=>{r=!0,s.forEach((n)=>e(n)),s.length=0}).catch(()=>{}),i=(n)=>{if(r)e(n);else s.push(n)}}return i}loadPart(e,t,i){this.abort();let s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,l)=>{if(this.loader)this.loader.destroy();if(e.gap||t.gap){l(Or(e,t));return}let o=this.loader=r?new r(s):new n(s),u=wr(e,t);e.loader=o;let d=sr(s.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Pr};t.stats=o.stats,o.load(u,c,{onSuccess:(h,g,m,f)=>{this.resetLoader(e,o),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:h.data,networkDetails:f};i(v),a(v)},onError:(h,g,m,f)=>{this.resetLoader(e,o),l(new Ue({type:Q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Me({url:u.url,data:void 0},h),error:Error(`HTTP Error ${h.code} ${h.text}`),networkDetails:m,stats:f}))},onAbort:(h,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,o),l(new Ue({type:Q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error("Aborted"),networkDetails:m,stats:h}))},onTimeout:(h,g,m)=>{this.resetLoader(e,o),l(new Ue({type:Q.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${c.timeout}ms`),networkDetails:m,stats:h}))}})})}updateStatsFromPart(e,t){let i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){let l=Math.round(e.duration/t.duration),o=Math.min(Math.round(i.loaded/r),l),d=(l-o)*Math.round(i.loaded/o);i.total=i.loaded+d}else i.total=Math.max(i.loaded,i.total);let n=i.loading,a=s.loading;if(n.start)n.first+=a.first-a.start;else n.start=a.start,n.first=a.first;n.end=a.end}resetLoader(e,t){if(e.loader=null,e.url=null,this.loader===t)self.clearTimeout(this.partLoadTimeout),this.loader=null;t.destroy()}}function wr(e,t=null,i){let s=t||e,r={type:se.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=yi(e,t,i);if(n.resetIV)r.resetIV=!0;if(n.byteRange)r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end;return r}function yi(e,t=null,i){let s={},r=t||e,n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(H(n)&&H(a)){var l;if((e.sn==="initSegment"||i)&&Vl((l=e.decryptdata)==null?void 0:l.method)){let o=Math.floor(n/16)*16,u=Math.ceil(a/16)*16;if(s.decryptRange={start:n-o,end:a-o},o>=16)s.resetIV=!0,o=o-16;s.byteRange={start:o,end:u}}else s.byteRange={start:n,end:a}}return s}function Or(e,t){let i=Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:Q.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};if(t)s.part=t;return(t?t:e).stats.aborted=!0,new Ue(s)}function Vl(e){return e==="AES-128"||e==="AES-256"}class ki{constructor(e,t,i,s=0,r=-1,n=!1,a,l,o){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.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=ii(),this.buffering={audio:ii(),video:ii(),audiovideo:ii()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=n,this.duration=a||0,this.decryptRange=o,this.iframe=l||!1}}function ii(){return{start:0,executeStart:0,executeEnd:0,end:0}}class Z{static isBuffered(e,t){if(e){let i=Z.getBuffered(e);for(let s=i.length;s--;)if(t>=i.start(s)&&t<=i.end(s))return!0}return!1}static bufferedRanges(e){if(e){let t=Z.getBuffered(e);return Z.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i1)e.sort((u,d)=>u.start-d.start||d.end-u.end);let s=-1,r=[];if(i)for(let u=0;u=e[u].start&&t<=e[u].end)s=u;let d=r.length;if(d){let c=r[d-1].end;if(e[u].start-cc)r[d-1].end=e[u].end}else r.push(e[u])}else r.push(e[u])}else r=e;let n=0,a,l=t,o=t;for(let u=0;u=d&&t<=c)s=u;if(t+i>=d&&te.startCC)return!0}return!1}function Mr(e,t){let i=e.start+t;e.setStart(i)}function Hn(e,t){let i=t.fragments;for(let s=0,r=i.length;s!!h)[0],a=Ft(s,n.cc)||s[Math.floor(s.length/2)];let o=n.programDateTime,u=a.programDateTime;if(!o||!u)return;let d=(u-o)/1000;if(Math.abs(d)>Math.max(60,e.totalduration)){i.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${e.totalduration})`);return}let c=d-(a.start-n.start);i.log(`Aligning playlists using PDT (diff: ${c})`),Hn(c,e)}function be(e,t,i){Se(e,t,i),e.addEventListener(t,i)}function Se(e,t,i){e.removeEventListener(t,i)}function cs(e){let t="",i=e.length;for(let s=0;s{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise((t)=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){if(this.queues===null)return;[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e)=>{var t;let i=(t=e[0])==null?void 0:t.label;if(i==="async-blocker"||i==="async-blocker-prepend")e[0].execute(),e.splice(0,1);else if(i==="block-audio")e.splice(0,1)})}insertNext(e,t){if(this.queues===null)return;this.queues[t].splice(1,0,...e)}unblockAudio(){var e;if(this.queues===null)return;if(((e=this.current("audio"))==null?void 0:e.label)==="block-audio")this.shiftAndExecuteNext("audio")}audioBlocking(){if(this.queues===null)return!1;return this.queues.audio.some((e)=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let s=t[0];try{s.execute()}catch(r){var i;if(s.onError(r),this.queues===null||this.tracks===null)return;let n=(i=this.tracks[e])==null?void 0:i.buffer;if(!(n!=null&&n.updating))this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){if(this.queues===null)return;this.queues[e].shift(),this.executeNext(e)}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;if(e===null||t===null)return"";return` +${this.list("video")} +${this.list("audio")} +${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],s=i==null?void 0:i.buffer;if(!s)return"none";return`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map((i)=>i.label).join(", "))||""}}function $r(e){let t=e.querySelectorAll("source");[].slice.call(t).forEach((i)=>{e.removeChild(i)})}function zl(e,t){let i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}function zi(e){return e==="audio"?1:0}function Br(e,t){return`${e?"":" - triggering recovery"}${t?" with HTMLMediaElement Error: "+t.message:""}`}function Ur(e){return`${e.type}_${e.sn}_${e.level}`}function Xi(e,t){let{start:i,end:s}=t,r=0;for(let n=0;n=s)break;let l=Math.max(i,a.start),o=Math.min(s,a.end);if(o>l)r+=o-l}return r}function Gr(e,t){return t.duration-e<=0.05}class Pi{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){if(this.hls)this.unregisterListener();if(this.timer||this.observer)this.stopCapping();this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){let{hls:e}=this;if(e)e.on(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;if(e)e.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){if(!this.hls)return;let i=this.hls.levels[t.droppedLevel];if(this.isLevelAllowed(i))this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){let i=t.media;if(this.clientRect=null,!this.hls)return;if(i instanceof HTMLVideoElement){if(this.media=i,this.hls.config.capLevelToPlayerSize)this.observe()}else this.media=null;if((this.timer||this.observer)&&this.hls.levels.length>1)this.detectPlayerSize()}onManifestParsed(e,t){if(this.restrictedLevels=[],t.video)this.startCapping();this.onLevelsUpdated()}onLevelsUpdated(){if(!this.hls)return;if((this.timer||this.observer)&&(H(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){let e=this.hls.levels;if(e.length>1&&e.some((t)=>!!t.videoCodec))this.startCapping()}}onBufferCodecs(e,t){if(t.video)this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}let e=this.hls.levels;if(e.length>1){let t=this.hls,i=this.getMaxLevel(e.length-1);if(i!==this.autoLevelCapping)t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);if(t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController)this.streamController.nextLevelSwitch();this.autoLevelCapping=t.autoLevelCapping}else if(e.length===1)this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((s,r)=>this.isLevelAllowed(s)&&r<=e);if(!this.observer)this.clientRect=null;return Pi.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;if(e)this.observer=new e((t)=>{var i;let s=(i=t[0])==null?void 0:i.contentRect;if(s)this.clientRect=s,this.detectPlayerSize()});if(this.observer&&this.media)this.observer.observe(this.media)}startCapping(){var e;if(this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize))return;if(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),!this.observer)this.timer=self.setInterval(this.detectPlayerSize.bind(this),1000);this.detectPlayerSize()}stopCapping(){if(this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer)self.clearInterval(this.timer),this.timer=void 0;if(this.observer)this.observer.disconnect(),this.observer=void 0}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();if(t.width=i.width,t.height=i.height,!t.width&&!t.height)t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:i}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch(s){}return Math.min(e,i)}isLevelAllowed(e){return!this.restrictedLevels.some((i)=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;let s=(a,l)=>{if(!l)return!0;return a.width!==l.width||a.height!==l.height},r=e.length-1,n=Math.max(t,i);for(let a=0;a=n||l.height>=n)&&s(l,e[a+1])){r=a;break}}return r}}function Vr(e,t,i,s){if(!e)return;Object.keys(t).forEach((r)=>{let n=e.filter((a)=>a.groupId===r).map((a)=>{let l=Te({},a);return l.details=void 0,l.attrs=new ce(l.attrs),l.url=l.attrs.URI=jn(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),l.groupId=l.attrs["GROUP-ID"]=t[r],l.attrs["PATHWAY-ID"]=s,l});e.push(...n)})}function jn(e,t,i,s){if(t){let{[i]:l}=s;if(l){let o=l[t];if(o)return o}}let{HOST:r,PARAMS:n}=s,a=new self.URL(e);if(r)a.hostname=r;if(n)Object.keys(n).sort().forEach((l)=>{if(l)St(a,l,n[l])});return a.href}class Os{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){if(this.timer)clearInterval(this.timer);this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let s=t.media instanceof self.HTMLVideoElement?t.media:null;if(this.media=s,s&&typeof s.getVideoPlaybackQuality==="function")this.isVideoPlaybackQualityAvailable=!0;self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let s=performance.now();if(t){if(this.lastTime){let r=s-this.lastTime,n=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,l=1000*n/r,o=this.hls;if(o.trigger(y.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),l>0){if(n>o.config.fpsDroppedMonitoringThreshold*a){let u=o.currentLevel;if(o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(o.autoLevelCapping===-1||o.autoLevelCapping>=u))u=u-1,o.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:o.currentLevel}),o.autoLevelCapping=u,this.streamController.nextLevelSwitch()}}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Ql(){if(Hr)return Qi.exports;return Hr=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}if(Object.create){if(s.prototype=Object.create(null),!new s().__proto__)i=!1}function r(o,u,d){this.fn=o,this.context=u,this.once=d||!1}function n(o,u,d,c,h){if(typeof d!=="function")throw TypeError("The listener must be a function");var g=new r(d,c||o,h),m=i?i+u:u;if(!o._events[m])o._events[m]=g,o._eventsCount++;else if(!o._events[m].fn)o._events[m].push(g);else o._events[m]=[o._events[m],g];return o}function a(o,u){if(--o._eventsCount===0)o._events=new s;else delete o._events[u]}function l(){this._events=new s,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],d,c;if(this._eventsCount===0)return u;for(c in d=this._events)if(t.call(d,c))u.push(i?c.slice(1):c);if(Object.getOwnPropertySymbols)return u.concat(Object.getOwnPropertySymbols(d));return u},l.prototype.listeners=function(u){var d=i?i+u:u,c=this._events[d];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,g=c.length,m=Array(g);h0){let n=su(e.cues,t,i);for(let a=0;ae[i].endTime)return-1;let s=0,r=i,n;while(s<=r)if(n=Math.floor((r+s)/2),te[n].startTime&&s-1)for(let n=r,a=e.length;n=t&&l.endTime<=i)s.push(l);else if(l.startTime>i)return s}return s}function fs(){if(typeof self>"u")return;return self.VTTCue||self.TextTrackCue}function jr(e,t,i,s,r){let n=new e(t,i,"");try{if(n.value=s,r)n.type=r}catch(a){n=new e(t,i,De(r?Me({type:r},s):s))}return n}class Xn{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{if(!this.hls)return;this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;if(e)e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){let{hls:e}=this;if(e)e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;if(t)this.updateDateRangeCues(t)}onMediaDetaching(e,t){if(this.media=null,!!t.transferMedia)return;if(this.id3Track)this.id3Track.remove(),this.id3Track=null;this.dateRangeCuesAppended={}}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return eu(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;let{samples:r}=t;if(!this.id3Track)this.id3Track=this.createTrack(this.media);let n=fs();if(!n)return;for(let a=0;asi)d=si;if(d-u<=0)d=u+ru;for(let h=0;hu.type===Re.audioId3&&l;else if(s==="video")o=(u)=>u.type===Re.emsg&&a;else o=(u)=>u.type===Re.audioId3&&l||u.type===Re.emsg&&a;tu(r.track,t,i,o)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){if(Math.abs(t.drift)>0.01)this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;let a=fs();if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:o}=e,u=Object.keys(o),d=this.dateRangeCuesAppended;if(l&&t){var c;if((c=l.track.cues)!=null&&c.length){let m=Object.keys(d).filter((f)=>u.indexOf(f)===-1);for(let f=m.length;f--;){var h;let v=m[f],E=(h=d[v])==null?void 0:h.cues;if(delete d[v],E)Object.keys(E).forEach((p)=>{let S=E[p];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(S)}catch(T){}}})}}else d=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(u.length===0||!H(g==null?void 0:g.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m{if(P!==v.id){let w=o[P];if(w.class===v.class&&w.startDate>v.startDate&&(!_||v.startDate<_.startDate))return w}return _},null);if(A)L=A.startTime,T=!0}let I=Object.keys(v.attr);for(let A=0;A0.01)P.startTime=E,P.endTime=L}else if(a){let w=v.attr[_];if(Rl(_))w=pn(w);let O=jr(a,E,L,{key:_,data:w},Re.dateRange);if(O)O.id=f,this.id3Track.track.addCue(O),S[_]=O}}d[f]={cues:S,dateRange:v,durationKnown:T}}}}class Qn{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:t}=this,i=this.levelDetails;if(!t||!i||!this.hls)return;this.currentTime=t.currentTime;let s=this.hls.config,r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=s;if(!n||a===1||!i.live)return;let l=this.targetLatency;if(l===null)return;let o=r-l,u=Math.min(this.maxLatency,l+i.targetduration);if(o0.05&&this.forwardBufferLength>1){let c=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-0.75*o-this.edgeStalled))*20)/20,g=Math.min(c,Math.max(1,h));this.changeMediaPlaybackRate(t,g)}else if(t.playbackRate!==1&&t.playbackRate!==0)this.changeMediaPlaybackRate(t,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;let t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;let i=this.levelDetails;return i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:i,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:l}=t,o=this.hls.userConfig,u=l?s||i:i;if(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||u===0)u=n!==void 0?n:a*r;let d=r;return u+Math.min(this.stallCount*t.liveSyncOnStallIncrease,d)}set targetLatency(e){if(!this.hls)return;this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;let i=this.levelDetails;if(i===null)return null;let s=i.edge,r=e-t-this.edgeStalled,n=s-i.totalduration,a=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){let e=this.levelDetails;if(e===null)return 1;return e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null||!this.hls)return 0;let t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;if(!e)return;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.ERROR,this.onError,this),e.on(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this)}unregisterListeners(){let{hls:e}=this;if(!e)return;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.ERROR,this.onError,this),e.off(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){if(this.media)this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){if(t.advanced)this.onTimeupdate();if(!t.live&&this.media)this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var i;let s=this.hls,r=this.media||t.event.appendInPlace&&(s==null||(i=s.interstitialsManager)==null?void 0:i.playerQueue.reduce((n,a)=>n||a.media,null));if(s&&r&&r.playbackRate>1&&r.playbackRate<=s.config.maxLiveSyncPlaybackRate)this.changeMediaPlaybackRate(r,1)}onError(e,t){var i;if(t.details!==R.BUFFER_STALLED_ERROR)return;if(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live)this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency")}changeMediaPlaybackRate(e,t){var i,s;if(e.playbackRate===t)return;(i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t}estimateLiveEdge(){let e=this.levelDetails;if(e===null)return null;return e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();if(e===null)return null;return e-this.currentTime}}function nu(){return typeof __HLS_WORKER_BUNDLE__==="function"}function au(){let e=Lt[Bt];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return Lt[Bt]=r,r}function ou(e){let t=Lt[e];if(t)return t.clientCount++,t;let i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Lt[e]=r,r}function lu(e){let t=Lt[e||Bt];if(t){if(t.clientCount--===1){let{worker:s,objectURL:r}=t;if(delete Lt[e||Bt],r)self.URL.revokeObjectURL(r);s.terminate()}}}function uu(e,t,i,s){let r=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],n=t[i+2],a=n>>2&15;if(a>12){let v=Error(`invalid ADTS sampling index:${a}`);e.emit(y.ERROR,y.ERROR,{type:Q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:v,reason:v.message});return}let l=(n>>6&3)+1,o=t[i+3]>>6&3|(n&1)<<2,u=r[a],d=a;if(l===5||l===29)d-=3;let c,h=(d&14)>>1,g=(d&1)<<7|o<<3,m=0;if(l===1&&a>=6){m=5;let v=a-3;c=[m<<3|h,g|(v&14)>>1,(v&1)<<7|8,0]}else c=[l<<3|h,g];let f="mp4a.40."+(m||l);return ae.log(`manifest codec:${s}, parsed codec:${f}, channels:${o}, rate:${u} (ADTS object type:${l} sampling index:${a} esds config:[${c.join(",")}])`),{config:c,samplerate:u,channelCount:o,codec:f,parsedCodec:f,manifestCodec:s}}function Zn(e,t){return e[t]===255&&(e[t+1]&246)===240}function Jn(e,t){return e[t+1]&1?7:9}function Fs(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function du(e,t){return t+5=e.length)return!1;let s=Fs(e,t);if(s<=i)return!1;let r=t+s;return r===e.length||Ei(e,r)}return!1}function ea(e,t,i,s,r){if(!e.samplerate){let n=uu(t,i,s,r);if(!n)return;Te(e,n)}}function ta(e){return 92160000/e}function fu(e,t){let i=Jn(e,t);if(t+i<=e.length){let s=Fs(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}function ia(e,t,i,s,r){let n=ta(e.samplerate),a=s+r*n,l=fu(t,i),o;if(l){let{frameLength:c,headerLength:h}=l,g=h+c,m=Math.max(0,i+g-t.length);if(m)o=new Uint8Array(g-h),o.set(t.subarray(i+h,t.length),0);else o=t.subarray(i+h,i+g);let f={unit:o,pts:a};if(!m)e.samples.push(f);return{sample:f,length:g,missing:m}}let u=t.length-i;return o=new Uint8Array(u),o.set(t.subarray(i,t.length),0),{sample:{unit:o,pts:a},length:u,missing:-1}}function Xe(e="",t=90000){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Ms{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:90000,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){if(this.cachedData)e=He(this.cachedData,e),this.cachedData=null;let i=hi(e,0),s=i?i.length:0,r,n=this._audioTrack,a=this._id3Track,l=i?mn(i):void 0,o=e.length;if(this.basePTS===null||this.frameIndex===0&&H(l))this.basePTS=gu(l,t,this.initPTS),this.lastPTS=this.basePTS;if(this.lastPTS===null)this.lastPTS=this.basePTS;if(i&&i.length>0)a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Re.audioId3,duration:Number.POSITIVE_INFINITY});while(st.length)return;let n=ra(t,i);if(n&&i+n.frameLength<=t.length){let a=n.samplesPerFrame*90000/n.sampleRate,l=s+r*a,o={unit:t.subarray(i,i+n.frameLength),pts:l,dts:l};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function ra(e,t){let i=e[t+1]>>3&3,s=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(i!==1&&r!==0&&r!==15&&n!==3){let a=e[t+2]>>1&1,l=e[t+3]>>6,o=i===3?3-s:s===3?3:4,u=mu[o*14+r-1]*1000,c=pu[(i===3?0:i===2?1:2)*3+n],h=l===3?1:2,g=vu[i][s],m=yu[s],f=g*8*m,v=Math.floor(g*u/c+a)*m,E=Pt();if(!!E&&E<=87&&s===2&&u>=224000&&l===0)e[t+3]=e[t+3]|128;return{sampleRate:c,channelCount:h,frameLength:v,samplesPerFrame:f}}}function Ns(e,t){return e[t]===255&&(e[t+1]&224)===224&&(e[t+1]&6)!==0}function na(e,t){return t+1{let l=new Uint8Array(a);if(s.set(l,16),!this.decrypter.isSync())this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(e[t].unit.length<32)continue;if(this.decryptAacSample(e,t,i),!this.decrypter.isSync())return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),s=0;for(let r=32;r{if(r.data=this.getAvcDecryptedUnit(n,l),!this.decrypter.isSync())this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}let r=e[t].units;for(;;i++){if(i>=r.length)break;let n=r[i];if(n.data.length<=48||n.type!==1&&n.type!==5)continue;if(this.decryptAvcSample(e,t,i,s,n),!this.decrypter.isSync())return}}}}class ua{constructor(e,t,i,s=ae){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.initData=void 0,this.logger=void 0,this.config=t,this.logger=s}resetTimeStamp(){}resetInitSegment(e,t,i,s){let r=this.videoTrack=Xe("video",1),n=this.audioTrack=Xe("audio",1),a=this.txtTrack=Xe("text",1);if(this.id3Track=Xe("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=this.initData=Sn(e);if(l.video){let{id:o,timescale:u,codec:d,supplemental:c}=l.video;r.id=o,r.timescale=a.timescale=u,r.codec=d,r.supplemental=c}if(l.audio){let{id:o,timescale:u,codec:d}=l.audio;n.id=o,n.timescale=u,n.codec=d}a.id=vn.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return Vo(e,"moof")}demux(e,t,i){this.timeOffset=t;let s=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){if(this.remainderData)s=He(this.remainderData,e);let o=Jo(s);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=s;let a=this.extractID3Track(r,t),l=this.parseFragment(r,n,t,i);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let i=this.timeOffset,s=this.videoTrack,r=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;let n=this.extractID3Track(s,this.timeOffset),a=this.parseFragment(s,r,i,t);return{videoTrack:s,audioTrack:Xe(),id3Track:n,textTrack:Xe(),initData:this.initData,sampleData:a}}parseFragment(e,t,i,s){let r=this.initData;if(r&&s){let{samples:n,sampleData:a}=Zo(i,e,r,this.logger,!1);return t.samples=n,a}t.samples=el(i,e)}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let s=ne(e.samples,["emsg"]);if(s)s.forEach((r)=>{let n=tl(r);if(Tu.test(n.schemeIdUri)){let a=qr(n,t),l=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;if(l<=0.001)l=Number.POSITIVE_INFINITY;let o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:Re.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let a=this.config.emsgKLVSchemaUri||Re.misbklv;if(n.schemeIdUri.startsWith(a)){let l=qr(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:Re.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(e,t,i){return Promise.reject(Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}function qr(e,t){return H(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class da{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if(!i||i.units.length===0)i=e[e.length-1];if((t=i)!=null&&t.units){let r=i.units;s=r[r.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,s=i.length;if(s){let r=i[s-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){let s=t.byteLength;if(s===0)return[];let r=e.naluState||0,n=r===_t?0:r,a=[],l=0,o=0,u=-1,d=0;if(r===_t)u=0,d=this.getNALuType(t,0),o=1;while(o0&&t[h-1]===0)h--;if(c-h+(h===0?n:0)=0)a.push({data:t.subarray(u,h),type:d});else{let m=this.getLastNalUnit(e.samples);if(m){if(h>0)m.data=He(m.data,t.subarray(0,h));else if(n>0)m.data=m.data.subarray(0,m.data.byteLength-n);m.state=0}}if(o0&&t[c-1]===0)c--;l=s-c+(c===0?n:0)}if(u>=0)a.push({data:t.subarray(u),type:d,state:l});else if(a.length===0&&l!==_t){let c=this.getLastNalUnit(e.samples);if(c)c.data=He(c.data,t),c.state=l}return e.naluState=l,a}}class gs{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;if(e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e)this.word<<=e,this.bitsAvailable-=e;else e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32)ae.error("Cannot read more than 32 bits at a time");if(this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error("no bits available");if(t=e-t,t>0&&this.bitsAvailable)return i<>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();if(1&e)return 1+e>>>1;else return-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class et{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){let i=et.syncOffset(e);if(i>0)t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`);return i!==-1}static syncOffset(e){let t=e.length,i=Math.min(pe*5,t-pe)+1,s=0;while(s1&&(n===0&&a>2||l+pe>i))return n}else if(a)return-1;else break;s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:vn[e],pid:-1,inputTimeScale:90000,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s,r,n){if(this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=et.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new ha(this.logger):null,this._audioTrack=et.createTrack("audio",s),this._id3Track=et.createTrack("id3"),this._txtTrack=et.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,e)this.demux(e,0,n,(r==null?void 0:r.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;if(e)e.pesData=null;if(t)t.pesData=null;if(i)i.pesData=null;this.aacOverFlow=null,this.remainderData=null}demux(e,t,i,s=!1,r=!1){if(!s)this.sampleAes=null;let n,a=this._videoTrack,l=this.videoIntegrityChecker,o=this._audioTrack,u=this._id3Track,d=this._txtTrack,c=i.iframe,h=a.pid,g=a.pesData,m=o.pid,f=u.pid,v=this._klvPid,E=o.pesData,p=u.pesData,S=null,T=null,L=this.pmtParsed,x=this._pmtId,b=e.length;if(this.remainderData)e=He(this.remainderData,e),b=e.length,this.remainderData=null;if(b>4,C;if(O>1){if(C=P+5+e[P+4],C===P+pe)continue}else C=P+4;switch(Y){case h:if(w){if(g&&!(l!=null&&l.isCorrupted)&&(n=ft(g,this.logger))){if(this.readyVideoParser(a.segmentCodec),this.videoParser!==null)this.videoParser.parsePES(a,d,n,!1,i)}g={data:[],size:0},l==null||l.reset(h)}if(l==null||l.handlePacket(e.subarray(P)),g)g.data.push(e.subarray(C,P+pe)),g.size+=P+pe-C;break;case m:if(c)break;if(w){if(E&&(n=ft(E,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n,i);break;case"mp3":this.parseMPEGPES(o,n);break}E={data:[],size:0}}if(E)E.data.push(e.subarray(C,P+pe)),E.size+=P+pe-C;break;case f:if(c)break;if(w){if(p&&(n=ft(p,this.logger)))this.parseID3PES(u,n);p={data:[],size:0}}if(p)p.data.push(e.subarray(C,P+pe)),p.size+=P+pe-C;break;case v:if(c)break;if(w){if(S&&(n=ft(S,this.logger)))this.parseKlvPES(u,n);S={data:[],size:0}}if(S)S.data.push(e.subarray(C,P+pe)),S.size+=P+pe-C;break;case 0:if(w)C+=e[C]+1;x=this._pmtId=Au(e,C);break;case x:{if(w)C+=e[C]+1;let k=bu(e,C,this.typeSupported,s,this.observer,this.logger,this.config,i);if(h=k.videoPid,h>0)a.pid=h,a.segmentCodec=k.segmentVideoCodec;if(m=k.audioPid,m>0)o.pid=m,o.segmentCodec=k.segmentAudioCodec;if(f=k.id3Pid,f>0)u.pid=f;if(v=k.klvPid,v>0)this._klvPid=v;if(T!==null&&!L)this.logger.warn(`MPEG-TS PMT found at ${P} after unknown PID '${T}'. Backtracking to sync byte @${I} to parse all TS packets.`),T=null,P=I-188;L=this.pmtParsed=!0;break}case 17:case 8191:break;default:T=Y;break}}else A++;if(A>0)Ti(this.observer,Error(`Found ${A} TS packet/s that do not start with 0x47`),i,void 0,this.logger);a.pesData=g,o.pesData=E,u.pesData=p;let _={audioTrack:o,videoTrack:a,id3Track:u,textTrack:d};if(r)this.extractRemainingSamples(_,i);return _}flush(e,t){let{remainderData:i}=this;this.remainderData=null;let s;if(i)s=this.demux(i,0,t,!1,!0);else s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack};if(this.extractRemainingSamples(s,t),this.sampleAes)return this.decrypt(s,this.sampleAes);return s}extractRemainingSamples(e,t){let{audioTrack:i,videoTrack:s,id3Track:r,textTrack:n}=e,a=s.pesData,l=i.pesData,o=r.pesData,u=this.videoIntegrityChecker,d;if(a&&!(u!=null&&u.isCorrupted)&&(d=ft(a,this.logger))){if(this.readyVideoParser(s.segmentCodec),this.videoParser!==null)this.videoParser.parsePES(s,n,d,!0,t),s.pesData=null}else s.pesData=a;if(l&&(d=ft(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,d,t);break;case"mp3":this.parseMPEGPES(i,d);break}i.pesData=null}else{if(l!=null&&l.size)this.logger.log("last AAC PES packet truncated,might overlap between fragments");i.pesData=l}if(o&&(d=ft(o,this.logger)))this.parseID3PES(r,d),r.pesData=null;else r.pesData=o}demuxSampleAes(e,t,i,s){let r=this.demux(e,i,s,!0,!this.config.progressive),n=this.sampleAes=new $s(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){if(this.videoParser===null){if(e==="avc")this.videoParser=new ca}}decrypt(e,t){return new Promise((i)=>{let{audioTrack:s,videoTrack:r}=e;if(s.samples&&s.segmentCodec==="aac")t.decryptAacSamples(s.samples,0,()=>{if(r.samples)t.decryptAvcSamples(r.samples,0,0,()=>{i(e)});else i(e)});else if(r.samples)t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){if(this.observer)this.observer.removeAllListeners();this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,i){let s=0,r=this.aacOverFlow,n=t.data;if(r){this.aacOverFlow=null;let c=r.missing,h=r.sample.unit.byteLength;if(c===-1)n=He(r.sample.unit,n);else{let g=h-c;r.sample.unit.set(n.subarray(0,c),g),e.samples.push(r.sample),s=r.missing}}let a,l;for(a=s,l=n.length;ar.length)break;let l=n;if(n+=16,n>=r.length)break;let o=r[n];n+=1;let u=0;if(o&128){let g=o&127;if(g===0||g>4||n+g>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let m=0;mr.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let d=n+u,c=r.subarray(l,d),h={data:c,len:c.byteLength,pts:s,dts:(a=t.dts)!=null?a:s,type:Re.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(h),n=d}}}function Si(e,t){return((e[t+1]&31)<<8)+e[t+2]}function Au(e,t){return(e[t+10]&31)<<8|e[t+11]}function bu(e,t,i,s,r,n,a,l){let o={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=(e[t+1]&15)<<8|e[t+2],d=t+3+u-4,c=(e[t+10]&15)<<8|e[t+11];t+=12+c;while(t0){let m=t+5,f=g;while(f>2){switch(e[m]){case 106:if(o.audioPid===-1)n.warn("AC-3 in M2TS support not included in build");break;case 5:if(o.klvPid===-1&&a.enableEmsgKLVMetadata)o.klvPid=h,n.log(`KLV metadata PID found: ${h}`);break}let E=e[m+1]+2;m+=E,f-=E}}break;case 194:case 135:return Ti(r,Error("Unsupported EC-3 in M2TS found"),l,void 0,n),o;case 36:return Ti(r,Error("Unsupported HEVC in M2TS found"),l,void 0,n),o}t+=g+5}return o}function Ti(e,t,i,s,r){r.warn(`parsing error: ${t.message}`),e.emit(y.ERROR,y.ERROR,{type:Q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:i,error:t,reason:t.message})}function Zi(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function ft(e,t){let i=0,s,r,n,a,l,o=e.data;if(!e||e.size===0)return null;while(o[0].length<19&&o.length>1)o[0]=He(o[0],o[1]),o.splice(1,1);if(s=o[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>e.size-6)return null;let d=s[7];if(d&192)if(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,d&64){if(l=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-l>5400000)t.warn(`${Math.round((a-l)/90000)}s delta between PTS and DTS, align them`),a=l}else l=a;n=s[8];let c=n+9;if(e.size<=c)return null;e.size-=c;let h=new Uint8Array(e.size);for(let g=0,m=o.length;gf){c-=f;continue}else s=s.subarray(c),f-=c,c=0;h.set(s,i),i+=f}if(r)r-=n+3;return{data:h,pts:a,dts:l,len:r}}return null}class ha{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;let t=Si(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let i=(e[3]&48)>>4;if(i===0)return;let s=e[3]&15,r=this.lastContinuityCounter;this.lastContinuityCounter=s;let n=(i&1)!=0;if((i&2)!=0&&e[4]!=0&&(e[5]&128)!=0)return;if(r<0)return;let o=n?r+1&15:r;if(s!==o){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${s}, Expected-CC=${o} Last-CC=${r}`),this.integrityState="cc-failed";return}if((e[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}}class fa{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);else if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);else if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);else if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);else if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);else if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);else if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}return}}class V{static box(e,...t){let i=8,s=t.length,r=s;while(s--)i+=t[s].byteLength;let n=new Uint8Array(i);mt(n,0,i),mt(n,4,e);for(s=0,i=8;s>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return V.box(ee.mdia,V.mdhd(e.timescale||0,e.duration||0),V.hdlr(e.type),V.minf(e))}static mfhd(e){return V.box(ee.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){if(e.type==="audio")return V.box(ee.minf,V.box(ee.smhd,Du),V.DINF,V.stbl(e));else return V.box(ee.minf,V.box(ee.vmhd,_u),V.DINF,V.stbl(e))}static moof(e,t,i){return V.box(ee.moof,V.mfhd(e),V.traf(i,t))}static moov(e){let t=e.length,i=[];while(t--)i[t]=V.trak(e[t]);return V.box.apply(null,[ee.moov,V.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(V.mvex(e)))}static mvex(e){let t=e.length,i=[];while(t--)i[t]=V.trex(e[t]);return V.box.apply(null,[ee.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(qe+1)),s=Math.floor(t%(qe+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&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 V.box(ee.mvhd,r)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),s,r;for(s=0;s>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(s=0;s>>8&255),i.push(n&255),i=i.concat(Array.prototype.slice.call(r));let a=V.box(ee.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,o=e.height,u=e.pixelRatio[0],d=e.pixelRatio[1];return V.box(ee.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,o>>8&255,o&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,V.box(ee.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),V.box(ee.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config,i=t.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return V.box(ee.mp4a,V.audioStsd(e),V.box(ee.esds,V.esds(e)))}static mp3(e){return V.box(ee[".mp3"],V.audioStsd(e))}static ac3(e){return V.box(ee["ac-3"],V.audioStsd(e),V.box(ee.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return V.box(ee.stsd,es,V.mp4a(e));if(t==="mp3"&&e.codec==="mp3")return V.box(ee.stsd,es,V.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return V.box(ee.stsd,es,V.avc1(e))}else throw Error("video track missing pps or sps");throw Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,r=e.height||0,n=Math.floor(i/(qe+1)),a=Math.floor(i%(qe+1));return V.box(ee.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,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,s>>8&255,s&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){let i=V.sdtp(e),s=e.id,r=Math.floor(t/(qe+1)),n=Math.floor(t%(qe+1));return V.box(ee.traf,V.box(ee.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),V.box(ee.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),V.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,V.box(ee.trak,V.tkhd(e),V.mdia(e))}static trex(e){let t=e.id;return V.box(ee.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i=e.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r),a,l,o,u,d,c;t+=8+r,n.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0);for(a=0;a>>24&255,o>>>16&255,o>>>8&255,o&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,c>>>24&255,c>>>16&255,c>>>8&255,c&255],12+16*a);return V.box(ee.trun,n)}static initSegment(e){let t=V.moov(e);return He(V.FTYP,t)}static hvc1(e){return new Uint8Array}}function wu(e,t,i=1,s=!1){let r=e*t*i;return s?Math.round(r):r}function Dt(e,t=!1){return wu(e,1000,1/Pu,t)}function Xr(e){let{baseTime:t,timescale:i,trackId:s}=e;return`${t/i} (${t}/${i}) trackId: ${s}`}function Qr(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}function $e(e,t){let i;if(t===null)return e;if(t4294967296)e+=i;return e}function $u(e){for(let t=0;ta.pts-l.pts);let n=e.samples;return e.samples=[],{samples:n}}function ri(e,t,i=!1){return(e==null?void 0:e.start)!==void 0?(e.start+(i?e.duration:0))/e.timescale:t}function Bu(e,t,i,s){if(e===null)return!0;let r=Math.max(s,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>=r}function Zr(e,t,i){let s=e.codec;if(s&&s.length>4)return s;if(t===he.AUDIO){if(s==="ec-3"||s==="ac-3"||s==="alac")return s;if(s==="fLaC"||s==="Opus")return mi(s,!1);return i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}else if(s==="mjpg")return s;return i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}class ps{constructor(e,t,i,s,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=n}configure(e){if(this.transmuxConfig=e,this.decrypter)this.decrypter.reset()}push(e,t,i,s){if(!this.observer)return ni(i);let r=i.transmuxing;r.executeStart=at();let n=new Uint8Array(e),{currentTransmuxState:a,transmuxConfig:l}=this;if(s)this.currentTransmuxState=s;let{contiguous:o,discontinuity:u,trackSwitch:d,accurateTimeOffset:c,timeOffset:h,initSegmentChange:g}=s||a,{audioCodec:m,videoCodec:f,defaultInitPts:v,duration:E,initSegmentData:p}=l,S=Uu(n,t);if(S&&Ot(S.method)){let b=this.getDecrypter(),I=kn(S.method);return this.asyncResult=!0,this.decryptionPromise=b.decrypt(n,S.key.buffer,S.iv.buffer,I,i.decryptRange).then((A)=>{let _=this.push(A,null,i);return this.decryptionPromise=null,_}),this.decryptionPromise}let T=this.needsProbing(u,d);if(T){let b=i.iframe&&p&&et.probe(p,this.logger)?p:n,I=this.configureTransmuxer(b);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:Q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),r.executeEnd=at(),ni(i)}if(u||d||g||T)this.resetInitSegment(p,m,f,E,t,i);if(u||g||T)this.resetInitialTimestamp(v);if(!o)this.resetContiguity();let L=this.transmux(n,S,h,c,i);this.asyncResult=Ut(L);let x=this.currentTransmuxState;return x.contiguous=!0,x.discontinuity=!1,x.trackSwitch=!1,r.executeEnd=at(),L}flush(e){let t=e.transmuxing;t.executeStart=at();let{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));let n=[],{timeOffset:a}=s;if(i){let d=i.flush();if(d)n.push(this.push(d.buffer,null,e))}let{demuxer:l,remuxer:o}=this;if(!l||!o){t.executeEnd=at();let d=[ni(e)];if(this.asyncResult)return Promise.resolve(d);return d}let u=l.flush(a,e);if(Ut(u))return this.asyncResult=!0,u.then((d)=>(this.flushRemux(n,d,e),n));if(this.flushRemux(n,u,e),this.asyncResult)return Promise.resolve(n);return n}flushRemux(e,t,i){if(!this.remuxer)return;let{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:o}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);let u=this.remuxer.remux(s,r,n,a,o,l,!0,this.id,i,t.initData,t.sampleData);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=at()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;if(!t||!i)return;t.resetTimeStamp(e),i.resetTimeStamp(e)}resetContiguity(){let{demuxer:e,remuxer:t}=this;if(!e||!t)return;e.resetContiguity(),t.resetNextTimestamp()}resetInitSegment(e,t,i,s,r,n){let{demuxer:a,remuxer:l}=this;if(!a||!l)return;a.resetInitSegment(e,t,i,s,r,n),l.resetInitSegment(e,t,i,r)}destroy(){if(this.demuxer)this.demuxer.destroy(),this.demuxer=void 0;if(this.remuxer)this.remuxer.destroy(),this.remuxer=void 0;if(this.observer)this.observer.removeAllListeners();this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,i,s,r){let n;if((t==null?void 0:t.method)==="SAMPLE-AES")n=this.transmuxSampleAes(e,t,i,s,r);else n=this.transmuxUnencrypted(e,i,s,r);return n}transmuxUnencrypted(e,t,i,s){let{demuxer:r,remuxer:n}=this;if(!r||!n)return ni(s);let a=r.demux(e,t,s,!1,!this.config.progressive),{audioTrack:l,videoTrack:o,id3Track:u,textTrack:d}=a;return{remuxResult:n.remux(l,o,u,d,t,i,!1,this.id,s,a.initData,a.sampleData),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){if(!this.demuxer)return Promise.reject(Error("no demuxer"));return this.demuxer.demuxSampleAes(e,t,i,r).then((n)=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,i,s,!1,this.id,r,n.initData,n.sampleData),chunkMeta:r}))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:s}=this;if(!i)return;let r;try{for(let d=0,c=ts.length;d0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null)i=t;return i}function Ut(e){return"then"in e&&e.then instanceof Function}class va{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class ya{constructor(e,t,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}class Ea{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Jr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=(l)=>{let o=l.data,u=this.hls;if(!u||!(o!=null&&o.event)||o.instanceNo!==this.instanceNo)return;switch(o.event){case"init":{var d;let c=(d=this.workerContext)==null?void 0:d.objectURL;if(c)self.URL.revokeObjectURL(c);break}case"transmuxComplete":{this.handleTransmuxComplete(o.data);break}case"flush":{this.onFlush(o.data);break}case"workerLog":{if(u.logger[o.data.logType])u.logger[o.data.logType](o.data.message);break}default:{o.data=o.data||{},o.data.frag=this.frag,o.data.part=this.part,o.data.id=this.id,u.trigger(o.event,o.data);break}}},this.onWorkerError=(l)=>{if(!this.hls)return;let o=Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:Q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:o})};let r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;let n=(l,o)=>{if(o=o||{},o.frag=this.frag||void 0,l===y.ERROR)o=o,o.parent=this.id,o.part=this.part,this.error=o.error;this.hls.trigger(l,o)};this.observer=new qn,this.observer.on(y.FRAG_DECRYPTED,n),this.observer.on(y.ERROR,n);let a=cr(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(r.workerPath||nu()){try{if(r.workerPath)l.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=ou(r.workerPath);else l.log(`injecting Web Worker for "${t}"`),this.workerContext=au();let{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:De(r)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new ps(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new ps(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Jr++;let t=this.hls.config,i=cr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:De(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),lu(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;if(t)t.destroy(),this.transmuxer=null}let e=this.observer;if(e)e.removeAllListeners();this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,r,n,a,l,o,u){var d,c;o.transmuxing.start=self.performance.now();let{instanceNo:h,transmuxer:g}=this,m=n?n.start:r.start,f=r.decryptdata,v=this.frag,E=v?r.cc!==v.cc:!0,p=v?o.level!==v.level:!0,S=v?o.sn-v.sn:-1,T=this.part?o.part-this.part.index:-1,L=S===0&&o.id>1&&o.id===(v==null?void 0:v.stats.chunkCount),x=!p&&(S===1||S===0&&(T===1||L&&T<=0)),b=self.performance.now();if(p||S||r.stats.parsing.start===0)r.stats.parsing.start=b;if(n&&(T||!x))n.stats.parsing.start=b;let I=!(v&&((d=r.initSegment)==null?void 0:d.url)===((c=v.initSegment)==null?void 0:c.url)),A=new ya(E,x,l,p,m,I);if(!x||E||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${o.sn}${o.part>-1?" part: "+o.part:""} ${this.id} playlist: ${o.level} id: ${o.id} + discontinuity: ${E} + trackSwitch: ${p} + contiguous: ${x} + accurateTimeOffset: ${l} + timeOffset: ${m} + initSegmentChange: ${I}`);let _=new va(i,s,t,a,u);this.configureTransmuxer(_)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:h,cmd:"demux",data:e,decryptdata:f,chunkMeta:o,state:A},e instanceof ArrayBuffer?[e]:[]);else if(g){let _=g.push(e,f,o,A);if(Ut(_))_.then((P)=>{this.handleTransmuxComplete(P)}).catch((P)=>{this.transmuxerError(P,o,"transmuxer-interface push error")});else this.handleTransmuxComplete(_)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let s=i.flush(e);if(Ut(s))s.then((r)=>{this.handleFlushResult(r,e)}).catch((r)=>{this.transmuxerError(r,e,"transmuxer-interface flush error")});else this.handleFlushResult(s,e)}}transmuxerError(e,t,i){if(!this.hls)return;this.error=e,this.hls.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i})}handleFlushResult(e,t){e.forEach((i)=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e});else if(i)i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function Sa(){return self.SourceBuffer||self.WebKitSourceBuffer}function Bs(){if(!it())return!1;let t=Sa();return!t||t.prototype&&typeof t.prototype.appendBuffer==="function"&&typeof t.prototype.remove==="function"}function Ta(){if(!Bs())return!1;let e=it();return typeof(e==null?void 0:e.isTypeSupported)==="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t)=>e.isTypeSupported(os(t,"video")))||["mp4a.40.2","fLaC"].some((t)=>e.isTypeSupported(os(t,"audio"))))}function Gu(){var e;let t=Sa();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==="function"}class wi{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new Ai}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,i){let s=this.stats;if(s.loading.start)throw Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}abort(){var e;if(this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort)this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Mt(e,t,!0))this.retry(e);else{var i;ae.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let s=this.callbacks;if(s)this.abortInternal(),s.onTimeout(this.stats,this.context,this.getNetworkDetails())}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Ss(e,i.retry),i.retry++,ae.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}class La{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,i;if(!e.length)return new Uint8Array(0);else if(e.length===1)i=e[0];else i=Hu(e,t);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Hu(e,t){let i=new Uint8Array(t),s=0;for(let r=0;r{let l=`${a==="level"?"playlist":a}LoadPolicy`,o=t[l]===void 0,u=[];if(n.forEach((d)=>{let c=`${a}Loading${d}`,h=t[c];if(h!==void 0&&o){u.push(c);let g=s[l].default;switch(t[l]={default:g},d){case"TimeOut":g.maxLoadTimeMs=h,g.maxTimeToFirstByteMs=h;break;case"MaxRetry":g.errorRetry.maxNumRetry=h,g.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":g.errorRetry.retryDelayMs=h,g.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=h,g.timeoutRetry.maxRetryDelayMs=h;break}}}),u.length)i.warn(`hls.js config: "${u.join('", "')}" setting(s) are deprecated, use "${l}": ${De(t[l])}`)}),Me(Me({},s),t)}function vs(e){if(e&&typeof e==="object"){if(Array.isArray(e))return e.map(vs);return Object.keys(e).reduce((t,i)=>(t[i]=vs(e[i]),t),{})}return e}function ed(e,t){let i=e.loader;if(i!==Li&&i!==Oi)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else if(Aa())e.loader=Li,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader")}function Ia(e,t){return $t(e,"audio",t)}function _a(e,t){return $t(e,"video",t)}function tn(e,t){let{audioCodec:i,videoCodec:s}=e;if(i)e.audioCodec=i=mi(i,t)||void 0;if(s)s=e.videoCodec=ul(s);let{unknownCodecs:r}=e;if((r==null?void 0:r.length)||0||i&&!Ia(i,t)||s&&!_a(s,t))return!1;return!0}function sn(e){let t={};e.forEach((i)=>{let s=i.groupId||"";i.id=t[s]=t[s]||0,t[s]++})}function rt(e,t=R.KEY_LOAD_ERROR,i,s,r){return new Ue({type:Q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s||null})}function rn(e){let{type:t}=e;switch(t){case se.AUDIO_TRACK:return J.AUDIO;case se.SUBTITLE_TRACK:return J.SUBTITLE;default:return J.MAIN}}function is(e,t){let i=e.url;if(i===void 0||i.indexOf("data:")===0)i=t.url;return i}class Ca{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,s=t.loader,n=new(i||s)(t);return this.loaders[e.type]=n,n}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){if(this.loaders[e])delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];if(t)t.destroy();this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:se.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:l}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:se.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:se.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){let{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:se.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){let i=this.loaders[se.LEVEL];if(i){let s=i.context;if(s&&!t.levels.some((r)=>r===s.levelOrTrack))i.abort(),delete this.loaders[se.LEVEL]}}load(e){var t;let i=this.hls.config,s=this.getInternalLoader(e);if(s){let o=this.hls.logger,u=s.context;if((u==null?void 0:u.levelOrTrack)===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){if(u.url===e.url)o.log(`[playlist-loader]: ignore ${e.url} ongoing request`);else o.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}o.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let r;if(e.type===se.MANIFEST)r=i.manifestLoadPolicy.default;else r=Te({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null});if(s=this.createInternalLoader(e),H((t=e.deliveryDirectives)==null?void 0:t.part)){let o;if(e.type===se.LEVEL&&e.level!==null)o=this.hls.levels[e.level].details;else if(e.type===se.AUDIO_TRACK&&e.id!==null)o=this.hls.audioTracks[e.id].details;else if(e.type===se.SUBTITLE_TRACK&&e.id!==null)o=this.hls.subtitleTracks[e.id].details;if(o){let{partTarget:u,targetduration:d}=o;if(u&&d){let c=Math.max(u*3,d*0.8)*1000;r=Te({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}}let n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},l={onSuccess:(o,u,d,c)=>{let h=this.getInternalLoader(d);this.resetInternalLoader(d.type);let g=o.data;if(u.parsing.start=performance.now(),Ge.isMediaPlaylist(g)||d.type!==se.MANIFEST)this.handleTrackOrLevelPlaylist(o,u,d,c||null,h);else this.handleMasterPlaylist(o,u,d,c)},onError:(o,u,d,c)=>{this.handleNetworkError(u,d,!1,o,c)},onTimeout:(o,u,d)=>{this.handleNetworkError(u,d,!0,void 0,o)}};s.load(e,a,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;if(e||i)this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t)}handleMasterPlaylist(e,t,i,s){let r=this.hls,n=e.data,a=is(e,i),l=Ge.parseMasterPlaylist(n,a);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}let{contentSteering:o,levels:u,iframeVariants:d,sessionData:c,sessionKeys:h,startTimeOffset:g,variableList:m}=l;this.variableList=m,u.forEach((p)=>{let{unknownCodecs:S}=p;if(S){let{preferManagedMediaSource:T}=this.hls.config,{audioCodec:L,videoCodec:x}=p;for(let b=S.length;b--;){let I=S[b];if($t(I,"audio",T))p.audioCodec=L=L?`${L},${I}`:I,Tt.audio[L.substring(0,4)]=2,S.splice(b,1);else if($t(I,"video",T))p.videoCodec=x=x?`${x},${I}`:I,Tt.video[x.substring(0,4)]=2,S.splice(b,1)}}});let{AUDIO:f=[],SUBTITLES:v,"CLOSED-CAPTIONS":E}=Ge.parseMasterPlaylistMedia(n,a,l);if(f.length){if(!f.some((S)=>!S.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO)this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),f.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ce({}),bitrate:0,url:""})}r.trigger(y.MANIFEST_LOADED,{levels:u,audioTracks:f,subtitles:v,iframeVariants:d,captions:E,contentSteering:o,url:a,stats:t,networkDetails:s,sessionData:c,sessionKeys:h,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,s,r){let n=this.hls,{id:a,level:l,type:o}=i,u=is(e,i),d=H(l)?l:H(a)?a:0,c=rn(i),h=Ge.parseLevelPlaylist(e.data,u,d,c,0,this.variableList);if(o===se.MANIFEST){let g={attrs:new ce({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Fn(h,0),n.trigger(y.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=h,this.handlePlaylistLoaded(h,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(y.ERROR,{type:Q.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===se.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;if(e.type===se.LEVEL)n+=`: ${e.level} id: ${e.id}`;else if(e.type===se.AUDIO_TRACK||e.type===se.SUBTITLE_TRACK)n+=` id: ${e.id} group-id: "${e.groupId}"`;let a=Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let l=R.UNKNOWN,o=!1,u=this.getInternalLoader(e);switch(e.type){case se.MANIFEST:l=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,o=!0;break;case se.LEVEL:l=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,o=!1;break;case se.AUDIO_TRACK:l=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,o=!1;break;case se.SUBTITLE_TRACK:l=i?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,o=!1;break}if(u)this.resetInternalLoader(e.type);let d={type:Q.NETWORK_ERROR,details:l,fatal:o,url:e.url,loader:u,context:e,error:a,networkDetails:t,stats:r};if(s){let c=e.url;if(t&&"url"in t)c=t.url;d.response=Me({url:c,data:void 0},s)}this.hls.trigger(y.ERROR,d)}handlePlaylistLoaded(e,t,i,s,r,n){let a=this.hls,{type:l,level:o,levelOrTrack:u,id:d,groupId:c,deliveryDirectives:h}=s,g=is(t,s),m=rn(s),f=typeof s.level==="number"&&m===J.MAIN?o:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(y.ERROR,{type:Q.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:t,context:s,level:f,parent:m,networkDetails:r,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){let E=e.playlistParsingError=Error("No Segments found in Playlist");a.trigger(y.ERROR,{type:Q.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:s,level:f,parent:m,networkDetails:r,stats:i});return}if(e.live&&n){if(n.getCacheAge)e.ageHeader=n.getCacheAge()||0;if(!n.getCacheAge||isNaN(e.ageHeader))e.ageHeader=0}switch(l){case se.MANIFEST:case se.LEVEL:if(f){if(!u)f=0;else if(u!==a.levels[f]){let E=a.levels.indexOf(u);if(E>-1)f=E}}a.trigger(y.LEVEL_LOADED,{details:e,levelInfo:u||a.levels[0],level:f||0,id:d||0,stats:i,networkDetails:r,deliveryDirectives:h,withoutMultiVariant:l===se.MANIFEST,context:s});break;case se.AUDIO_TRACK:a.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:h,context:s});break;case se.SUBTITLE_TRACK:a.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:h,context:s});break}}}class tt{static get version(){return Bt}static isMSESupported(){return Bs()}static isSupported(){return Ta()}static getMediaSource(){return it()}static get Events(){return y}static get MetadataSchema(){return Re}static get ErrorTypes(){return Q}static get ErrorDetails(){return R}static get DefaultConfig(){if(!tt.defaultConfig)return Qu;return tt.defaultConfig}static set DefaultConfig(e){tt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new qn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=xo(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),i=this.config=Ju(tt.DefaultConfig,e,t);if(this.userConfig=e,i.progressive)ed(i,t);let{streamController:s,abrController:r,bufferController:n,capLevelController:a,errorController:l,fpsController:o,id3TrackController:u,iframeController:d,gapController:c}=i,h=new l(this),g=this.abrController=new r(this),m=new Bn(this),f=i.interstitialsController,v=f?this.interstitialsController=new f(this,tt):null,E=n?this.bufferController=new n(this,m):null,p=a?this.capLevelController=new a(this):null,S=o?new o(this):null,T=i.cmcdController,L=T?this.cmcdController=new T(this):null,x=new Ca(this),b=i.contentSteeringController,I=b?new b(this):null,A=this.levelController=new Ra(this,I),_=u?new u(this):void 0,P=new Da(this.config,this.logger),w=this.streamController=new s(this,m,P),Y=this.gapController=c?new c(this,m):void 0;if(p)p.setStreamController(w);let O=[x,A,w];if(v)O.splice(1,0,v);if(I)O.splice(1,0,I);this.networkControllers=O;let C=[g];if(E)C.push(E);if(Y)C.push(Y);if(p)C.push(p);if(S)S.setStreamController(w),C.push(S);if(_)C.push(_);C.push(m),this.audioTrackController=this.createController(i.audioTrackController,O);let k=i.audioStreamController;if(k)O.push(this.audioStreamController=new k(this,m,P));this.subtitleTrackController=this.createController(i.subtitleTrackController,O);let G=i.subtitleStreamController;if(G)O.push(this.subtititleStreamController=new G(this,m,P));if(this.createController(i.timelineController,C),P.emeController=this.emeController=this.createController(i.emeController,C),L)C.push(L);this.latencyController=this.createController(i.latencyController,C),this.coreComponents=C,this.iframeController=d?new d(this,tt):void 0,O.push(h);let D=h.onErrorOut;if(typeof D==="function")this.on(y.ERROR,D,h);this.on(y.MANIFEST_LOADED,x.onManifestLoaded,x)}createController(e,t){if(e){let i=new e(this);if(t)t.push(i);return i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);else try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let s=e===y.ERROR;this.trigger(y.ERROR,{type:Q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(y.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((t)=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach((t)=>t.destroy()),this.coreComponents.length=0,this.iframeController=void 0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let r=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(y.ERROR,{type:Q.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}if(this.logger.log("attachMedia"),this._media)this.logger.warn("media must be detached before attaching"),this.detachMedia();let t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(y.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(y.MEDIA_DETACHING,e),this._media=null,this.trigger(y.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,i={transferMedia:t};return this.trigger(y.MEDIA_DETACHING,i),this.trigger(y.MEDIA_DETACHED,i),t}loadSource(e){var t;this.stopLoad();let i=this.media,s=this._url,r=this._url=ys.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});if(this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),i&&s&&(s!==r||(t=this.bufferController)!=null&&t.hasSourceTypes()))this.detachMedia(),this.attachMedia(i);this.trigger(y.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", ":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i{if(e.resumeBuffering)e.resumeBuffering()})}pauseBuffering(){if(this.bufferingEnabled)this.logger.log("pause buffering"),this.networkControllers.forEach((e)=>{if(e.pauseBuffering)e.pauseBuffering()})}get inFlightFragments(){let e={[J.MAIN]:this.streamController.inFlightFrag};if(this.audioStreamController)e[J.AUDIO]=this.audioStreamController.inFlightFrag;if(this.subtititleStreamController)e[J.SUBTITLE]=this.subtititleStreamController.inFlightFrag;return e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=this.started,i=e==null?void 0:e.currentTime;if(this.detachMedia(),e){if(this.attachMedia(e),t){if(i)this.startLoad(i);else if(!this.config.autoStartLoad)this.startLoad()}}}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;if(!e)e=this._sessionId=_o();return e}get levels(){let e=this.levelController.levels;return e?e:[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;if(e===-1&&this.abrController.forcedAutoLevel>-1)return this.abrController.forcedAutoLevel;return e}set startLevel(e){if(this.logger.log(`set startLevel:${e}`),e!==-1)e=Math.max(e,this.minAutoLevel);this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=this.capLevelController,i=!!e;if(t&&i!==this.config.capLevelToPlayerSize){if(i)t.startCapping();else t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch();this.config.capLevelToPlayerSize=i}}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;if(!e)return NaN;return e.getEstimate()}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;if(!e)return NaN;return e.defaultEstimate}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;if(!e)return NaN;return e.getEstimateTTFB()}set autoLevelCapping(e){if(this._autoLevelCapping!==e)this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated()}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){if(cl(e)&&this._maxHdcpLevel!==e)this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated()}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let s=0;s=t)return s;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,s;if(t===-1&&e!=null&&e.length)s=e.length-1;else s=t;if(i)for(let r=s;r--;){let n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=i)return r}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;if(t)t.audioTrack=e}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){let{audioTrackController:t}=this;if(t)t.nextAudioTrack=e}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;if(t)t.subtitleTrack=e}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;if(t)t.subtitleDisplay=e}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){if(!this.latencyController)return;this.latencyController.targetLatency=e}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return null}get iframeVariants(){let e=this.levelController.iframeVariants;return e?e:[]}createIFramePlayer(e){return null}createImageIFramePlayer(e){return null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=Rn(t);return st.getMediaDecodingInfoPromise(e,i,navigator.mediaCapabilities)}}var H,ho,fo,Q,R,y,$i,er,ys,se,J,he,yt,Es,nt=function(){},So,ns,ae,Bi,nr,st,cn,Ro="utf-16",Ui="utf-16be",ar="utf-16le",ai="utf-8",Xt=10,Uo=10,qe,ee,vn,lr,Gt,Hi,Ki,Wi,Tt,Yi,ol,ls,pi,wt,ml=(e)=>{let t=new WeakSet;return(i,s)=>{if(e)s=e(i,s);if(typeof s==="object"&&s!==null){if(t.has(s))return;t.add(s)}return s}},De=(e,t)=>JSON.stringify(e,ml(t)),bs,In,Ee,ye,Is,Ll,vr,Al="com.apple.hls.interstitial",Dn=10,ot,ei,Er,Sr,_l,ji,Dl,Ds,Ae,Gl=16,Pr,Ue,Cs,Fr,B,ks,Nr,Wn="HlsJsTrackRemovedError",jl=0.25,ql=0.001,Yn,Ps,Xl=300000,ws,Qi,Hr,Zl,qn,ui=2,Jl=100,zn,Re,ru=0.25,si,Bt="1.7.2",Lt,gu=(e,t,i)=>{if(H(e))return e*90;let s=i?i.baseTime*90000/i.timescale:0;return t*90000+s},mu,pu,vu,yu,oa,Su=(e,t)=>{let i=0,s=5;t+=s;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);while(s>0){a[0]=e[t];let l=Math.min(s,8),o=8-l;n[0]=4278190080>>>24+o<>o,i=!i?r[0]:i<({remuxResult:{},chunkMeta:e}),Jr=0,je,Vu=100,xa,Ku,Li,ba,zu=(e,t,i)=>Math.max(t,Math.min(e,i)),Xu,Oi,en,Qu,Ra,Da,td,id,sd,rd,nd;var Pa=It(()=>{H=Number.isFinite||function(e){return typeof e==="number"&&isFinite(e)},ho=Number.isSafeInteger||function(e){return typeof e==="number"&&Math.abs(e)<=fo},fo=Number.MAX_SAFE_INTEGER||9007199254740991,Q=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),R=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),y=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});$i={exports:{}};ys=go();se={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack",MEDIA_FRAGMENT:"media-fragment",KEY:"key",STEERING_MANIFEST:"steering-manifest",SERVER_CERTIFICATE:"server-certificate",INTERSTITIAL_ASSET_LIST:"interstitial-asset-list"},J={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},he={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};yt=class yt extends bi{constructor(e,t){super(t);this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(H(e)&&H(t))return t-e}return null}get bitrate(){if(this.byteLength)return this.byteLength*8/this.duration;if(this._bitrate)return this._bitrate;return null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity){if(!this._decryptdata)this._decryptdata=t.identity.getDecryptData(this.sn)}else if(!((e=this._decryptdata)!=null&&e.keyId)){let i=Object.keys(t);if(i.length===1){let s=this._decryptdata=t[i[0]]||null;if(s)this._decryptdata=s.getDecryptData(this.sn,t)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=!H(this.duration)?0:this.duration;return this.programDateTime+e*1000}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;else if(this.levelkeys){var t;let i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){if(this._programDateTime===null&&this.rawProgramDateTime)this.programDateTime=Date.parse(this.rawProgramDateTime);return this._programDateTime}set programDateTime(e){if(!H(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){if(!Fe(this))return null;if(!this._ref)this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime};return this._ref}addStart(e){this.setStart(this.start+e)}setStart(e){if(this.start=e,this._ref)this._ref.start=e}setDuration(e){if(this.duration=e,this._ref)this._ref.duration=e}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let s=t[e];if(s&&!((i=this._decryptdata)!=null&&i.keyId))this._decryptdata=s.getDecryptData(this.sn,t)}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,r,n=!1){let{elementaryStreams:a}=this,l=a[e];if(!l){a[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:n};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,r)}};Es=class Es extends bi{constructor(e,t,i,s,r){super(i);this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;let n=e.enumeratedString("BYTERANGE");if(n)this.setByteRange(n,r);if(r)this.fragOffset=r.fragOffset+r.duration}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===J.SUBTITLE&&this.stats.loading.end>0)}};So={trace:nt,debug:nt,log:nt,warn:nt,info:nt,error:nt};ns=rs();ae=ns;st=Lo(),cn=nn(st);qe=Math.pow(2,32)-1,ee={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},vn={video:1,audio:2,id3:3,text:4};Gt=bn("userAgent");bn("vendor");Tt={audio:{a3ds:1,"ac-3":0.95,"ac-4":1,alac:0.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":0.9,enca:1,fLaC:0.9,flac:0.9,FLAC:0.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:0.8,dav1:0.8,drac:1,dva1:1,dvav:1,dvh1:0.7,dvhe:0.7,encv:1,hev1:0.75,hvc1:0.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:0.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};Yi={};ol=/flac|opus|mp4a\.40\.34/i;ls=["NONE","TYPE-0","TYPE-1",null];pi=["SDR","PQ","HLG"];wt={No:"",Yes:"YES",v2:"v2"};bs=class bs extends Qe{constructor(e){super("abr",e.logger);this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=(t)=>{var i;let{fragCurrent:s,partCurrent:r,hls:n}=this;if(!n)return;let{autoLevelEnabled:a,media:l}=n;if(!s||!l)return;let o=performance.now(),u=r?r.stats:s.stats,d=r?r.duration:s.duration,c=o-u.loading.start,h=n.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=h){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;let f=m>-1&&m!==g,v=!!t||f;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let E=n.mainForwardBufferInfo;if(!v&&E===null)return;let p=this.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(c<=Math.max(p,1000*(d/(S*2))))return;let T=E?E.len/S:0,L=u.loading.first?u.loading.first-u.loading.start:-1,x=u.loaded&&L>-1,b=this.getBwEstimate(),I=n.levels,A=I[g],_=Math.max(u.loaded,Math.round(d*(s.bitrate||A.averageBitrate)/8)),P=x?c-L:c;if(P<1&&x)P=Math.min(c,u.loaded*8/b);let w=x?u.loaded*1000/P:0,Y=p/1000,O=w?(_-u.loaded)/w:_*8/b+Y;if(O<=T)return;let C=w?w*8:b,k=((i=(t==null?void 0:t.details)||n.latestLevelDetails)==null?void 0:i.live)===!0,G=n.config.abrBandWidthUpFactor,D=Number.POSITIVE_INFINITY,U;for(U=g-1;U>h;U--){let X=I[U].maxBitrate,z=!I[U].details||k;if(D=this.getTimeToLoadFrag(Y,C,d*X,z),D=O)return;if(D>d*10)return;if(x)this.bwEstimator.sample(c-Math.min(p,L),u.loaded);else this.bwEstimator.sampleTTFB(c);let F=I[U].maxBitrate;if(this.getBwEstimate()*G>F)this.firstAutoFloor=Math.min(U,n.firstLevel),this.resetEstimator(F);let M=this.findBestLevel(F,h,U,0,T,1,1);if(M>-1)U=M;this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly; + Fragment duration: ${s.duration.toFixed(3)} + Time to underbuffer: ${T.toFixed(3)} s + Estimated load time for current fragment: ${O.toFixed(3)} s + Estimated load time for down switch fragment: ${D.toFixed(3)} s + TTFB estimate: ${L|0} ms + Current BW estimate: ${H(b)?b|0:"Unknown"} bps + New BW estimate: ${this.getBwEstimate()|0} bps + Switching to level ${U} @ ${F|0} bps`),n.nextLoadLevel=n.nextAutoLevel=U,this.clearTimer();let q=()=>{this.clearTimer();let X=this.hls;if(this.fragCurrent===s&&X.loadLevel===U&&U>0){let z=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${U>0?"and switching down":""} + Fragment duration: ${s.duration.toFixed(3)} s + Time to underbuffer: ${z.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,U>h){let j=this.findBestLevel(X.levels[h].bitrate,h,U,0,z,1,1);if(j===-1)j=h;X.nextLoadLevel=X.nextAutoLevel=j,this.firstAutoFloor=Math.min(j,X.firstLevel),this.resetEstimator(X.levels[j].bitrate)}}};if(f||O>D*2)q();else this.timer=self.setInterval(q,D*1000);n.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){if(!this.hls)return;if(e)this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e;this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new dn(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;if(!e)return;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(y.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){if(this.lastLoadedFragLevel>-1&&this.fragCurrent)this.lastLoadedFragLevel=this.fragCurrent.level;this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;if(this.ignoreFragment(i))return;if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(t.fatal)return;switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&ss(i,s)){let n=performance.now(),a=r?r.stats:i.stats,l=n-a.loading.start,o=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&o>-1){let d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,o),a.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,s){let r=e+i/t,n=s?e+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){let i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;if(H(r))this.lastLevelLoadSec=r/1000;if(t.details.live)this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive);else this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD);if(this.timer>-1)this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var i;let{frag:s,part:r}=t,n=r?r.stats:s.stats;if(s.type===J.MAIN)this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start);if(this.ignoreFragment(s))return;if(this.clearTimer(),s.level===this._nextAutoLevel)this._nextAutoLevel=-1;if(this.firstSelection=-1,(i=this.hls)!=null&&i.config.abrMaxWithRealBitrate){let a=r?r.duration:s.duration,l=this.hls.levels[s.level],o=(l.loaded?l.loaded.bytes:0)+n.loaded,u=(l.loaded?l.loaded.duration:0)+a;l.loaded={bytes:o,duration:u},l.realBitrate=Math.round(8*o/u)}if(s.bitrateTest){let a={stats:n,frag:s,part:r,id:s.type};this.onFragBuffered(y.FRAG_BUFFERED,a),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}onFragBuffered(e,t){let{frag:i,part:s}=t,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;let a=((i.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());if(this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest)this.bitrateTestDelay=a/1000;else if(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate())this.firstAutoFloor=-1}ignoreFragment(e){return e.type!==J.MAIN||e.sn==="initSegment"}clearTimer(){if(this.timer>-1)self.clearInterval(this.timer),this.timer=-1}get firstAutoLevel(){let{hls:e}=this;if(!e)return 0;let{maxAutoLevel:t,minAutoLevel:i}=e,s=this.getBwEstimate(),r=this.getStarvationDelay(),n=e.config.maxStarvationDelay,a=this.findBestLevel(s,i,t,r/2,n,1,1);if(a>-1)return a;let l=e.firstLevel,o=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,u=Math.min(Math.max(l,i),t,o);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${u}`),u}get forcedAutoLevel(){if(this.nextAutoLevelKey)return-1;return this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),o=this.getStarvationDelay(),u=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(o){let f=this.findBestLevel(l,n,s,o,0,u,d);if(f>=0)return this.rebufferNotice=-1,f}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!o){let f=this.bitrateTestDelay;if(f)c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-f,this.info(`bitrate test took ${Math.round(1000*f)}ms, set first fragment max fetchDuration to ${Math.round(1000*c)} ms`),u=d=1}let h=this.findBestLevel(l,n,s,o,c,u,d);if(this.rebufferNotice!==h)this.rebufferNotice=h,this.info(`${o?"rebuffering expected":"buffer is empty"}, optimal quality level ${h}`);if(h>-1)return h;let g=i.levels[n],m=i.loadLevelObj;if(m&&(g==null?void 0:g.bitrate)=t;k--){var C;let G=g[k],D=k>h;if(!G)continue;if(L&&G.codecSet!==L||x&&G.videoRange!==x||D&&b>G.frameRate||!D&&b>0&&bj.smooth===!1)){if(!T||k!==P){O.push(k);continue}}let U=G.details,F=(d?U==null?void 0:U.partTarget:U==null?void 0:U.averagetargetduration)||w||1,M;if(!D)M=n*e;else M=a*e;let q=w&&s>=w*2&&r===0?G.averageBitrate:G.maxBitrate,X=this.getTimeToLoadFrag(Y,M,q*F,!U||U.live);if(M>=q&&(k===o||G.loadError===0&&G.fragmentError===0||un(G,E.errorPenaltyExpireMs))&&(X<=Y||!H(X)||S&&!this.bitrateTestDelay||X${k} adjustedbw(${Math.round(M)})-bitrate=${Math.round(M-q)} ttfb:${Y.toFixed(1)} avgDuration:${F.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${X.toFixed(1)} firstSelection:${T} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${f}`)}if(T)this.firstSelection=k;return k}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);if(this._nextAutoLevel!==t)this.nextAutoLevelKey="",this._nextAutoLevel=t}deriveNextAutoLevel(e){if(!this.hls)return-1;let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}};In={search:function(e,t){let i=0,s=e.length-1,r=null,n=null;while(i<=s){r=(i+s)/2|0,n=e[r];let a=t(n);if(a>0)i=r+1;else if(a<0)s=r-1;else return n}return null}};Ee={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ye={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};Is=class Is extends Qe{constructor(e){super("error-controller",e.logger);this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.ERROR,this.onError,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;if(!e)return;e.off(y.ERROR,this.onError,this),e.off(y.ERROR,this.onErrorOut,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this)}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){if((e==null?void 0:e.type)===J.MAIN)return e.level;return this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;if((e=t.loadLevelObj)!=null&&e.details||i===-1)return t.loadLevel;return i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;let s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter((n)=>s.indexOf(n.groupId)>=0).some((n)=>{var a;return(a=n.details)==null?void 0:a.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;let s=this.hls,r=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=li();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ee.SendAlternateToPenaltyBox;return}case R.PLAYLIST_UNCHANGED_ERROR:case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var n;let a=t.parent===J.MAIN?t.level:s.loadLevel;if(t.details===R.LEVEL_EMPTY_ERROR&&!!((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live))t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a);else t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,a)}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:if(typeof(r==null?void 0:r.level)==="number")t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level);return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){let a=s.loadLevelObj;if(a&&(r.type===se.AUDIO_TRACK&&a.hasAudioGroup(r.groupId)||r.type===se.SUBTITLE_TRACK&&a.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Ee.SendAlternateToPenaltyBox,t.errorAction.flags=ye.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ee.SendAlternateToPenaltyBox,flags:ye.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ee.SendAlternateToPenaltyBox,flags:ye.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,t.level);return;case R.MEDIA_SOURCE_REQUIRES_RESET:if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,t.level);t.errorAction.flags|=ye.ResetMediaSource|ye.SwitchToSDR;return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_APPEND_NO_PROGRESS:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction=li();return}if(t.type===Q.KEY_SYSTEM_ERROR)t.levelRetry=!1,t.errorAction=li()}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,s=ir(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(Mt(s,r,ci(e),e.response))return{action:Ee.RetryRequest,flags:ye.None,retryConfig:s,retryCount:r};let a=this.getLevelSwitchAction(e,t);if(s)a.retryConfig=s,a.retryCount=r;return a}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=ir(on(e)?n:r,e),l=t.levels.reduce((u,d)=>u+d.fragmentError,0);if(s){if(e.details!==R.FRAG_GAP)s.fragmentError++;if(!ln(e)){if(Mt(a,l,ci(e),e.response))return{action:Ee.RetryRequest,flags:ye.None,retryConfig:a,retryCount:l}}}let o=this.getLevelSwitchAction(e,i);if(a)o.retryConfig=a,o.retryCount=l;return o}getLevelSwitchAction(e,t){let i=this.hls;if(t===null||t===void 0)t=i.loadLevel;let s=this.hls.levels[t];if(s){var r,n;let o=e.details;if(s.loadError++,s.loadErrorTime=self.performance.now(),o===R.BUFFER_APPEND_ERROR)s.fragmentError++;let u=-1,{levels:d,loadLevel:c,minAutoLevel:h,maxAutoLevel:g}=i;if(!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError)i.loadLevel=-1;let m=(r=e.frag)==null?void 0:r.type,v=(m===J.AUDIO&&o===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&pr(e))&&d.some(({audioCodec:L})=>s.audioCodec!==L),p=e.sourceBufferName==="video"&&pr(e)&&d.some(({codecSet:L,audioCodec:x})=>s.codecSet!==L&&s.audioCodec===x),{type:S,groupId:T}=(n=e.context)!=null?n:{};for(let L=d.length;L--;){let x=(L+c)%d.length;if(x!==c&&x>=h&&x<=g&&(d[x].loadError===0||un(d[x],i.config.errorPenaltyExpireMs))){var a,l;let b=d[x];if(o===R.FRAG_GAP&&m===J.MAIN&&e.frag){let I=d[x].details;if(I){let A=Rs(e.frag,I.fragments,e.frag.start);if(A!=null&&A.gap)continue}}else if(S===se.AUDIO_TRACK&&b.hasAudioGroup(T)||S===se.SUBTITLE_TRACK&&b.hasSubtitleGroup(T))continue;else if(m===J.AUDIO&&(a=s.audioGroups)!=null&&a.some((I)=>b.hasAudioGroup(I))||m===J.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some((I)=>b.hasSubtitleGroup(I))||v&&s.audioCodec===b.audioCodec||p&&s.codecSet===b.codecSet||!v&&s.audioCodec!==b.audioCodec)continue;u=x;break}}if(u>-1&&i.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Ee.SendAlternateToPenaltyBox,flags:ye.None,nextAutoLevel:u}}return{action:Ee.SendAlternateToPenaltyBox,flags:ye.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i,s;switch((i=t.errorAction)==null?void 0:i.action){case Ee.DoNothing:break;case Ee.SendAlternateToPenaltyBox:if(this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP&&t.details!==R.PLAYLIST_UNCHANGED_ERROR&&!_n(t))t.fatal=!0;break;case Ee.RetryRequest:break}if((((s=t.errorAction)==null?void 0:s.flags)||0)&ye.ResetMediaSource)this.hls.recoverMediaError();if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let s=i.nextAutoLevel;if(i.flags===ye.None)this.switchLevel(e,s);else if(i.flags&ye.SwitchToSDR){let a=this.hls.levels,l=a.length;for(let o=l;o--;)if(a[o].videoRange!=="SDR")a[o].fragmentError++,a[o].loadError++;else if(s===void 0)s=o}else if(i.flags&ye.MoveAllAlternatesMatchingHDCP){let a=this.getVariantLevelIndex(e.frag),l=t.levels[a],o=l==null?void 0:l.attrs["HDCP-LEVEL"];i.hdcpLevel=o;let u=o==="NONE";if(o&&!u)t.maxHdcpLevel=ls[ls.indexOf(o)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);else{if(u)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");i.flags|=ye.MoveAllAlternatesMatchingKey}}if(i.flags&ye.MoveAllAlternatesMatchingKey){let a=e.decryptdata;if(a){let l=this.hls.levels,o=l.length;for(let d=o;d--;)if(this.variantHasKey(l[d],a)){var r,n;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(r=l[d].audioGroups)==null?void 0:r.join(",")}" (${(n=e.frag)==null?void 0:n.type} fragment) ${Et(a.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}let u=e.frag;if(this.hls.levels.length=0&&u>t.partTarget)l+=1}let o=i&&hr(i);return new vi(a,l>=0?l:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){let{details:s,stats:r}=t,n=s.fragments,a=self.performance.now(),l=r.loading.first?Math.max(0,Math.floor(a-r.loading.first)):0;s.advancedDateTime=Date.now()-l;let o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){let d=Math.max(o||0,0);s.appliedTimelineOffset=d,n.forEach((c)=>{c==null||c.setStart(c.playlistOffset+d)})}if(s.live||i!=null&&i.live){var u;let d="levelInfo"in t?t.levelInfo:t.track;s.reloaded(i);let c=(u=n[n.length-1])==null?void 0:u.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let T=Error(`${c} playlist ${d.id} hit max allowed unchanged reloads.`);this.warn(T);let{networkDetails:L,context:x}=t;this.hls.trigger(y.ERROR,{type:Q.NETWORK_ERROR,details:R.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:T,reason:T.message,level:t.level,parent:c,context:x,networkDetails:L,stats:r});return}if(i){wl(i,s,this);let T=s.playlistParsingError;if(T){this.warn(T);let L=this.hls;if(!L.config.ignorePlaylistParsingErrors){let{networkDetails:x}=t;L.trigger(y.ERROR,{type:Q.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:T,reason:T.message,level:t.level,parent:c,networkDetails:x,stats:r});return}s.playlistParsingError=null}}if(s.requestScheduled===-1)s.requestScheduled=r.loading.start;let h=this.hls.mainForwardBufferInfo,g=h?h.end-h.len:0,m=(s.edge-g)*1000,f=Fn(s,m);if(s.requestScheduled+f0){if(P>s.targetduration*3)this.log(`Playlist last advanced ${_.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,S=void 0;else if(i!=null&&i.tuneInGoal&&P-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${w} with playlist age: ${s.age}`),w=0;else{let Y=Math.floor(w/s.targetduration);if(p+=Y,S!==void 0){let O=Math.round(w%s.targetduration/s.partTarget);S+=O}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${_.toFixed(2)}s goal: ${w} skip sn ${Y} to part ${S}`)}s.tuneInGoal=w}if(E=this.getDeliveryDirectives(s,t.deliveryDirectives,p,S),T||!A){s.requestScheduled=a,this.loadingPlaylist(d,E);return}}else if(s.canBlockReload||s.canSkipUntil)E=this.getDeliveryDirectives(s,t.deliveryDirectives,p,S);if(E&&p!==void 0&&s.canBlockReload)s.requestScheduled=r.loading.first+Math.max(f-l*2,f/2);this.scheduleLoading(d,E,s)}else this.clearTimer()}scheduleLoading(e,t,i){let s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}let r=self.performance.now(),n=s.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}let a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,s){let r=hr(e);if(t!=null&&t.skip&&e.deltaUpdateFailed)i=t.msn,s=t.part,r=wt.No;return new vi(i,s,r)}checkRetry(e){let t=e.details,i=ci(e),s=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},l=!!s&&!!a&&(r===Ee.RetryRequest||!s.resolved&&r===Ee.SendAlternateToPenaltyBox);if(l){var o;if(n>=a.maxNumRetry)return!1;if(i&&(o=e.context)!=null&&o.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var u;let d=Nt((u=e.response)==null?void 0:u.code);if(this.clearTimer(),d)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1000);else{let c=Ss(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${c}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),c)}}e.levelRetry=!0,s.resolved=!0}return l}checkOfflineStatus(){if(this.clearTimer(),Nt(0))this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1000);else this.log("Connection restored (online)"),this.loadPlaylist()}};Ae={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};Pr=Math.pow(2,17);Ue=class Ue extends Error{constructor(e){super(e.error.message);this.data=void 0,this.data=e}};Cs=class Cs extends Qe{constructor(e,t){super(e,t);this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){if(!this._tickInterval)return this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0;return!1}clearInterval(){if(this._tickInterval)return self.clearInterval(this._tickInterval),this._tickInterval=null,!0;return!1}clearNextTick(){if(this._tickTimer)return self.clearTimeout(this._tickTimer),this._tickTimer=null,!0;return!1}tick(){if(this._tickCallCount++,this._tickCallCount===1){if(this.doTick(),this._tickCallCount>1)this.tickImmediate();this._tickCallCount=0}else this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}};Fr={length:0,start:()=>0,end:()=>0};B={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_LEVEL:"WAITING_LEVEL"};ks=class ks extends Cs{constructor(e,t,i,s,r){super(s,e.logger);this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=B.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:n,fragCurrent:a,media:l,mediaBuffer:o,state:u}=this,d=l?l.currentTime:0,c=Z.bufferInfo(o?o:l,d,n.maxBufferHole),h=c.len;if(this.log(`Media seeking to ${d}, state: ${u}, ${!h?"out of":"in"} buffer`),this.state===B.ENDED)this.resetLoadingState();else if(a){let m=n.maxFragLookUpTolerance,f=a.start-m,v=a.start+a.duration+m;if(!h||vc.end){let E=dv;if(E||p)if(a.loader&&(p||!this.isFragmentNearlyDownloaded(a)))this.log(`Cancelling fragment load for seek (sn: ${a.sn}) - ${E?"backward":"forward"} seek`),a.abortRequests(),this.resetLoadingState();else this.fragPrevious=null}}if(l){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);let m=this.lastCurrentTime;if(d>m)this.lastCurrentTime=d;if(!this.loadingParts){let f=Math.max(c.end,d),v=this.shouldLoadParts(this.getLevelDetails(),f);if(v)this.log(`LL-Part loading ON after seeking to ${d} with buffer @${f}`),this.loadingParts=v}}let g=!Z.isBuffered(l,d);if(!this.hls.hasEnoughToStart||g){if(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,g)this.startPosition=d}if(h<1&&this.state===B.IDLE)this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new ds(e.config),this.initFragmentLoader=new ds(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ci(e.config)}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===B.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;if(e!=null&&e.loader)e.abortRequests(),this.fragmentTracker.removeFragment(e);this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=B.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let i=this.getLevelDetails();if(i!=null&&i.live)return(this.hls.liveSyncPosition||i.fragmentStart)+this.timelineOffset;return e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){return}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;let r=e.buffered;if(this.config.maxBufferHole&&r&&r.length>1)e=Z.bufferedInfo(r,e.start,0);let n=e.nextStart;if(n&&n>s&&n{let n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)} was dropped during download.`),this.fragmentTracker.removeFragment(n);return}let a=++n.stats.chunkCount;this.log(`load progress ${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)} chunk: ${a}`),this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,s).then((r)=>{if(!r)return;let n=this.state,a=r.frag;if(this.fragContextChanged(a)){if(n===B.FRAG_LOADING||!this.fragCurrent&&n===B.PARSING)this.fragmentTracker.removeFragment(a),this.state=B.IDLE;return}if("payload"in r)this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level} (bytes ${a.stats.loaded})`),this.hls.trigger(y.FRAG_LOADED,r);this._handleFragmentLoadComplete(r)}).catch((r)=>{if(this.state===B.STOPPED||this.state===B.ERROR)return;this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e)})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===Ae.APPENDING){let r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),a=Math.max(e.duration,n?n.len:this.config.maxBufferLength),l=this.backtrackFragment;if((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))i.removeFragment(e)}else if(((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0)i.removeAllFragments();else if(i.hasParts(e.type)){if(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ae.PARTIAL)i.removeFragment(e)}}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,i=e.fragments[e.fragments.length-1];if(i.endList&&!t.isEndListAppended(this.playlistType)){let s=t.getPartialFragment(i.end);if(s)t.removeFragment(s),t.fragBuffered(i,!0)}t.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}if(!e.fragments[0])e.deltaUpdateFailed=!0}waitForLive(e){let t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let s={startOffset:e,endOffset:t,type:i};this.hls.trigger(y.BUFFER_FLUSHING,s)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then((i)=>{var s;let r=i.frag;if(!this.levels||!ss(r,(s=this.fragCurrent)==null?void 0:s.initSegment))throw new Ue({type:Q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,error:Error("init load aborted"),fatal:!1,frag:r,networkDetails:null});return i}).then((i)=>{let{frag:s,payload:r}=i,n=s.decryptdata;if(r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&Ot(n.method)){let a=self.performance.now(),{decryptRange:l}=yi(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,kn(n.method),l).catch((o)=>{throw t.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:s}),this.fragmentLoader.abort(),o}).then((o)=>{let u=self.performance.now();return t.trigger(y.FRAG_DECRYPTED,{frag:s,part:null,payload:o,stats:{tstart:a,tdecrypt:u}}),i.payload=o,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)})}completeInitSegmentLoad(e){let t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){let{initSegment:t}=e;if(!this.bitrateTest&&Fe(e)&&t&&!t.data){var i;return(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch((r)=>{if(this.state===B.STOPPED||this.state===B.ERROR)throw r;if("data"in r)r.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(r);throw this.resetFragmentLoading(e),r})}}unhandledEncryptionError(e,t){var i,s;let r=e.tracks;if(r&&!t.encrypted&&((i=r.audio)!=null&&i.encrypted||(s=r.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let n=this.media,a=Error("EME not supported (light build)");if(this.warn(a.message),!n||n.mediaKeys)return!1;return this.hls.trigger(y.ERROR,{type:Q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!0,error:a,frag:t}),this.resetTransmuxer(),!0}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!ss(e,t)}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?cs(Z.getBuffered(i)):"(detached)"})`),Fe(e)){var s;if(e.type!==J.SUBTITLE){let n=e.elementaryStreams;if(!Object.keys(n).some((a)=>!!n[a])){this.state=B.IDLE;return}}let r=(s=this.levels)==null?void 0:s[e.level];if(r!=null&&r.fragmentError&&(t||this.fragmentTracker.getState(e)!==Ae.PARTIAL))this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0,e.stats.retry=0}this.state=B.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let i=e.frag,{part:s,partsLoaded:r}=e,n=!r||r.length===0||r.some((o)=>!o),{decryptRange:a}=yi(i,s),l=new ki(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n,i.duration,this.iframesOnly,a);this.log(`load complete ${i.type} sn: ${i.sn}${s?" part: "+s.index:""} of ${this.fragInfo(i,!1,s)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,i){var s;let r=null;if(e.encrypted&&!((s=e.decryptdata)!=null&&s.key))this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=B.KEY_LOADING,r=this.keyLoader.load(e,i).then((n)=>{if(!this.fragContextChanged(n.frag)){if(this.hls.trigger(y.KEY_LOADED,n),this.state===B.KEY_LOADING)this.state=B.IDLE;return n}}),this.hls.trigger(y.KEY_LOADING,{frag:e});else if(!e.encrypted){if(r=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),r)this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)}return r}_doFragLoad(e,t,i=null,s){this.fragCurrent=e;let r=t.details;if(!this.levels||!r)throw Error(`frag load aborted, missing level${r?"":" detail"}s`);let n=this.fragPrevious;if(!zt(e,n)){let h=this.shouldLoadParts(t.details,e.end);if(h!==this.loadingParts)this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${n==null?void 0:n.sn}->${e.sn}`),this.loadingParts=h}if(i=Math.max(e.start,i||0),this.loadingParts){let h=r.partList;if(h&&s){if(i>r.fragmentEnd&&r.fragmentHint)e=r.fragmentHint;let g=this.getNextPart(h,e,i);if(g>-1){let m=h[g];if(e=this.fragCurrent=m.fragment,!zt(e,n)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,m)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(m,t.details))return Promise.resolve(null);let f=this.loadKeyFor(e,r);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${g}/${h.length-1}) of ${this.fragInfo(e,!1,m)} cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${i}${m.byteRange.length?` range:${m.byteRange.join("-")}`:""}`),this.nextLoadPosition=m.start+m.duration,this.state=B.FRAG_LOADING;let v,E=this.loadInitSegmentIfNeeded(e);if(f||E){let p=!!f;v=Promise.all([f,E]).then(([S])=>{if(p&&(!S||this.fragContextChanged(S.frag)))return null;return this.doFragPartsLoad(e,m,t,s)}).catch((S)=>this.handleFragLoadError(S))}else v=this.doFragPartsLoad(e,m,t,s).catch((p)=>this.handleFragLoadError(p));if(this.hls.trigger(y.FRAG_LOADING,{frag:e,part:m,targetBufferTime:i}),this.fragCurrent===null)return Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts"));return v}else if(!e.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}if(this.loadingParts){var a;this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${e.sn} loaded parts: ${(a=r.partList)==null?void 0:a.filter((h)=>h.loaded).map((h)=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let l=this.loadInitSegmentIfNeeded(e),o=this.loadKeyFor(e,r,l);if(this.fragContextChanged(e)){var u;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(u=this.fragCurrent)==null?void 0:u.relurl}`),l==null||l.catch(()=>null),o==null||o.catch(()=>null),Promise.resolve(null)}if(this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${i}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),H(e.sn)&&!this.bitrateTest)this.nextLoadPosition=e.start+e.duration;this.state=B.FRAG_LOADING;let d=this.config.progressive&&e.type!==J.SUBTITLE,c;if(d&&o)c=o.then((h)=>{if(!h||this.fragContextChanged(h.frag))return null;return this.fragmentLoader.load(e,this.iframesOnly,s,l)}).catch((h)=>this.handleFragLoadError(h));else c=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,d?s:void 0,d?l:void 0),o,l]).then(([h])=>{if(!d&&s)s(h);return h}).catch((h)=>this.handleFragLoadError(h));if(this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null)return Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING"));return Promise.all([c,l]).then(([h])=>h)}doFragPartsLoad(e,t,i,s){return new Promise((r,n)=>{var a;let l=[],o=(a=i.details)==null?void 0:a.partList,u=(d)=>{this.fragmentLoader.loadPart(e,d,s).then((c)=>{l[d.index]=c;let h=c.part;this.hls.trigger(y.FRAG_LOADED,c);let g=Dr(i.details,e.sn,d.index+1)||Nn(o,e.sn,d.index+1);if(g)u(g);else return r({frag:e,part:h,partsLoaded:l})}).catch(n)};u(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;if(t.frag&&t.details===R.INTERNAL_ABORTED)this.handleFragLoadAborted(t.frag,t.part);else if(t.frag&&t.type===Q.KEY_SYSTEM_ERROR&&!t.fatal)t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag);this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:Q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==B.PARSING){if(!this.fragCurrent&&this.state!==B.STOPPED&&this.state!==B.ERROR)this.state=B.IDLE;return}let{frag:i,part:s,level:r}=t,n=self.performance.now();if(i.stats.parsing.end=n,s)s.stats.parsing.end=n;let a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);if(o!==this.loadingParts)this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=o;this.updateLevelTiming(i,s,r,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var i;let s=e.partList[0],r=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=r){if(this.playhead>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:n}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;let a=t[s],l=a.details,o=n>-1?Dr(l,r,n):null,u=o?o.fragment:Mn(l,r,i);if(!u)return null;if(i&&i!==u)u.stats=i.stats;return{frag:u,part:o,level:a}}bufferFragmentData(e,t,i,s,r){if(this.state!==B.PARSING)return;if(Fe(t)&&!this.fragContextChanged(t))this.fragPrevious=t;let{data1:n,data2:a}=e,l=n;if(a)l=He(n,a);if(!l.length)return;let o=this.initPTS[t.cc],u=o?-o.baseTime/o.timescale:void 0,d={type:e.type,frag:t,part:i,chunkMeta:s,offset:u,parent:t.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,d),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!Z.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,s=Z.bufferInfo(t,i,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*0.25),a=Math.max(Math.min(e.start-n,s.end-n),i+n);if(e.start-a>n)this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;let s=this.playhead,n=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,n)}getFwdBufferInfoAtPos(e,t,i,s){let r=Z.bufferInfo(e,t,s);if(r.len===0&&r.nextStart!==void 0){let n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(r.nextStart<=n.end||n.gap)){let a=Math.max(Math.min(r.nextStart,n.end)-t,s);return Z.bufferInfo(e,t,a)}}return r}getMaxBufferLength(e){let{config:t}=this,i;if(e)i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength);else i=t.maxBufferLength;return Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){let s=e.nextStart;if(s&&i.start>s){let r=e.buffered;if(r){let{len:n,bufferedIndex:a}=e;for(let l=r.length-1;l>a;l--)if(r[l].start=t}}return!1}reduceMaxBufferLength(e,t){let i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t/2),r=Math.max(e-t*3,i.maxMaxBufferLength/2,s);if(r>=s)return i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0;return!1}getAppendedFrag(e){let t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;if(t&&"fragment"in t)return t.fragment;return t}getNextFragment(e,t){let i=t.fragments,s=i.length;if(!s)return null;let{config:r}=this,n=t.fragmentStart,a=r.lowLatencyMode&&!!t.partList,l=null;if(t.live){let d=r.initialLiveManifestSize;if(s=n)f=h,v=h===c?"config":"next load start";else if(g)f=g,v="live edge";else f=e,v="buffer pos";if(f1)return!0}return!1}getNextFragmentLoopLoading(e,t,i,s,r){let n=null;if(e.gap){if(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&i.nextStart){let a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(a!==null&&i.len+a.len>=r){let l=n.sn;if(this.loopSn!==l)this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l;return null}}}return this.loopSn=void 0,n}get primaryPrefetch(){if(hs(this.config));return!1}filterReplacedPrimary(e,t){if(!e)return e;if(hs(this.config));return e}getNextPart(e,t,i){let s=-1,r=!1,n=!0;for(let l=0,o=e.length;l-1&&i ${a.fragment.sn})`);return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,s=null;if(i){if(e.hasProgramDateTime){if(s=yl(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s)this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)}if(!s){let r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){let n=t[r-e.startSN];if(i.cc===n.cc)s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`)}if(!s){if(s=Tl(e,i.cc,i.end),s)this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`)}}}else{let r=this.hls.liveSyncPosition;if(r!==null)s=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e)}return s}getFragmentAtPosition(e,t,i){let{config:s}=this,{fragPrevious:r}=this,{fragments:n,endSN:a}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:o}=s,u=i.partList,d=!!(this.loadingParts&&u!=null&&u.length&&l);if(d&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn)n=n.concat(l),a=l.sn;if(r&&this.fragmentTracker.getState(r)===Ae.NOT_LOADED)r=null;let c;if(et-o||(h=this.media)!=null&&h.paused||!this.startFragRequested?0:o;c=Rs(r,n,e,m)}else c=n[n.length-1];if(c){let g=c.sn-i.startSN,m=this.fragmentTracker.getState(c);if(m===Ae.OK||m===Ae.PARTIAL&&c.gap)r=c;if(zt(c,r)&&(!d||u[0].fragment.sn>c.sn||!i.live)){let f=n[g+1];if(c.sn${e.startSN} fragments: ${s}`),l}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;if(i=0)i=this.nextLoadPosition;return i}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;let i=(t=this.media)==null?void 0:t.currentTime;if(H(i))return i;return this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==J.MAIN)return!1;let t=this.getLevelDetails();if(t)return t.iframesOnly;return(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){if(this.transmuxer&&e.type===this.playlistType&&Fe(e)&&e.stats.aborted)this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e)}resetFragmentLoading(e){if(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==B.FRAG_LOADING_WAITING_RETRY)this.state=B.IDLE}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let E=this.getCurrentContext(t.chunkMeta);if(E)t.frag=E.frag}let{frag:i,part:s}=t;if(!i||!this.levels||i.type!==e)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${(r=this.fragCurrent)==null?void 0:r.relurl}`);return}let n=t.details===R.FRAG_GAP;if(n)this.fragmentTracker.addAsGap(i);let a=t.errorAction;if(!a){this.state=B.ERROR;return}let{action:l,flags:o,retryCount:u=0,retryConfig:d}=a,c=!!d,h=c&&l===Ee.RetryRequest,g=c&&!a.resolved&&o&ye.MoveAllAlternatesMatchingHost,m=this.hls.latestLevelDetails,f=m==null?void 0:m.live;if(!h&&g&&Fe(i)&&f&&i.sn=t||i&&!Nt(0)){if(i)this.log("Connection restored (online)");this.resetStartWhenNotLoaded(),this.state=B.IDLE}}reduceLengthAndFlushBuffer(e){if(this.state===B.PARSING||this.state===B.PARSED){let{frag:t,parent:i}=e,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>0.5;if(r)this.reduceMaxBufferLength(s.len,(t==null?void 0:t.duration)||10);let n=!r;if(n)this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`);else if(s.nextStart&&t&&s.nextStart>t.start)this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,i===J.AUDIO?i:void 0);if(t)this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start;return this.resetLoadingState(),n}return!1}resetFragmentErrors(e){if(e===J.AUDIO)this.fragCurrent=null;if(!this.hls.hasEnoughToStart)this.startFragRequested=!1;if(this.state!==B.STOPPED)this.state=B.IDLE}afterBufferFlushed(e,t){if(!e)return;let i=Z.getBuffered(e);if(this.fragmentTracker.detectEvictedFragments(t,i,this.playlistType),this.state===B.ENDED)this.resetLoadingState()}resetLoadingState(){if(this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==B.STOPPED)this.state=B.IDLE}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.getLevelDetails();if(e!=null&&e.live)this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState();else this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){let r=i.details;if(!r){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((d,c)=>{let h=e.elementaryStreams[c];if(h){let g=h.endPTS-h.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${g})`),d||!1;let m=s.partial?0:wn(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this.iframesOnly,this);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:r,level:i,drift:m,type:c,frag:e,start:h.startPTS,end:h.endPTS}),!0}return d},!1)){var a,l,o,u;let d=((a=this.transmuxer)==null?void 0:a.error)===null,c=((l=this.transmuxer)==null?void 0:l.error)!=null,h=((o=(u=this.levels)==null?void 0:u.length)!=null?o:0)>1;if(i.fragmentError===0||d&&(i.fragmentError<2||e.endList)||c&&h)this.treatAsGap(e,i);if(d){let g=Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(g.message),this.hls.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:g,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=B.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN}-${(r=t&&!i?e.endPTS:(i||e).end)!=null?r:NaN}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(e,t){if(t)t.fragmentError++;this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;let i=(t=e.loader)==null?void 0:t.stats;if(!i)return!1;let s=i.loading.first>0,n=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&n<=0.15}recoverWorkerError(e){if(e.event==="demuxerWorker"){if(this.fragmentTracker.removeAllFragments(),this.transmuxer)this.transmuxer.destroy(),this.transmuxer=null;this.resetStartWhenNotLoaded(),this.resetLoadingState()}}set state(e){let t=this._state;if(t!==e)this._state=e,this.log(`${t}->${e}`)}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let i=0,{hls:s,media:r,config:n,levels:a,playlistType:l}=this,o=this.getLevelDetails();if(r&&!r.paused&&a){var u;let h=l===J.AUDIO?st.estimatedAudioBitrate(e.audioCodec,128000):e.maxBitrate,g=1+s.ttfbEstimate/1000,m=s.bandwidthEstimate*n.abrBandWidthUpFactor,f=o&&(this.loadingParts?o.partTarget:o.averagetargetduration)||((u=this.fragCurrent)==null?void 0:u.duration)||6;if(i=g+h*f/m,!e.details)i+=g}let d=this.playhead,c=!(o!=null&&o.live)||t.end-d>i*1.5;return{fetchdelay:i,okToFlushForwardBuffer:c}}scheduleTrackSwitch(e,t,i){let{media:s,playlistType:r}=this;if(!s||!e)return;let n=i?this.getBufferedFrag(this.playhead+t):null;if(n){let l=this.followingBufferedFrag(n);if(l){var a;this.abortCurrentFrag();let o=l.maxStartPTS?l.maxStartPTS:l.start,u=l.duration,d=Math.max(n.end,o+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?0.5:0.125)),u*(this.couldBacktrack?0.75:0.25)));if((((a=this.getLevelDetails())==null?void 0:a.fragmentStart)||0)>d)return;let h=r===J.MAIN?null:"audio";this.flushMainBuffer(d,Number.POSITIVE_INFINITY,h),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){let s=t===J.AUDIO;this.flushMainBuffer(0,i.start-(s?0:1),s?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){if(e)return this.getBufferedFrag(e.end+0.5);return null}abortCurrentFrag(){let e=this.fragCurrent;if(this.fragCurrent=null,e)e.abortRequests(),this.fragmentTracker.removeFragment(e);switch(this.state){case B.KEY_LOADING:case B.FRAG_LOADING:case B.FRAG_LOADING_WAITING_RETRY:case B.PARSING:case B.PARSED:this.state=B.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(Z.isBuffered(e,i))t=this.getAppendedFrag(i);else if(Z.isBuffered(e,i+0.1))t=this.getAppendedFrag(i+0.1);if(t){if(this.backtrackFragment=void 0,!zt(t,this.fragPlaying))return this.fragPlaying=t,!0}}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:i,config:s,playlistType:r}=this;if(t!=null&&t.readyState&&e&&i&&s){let n=this.getBufferOutput(),a=this.getFwdBufferInfo(n,r);if(!a)return;let l=r===J.AUDIO?i.nextAudioTrack:i.nextLoadLevel,o=e[l],{fetchdelay:u,okToFlushForwardBuffer:d}=this.calculateOptimalSwitchPoint(o,a);this.scheduleTrackSwitch(a,u,d)}this.tickImmediate()}};Nr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;Yn=class Yn extends Error{constructor(e){super(e);this.name=Wn}};Ps=class Ps extends Qe{constructor(e,t){super("buffer-controller",e.logger);this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=(i)=>{var s;if(!this.hls)return;if(((s=this.mediaSource)==null?void 0:s.readyState)!=="open")return;if(!this.media||this.media.seeking)return;this.hls.pauseBuffering()},this._onStartStreaming=(i)=>{if(!this.hls)return;this.hls.resumeBuffering()},this._onMediaSourceOpen=(i)=>{let{media:s,mediaSource:r}=this;if(i)this.log("Media source opened");if(!s||!r)return;if(Se(r,"sourceopen",this._onMediaSourceOpen),Se(s,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:s,mediaSource:r}),this.mediaSource!==null)this.checkPendingTracks()},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let i=this.media.error,{appendError:s,appendErrors:r}=this,n=!1;if(!s&&i)n=Math.max(++r.audio,++r.video,++r.audiovideo)>=this.hls.config.appendErrorMaxRetry;let a=Error(`MediaSource closed while media attached${Br(n,i)}`);this.warn(a),this.hls.trigger(y.ERROR,Te({fatal:n},s,{type:Q.MEDIA_ERROR,details:R.MEDIA_SOURCE_REQUIRES_RESET,error:a}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:s}=this;if(i!==s)this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this._onMediaError=()=>{let{media:i}=this;if(i){var s,r;this.log(`Media error (code: ${(s=i.error)==null?void 0:s.code}): ${(r=i.error)==null?void 0:r.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=Ao(it(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){if(this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue)this.operationQueue.destroy(),this.operationQueue=null;this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_APPENDING,this.onBufferAppending,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.BUFFER_EOS,this.onBufferEos,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.FRAG_PARSED,this.onFragParsed,this),e.on(y.FRAG_CHANGED,this.onFragChanged,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_APPENDING,this.onBufferAppending,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_EOS,this.onBufferEos,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.FRAG_PARSED,this.onFragParsed,this),e.off(y.FRAG_CHANGED,this.onFragChanged,this),e.off(y.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let r=this.isUpdating();if(!r)this.operationQueue.removeBlockers();let n=this.isQueued();if(r||n)this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`);this.operationQueue.destroy()}let s=this.transferData;if(s&&!this.sourceBufferCount&&s.mediaSource===t)Te(i,s.tracks);else this.sourceBuffers.forEach((r)=>{let[n]=r;if(n)i[n]=Te({},this.tracks[n]),this.removeBuffer(n);r[0]=r[1]=null});return{media:e,mediaSource:t,tracks:i}}initTracks(){let e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var i;let s=2;if(t.audio&&!t.video||!t.altAudio)s=1;if(this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s)this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let s=it(this.appendSource);if(s){let r=!!t.mediaSource;if(r||t.overrides)this.transferData=t,this.overrides=t.overrides;let n=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(n),r)this._objectUrl=i.src,this.attachTransferred();else{let a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&n instanceof l,$r(i),zl(i,a),i.load()}catch(l){i.src=a}else i.src=a}if(be(i,"emptied",this._onMediaEmptied),be(i,"error",this._onMediaError),this.appendSource)be(i,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,i;if(this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),be(e,"sourceopen",this._onMediaSourceOpen),be(e,"sourceended",this._onMediaSourceEnded),be(e,"sourceclose",this._onMediaSourceClose),this.appendSource)be(e,"startstreaming",this._onStartStreaming),be(e,"endstreaming",this._onEndStreaming)}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,s=t.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{if(this.media&&this.mediaSourceOpenOrEnded)this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) +required tracks: ${De(i,(l,o)=>l==="initSegment"?void 0:o)}; +transfer tracks: ${De(s,(l,o)=>l==="initSegment"?void 0:o)}}`),!bo(s,i)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,o=this.details,u=Math.max(l,(o==null?void 0:o.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,r.forEach((l)=>{let o=l,u=s[o];if(u){let d=u.buffer;if(d){let c=this.fragmentTracker,h=u.id;if(c.hasFragments(h)||c.hasParts(h)){let f=Z.getBuffered(d);c.detectEvictedFragments(o,f,h,null,null,!0)}let g=zi(o),m=[o,d];if(this.sourceBuffers[g]=m,d.updating&&this.operationQueue)this.operationQueue.prependBlocker(o);this.trackSourceBuffer(o,u)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{if(a)this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let a=r.readyState==="open";try{let l=r.sourceBuffers;for(let o=l.length;o--;){if(a)l[o].abort();r.removeSourceBuffer(l[o])}if(a)r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}if(this.sourceBufferCount)this.onBufferReset()}if(Se(r,"sourceopen",this._onMediaSourceOpen),Se(r,"sourceended",this._onMediaSourceEnded),Se(r,"sourceclose",this._onMediaSourceClose),this.appendSource)Se(r,"startstreaming",this._onStartStreaming),Se(r,"endstreaming",this._onEndStreaming);this.mediaSource=null,this._objectUrl=null}if(s){if(Se(s,"emptied",this._onMediaEmptied),Se(s,"error",this._onMediaError),Se(s,"seeking",this._onStartStreaming),!i){if(n)self.URL.revokeObjectURL(n);if(this.mediaSrc===n){if(s.removeAttribute("src"),this.appendSource)$r(s);s.load()}else this.warn("media|source.src was changed by a third party - skip cleanup")}this.media=null}}onBufferReset(){this.sourceBuffers.forEach(([e])=>{if(e)this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;if((s=this.mediaSource)!=null&&s.sourceBuffers.length)this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[zi(e)]=[null,null];let t=this.tracks[e];if(t)this.clearBufferAppendTimeoutId(t),t.buffer=void 0}resetQueue(){if(this.operationQueue)this.operationQueue.destroy();this.operationQueue=new Kn(this.tracks)}onBufferCodecs(e,t){var i;let s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let n="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&(("audio"in t)||("video"in t)),a=!n&&this.sourceBufferCount&&this.media&&r.some((l)=>!s[l]);if(n||a){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`);return}if(r.forEach((l)=>{var o,u;let d=t[l],{id:c,codec:h,levelCodec:g,container:m,metadata:f,supplemental:v}=d,E=s[l],p=(o=this.transferData)==null||(o=o.tracks)==null?void 0:o[l],S=p!=null&&p.buffer?p:E,T=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),L=S==null?void 0:S.levelCodec;if(!E)E=s[l]={buffer:void 0,listeners:[],codec:h,supplemental:v,container:m,levelCodec:g,metadata:f,id:c};let x=oi(T,L),b=x==null?void 0:x.replace(Nr,"$1"),I=oi(h,g),A=(u=I)==null?void 0:u.replace(Nr,"$1");if(I&&x&&b!==A){if(l.slice(0,5)==="audio")I=mi(I,this.appendSource);if(this.log(`switching codec ${T} to ${I}`),I!==(E.pendingCodec||E.codec))E.pendingCodec=I;E.container=m,this.appendChangeType(l,m,I)}}),this.tracksReady||this.sourceBufferCount)t.tracks=this.sourceBufferTracks;if(this.sourceBufferCount)return;if(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main")this.log("Main audio-only"),this.bufferCodecEventsTotal=1;if(this.mediaSourceOpenOrEnded)this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let s=`${t};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{let n=this.tracks[e];if(n){let a=n.buffer;if(a!=null&&a.changeType)this.log(`changing ${e} sourceBuffer type to ${s}`),a.changeType(s),n.codec=i,n.container=t}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:(n)=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,s=i+e.duration*0.05;if(((t=this.fragmentTracker.getAppendedFrag(i,J.MAIN))==null?void 0:t.gap)===!0)return;let n={label:"block-audio",execute:()=>{var a,l;if(this.lastVideoAppendEnd>s||Z.isBuffered((a=this.tracks.video)==null?void 0:a.buffer,s)||((l=this.fragmentTracker.getAppendedFrag(s,J.MAIN))==null?void 0:l.gap)===!0)this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:(a)=>{this.warn("Error executing block-audio operation",a)}};this.append(n,"audio",!0)}unblockAudio(){if(this.operationQueue)this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:l,chunkMeta:o,offset:u}=t,d=o.buffering[r],c=Fe(a)&&!l&&!a.gap&&!o.partial&&!o.iframe,h=null,g=!1,{sn:m,cc:f}=a,v=self.performance.now();d.start=v;let E=a.stats.buffering,p=l?l.stats.buffering:null;if(E.start===0)E.start=v;if((p==null?void 0:p.start)===0)p.start=v;let S=i.audio,T=!1;if(r==="audio"&&(S==null?void 0:S.container)==="audio/mpeg")T=!this.lastMpegAudioChunk||o.id===1||this.lastMpegAudioChunk.sn!==o.sn,this.lastMpegAudioChunk=o;let L=i.video,x=L==null?void 0:L.buffer;if(x&&m!=="initSegment"&&u!==void 0){let A=S==null?void 0:S.buffer,_=l||a;if(r==="audio"&&n!=="main"&&!(L.ending||L.ended)&&A&&Z.getBuffered(A).length){let w=_.start+_.duration*0.05,Y=Z.getBuffered(x),O=this.currentOp("video");if(!Y.length&&!O)this.blockAudio(_);else if(!Z.isBuffered(x,w)&&this.lastVideoAppendEnd_.duration)this.unblockAudio();else if(this.isAudioBlocked())this.executeNext("audio")}}let b=(l||a).start,I={label:`append-${r}`,execute:()=>{var A;d.executeStart=self.performance.now();let _=(A=this.tracks[r])==null?void 0:A.buffer;if(_){if(c)h=Z.timeRangesToArray(Z.getBuffered(_)),g=Gr(Xi(h,a),a);if(T)this.updateTimestampOffset(_,b,0.1,r,m,f);else if(u!==void 0&&H(u))this.updateTimestampOffset(_,u,0.000001,r,m,f)}this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);let A=self.performance.now();if(d.executeEnd=d.end=A,E.first===0)E.first=A;if((p==null?void 0:p.first)===0)p.first=A;let _={};if(this.sourceBuffers.forEach(([P,w])=>{if(P)_[P]=Z.getBuffered(w)}),c){let P=this.getFragmentAppendProgress(a),w=_[r];if(w&&h){let Y=Z.timeRangesToArray(w),O=Xi(Y,a);P.progressed||(P.progressed=O-Xi(h,a)>ql);let C=g&&Gr(O,a);P.fullyBuffered[r]=P.fullyBuffered[r]===void 0?C:P.fullyBuffered[r]&&C}}this.hls.trigger(y.BUFFER_APPENDED,{type:r,frag:a,part:l,chunkMeta:o,parent:n,timeRanges:_})},onError:(A)=>{var _;this.clearBufferAppendTimeoutId(this.tracks[r]);let P=A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A;if(P){if(!this._quotaEvictionPending[r]){let C=this.getBackBufferEvictionTarget(r,s.byteLength,a.type);if(C>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${m} - evicting back buffer to ${C.toFixed(3)}s and retrying`);let k=this.getFlushOp(r,0,C),G=this.getClearEvictionPendingOp(r);this.insertNext([k,I,G],r);return}this.warn(`QuotaExceededError on "${r}" sn: ${m} - no back buffer available to evict`)}}if(c)this.getFragmentAppendProgress(a).errored=!0;let w={type:Q.MEDIA_ERROR,parent:n,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:l,chunkMeta:o,error:A,err:A,fatal:!1},Y=(_=this.media)==null?void 0:_.error;if(A.name===Wn&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))w.errorAction=li(!0);else{var O;if(P)w.details=R.BUFFER_FULL_ERROR;let C=++this.appendErrors[r],k=this.hls.config.appendErrorMaxRetry;if(this.warn(`Failed ${C}/${k+1} times to append segment in "${r}" sourceBuffer with error: ${A.message}`),C>=k)w.fatal=!P;let G=(O=this.mediaSource)==null?void 0:O.readyState;if(G==="ended"||G==="closed"||!!Y)this.warn(`MediaSource readyState "${G}" during SourceBuffer${Br(w.fatal,Y)}`),w.details=R.MEDIA_SOURCE_REQUIRES_RESET}if(this.appendError=w,this.hls.trigger(y.ERROR,w),P&&this.hls)this.trimBuffers(a.start,1)}};this.log(`queuing "${r}" append sn: ${m}${l?" p: "+l.index:""} of ${n} playlist ${a.level} cc: ${f} offset: ${u} bytes: ${s.byteLength}`),this.append(I,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{var s;let r=(s=this.tracks[e])==null?void 0:s.buffer;this.log(`Remove request ${t}-${i} from ${e} Source Buffer complete > buffer: ${r?cs(Z.getBuffered(r)):"(detached)"}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:t,end:i})},onError:(s)=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:0,end:0,error:s})}}}onBufferFlushing(e,t){let{type:i,startOffset:s,endOffset:r}=t;if(!i||i==="audio")this.unblockAudio();if(i)this.append(this.getFlushOp(i,s,r),i);else this.sourceBuffers.forEach(([n])=>{if(n)this.append(this.getFlushOp(n,s,r),n)})}onFragParsed(e,t){let{frag:i,part:s,chunkMeta:r}=t,n=[],a=s?s.elementaryStreams:i.elementaryStreams;if(a[he.AUDIOVIDEO])n.push("audiovideo");else{if(a[he.AUDIO])n.push("audio");if(a[he.VIDEO])n.push("video")}let l=()=>{let o=self.performance.now();if(i.stats.buffering.end=o,s)s.stats.buffering.end=o;let u=s?s.stats:i.stats;if(this.checkAppendProgress(i,s,r,n),!this.hls)return;if(this.hls.trigger(y.FRAG_BUFFERED,{frag:i,part:s,stats:u,id:i.type,chunkMeta:r}),!s&&i.gap&&u.retry)this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${u.retry}`)};if(n.length===0)this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${s?`part: ${s.index} of `:""}sn: ${i.sn}`);this.blockBuffers(l,n).catch((o)=>{this.warn(`Fragment buffered callback ${o.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var i,s;let r=(i=this.hls)==null?void 0:i.config;if(!r)return;let{backBufferLength:n,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,n,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:o}=this,u=(s=this.appendError)==null?void 0:s.sourceBufferName;Object.keys(l).forEach((d)=>{if(!l[d])return;if(o[d]=0,d===u)this.appendError=void 0;if(d==="audio"||d==="video"){if(o.audiovideo=0,u==="audiovideo")this.appendError=void 0}else if(o.audio=0,o.video=0,u!=="audiovideo")this.appendError=void 0})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([n])=>{if(n){let a=this.tracks[n];if(!t.type||t.type===n){if(a.ending=!0,!a.ended)a.ended=!0,this.log(`${n} buffer reached EOS`)}}});let s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;if(this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var a;return n&&!((a=this.tracks[n])!=null&&a.ended)}))if(this.unblockAudio(),s)this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:n}=this;if((n==null?void 0:n.readyState)!=="open"){if(n)this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.endOfStream(),this.hls.trigger(y.BUFFERED_TO_END,void 0)});else this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0);else if(t.type==="video")this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];if(t)t.ending=!1}})}onLevelUpdated(e,{details:t}){if(!t.fragments.length)return;this.details=t,this.updateDuration()}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();if(!e)return;this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var i;let s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;if(H(s)&&s!==t.frag.level)this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,i){let{media:s}=this;if(!s)return 0;return this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,i,t)}getFragmentAppendProgress(e){var t;let i=Ur(e),s=this.fragmentAppendProgress[i];if(((t=s)==null?void 0:t.stats)!==e.stats)s={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=s;return s}checkAppendProgress(e,t,i,s){if(t||!Fe(e)||e.gap||i.iframe||i.partial)return;let r=Ur(e),n=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];let a=e.stats.buffering;if(a.start&&!a.first)return;let l=(n==null?void 0:n.stats)===e.stats?n:void 0;if(l!=null&&l.errored)return;let o=s.length>0&&s.every((h)=>(l==null?void 0:l.fullyBuffered[h])===!0);if(l!=null&&l.progressed||o){delete this.appendsWithoutProgress[r];return}if(!l&&s.length===0)return;let u=(this.appendsWithoutProgress[r]||0)+1,d=this.hls;if(u>=d.config.appendErrorMaxRetry)delete this.appendsWithoutProgress[r];else this.appendsWithoutProgress[r]=u;this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${u} time${u>1?"s":""} without buffered range growth`),d.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:i,parent:e.type,appendsWithoutProgress:u,error:Error(`Fragment append did not increase buffered coverage (${u})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,i,s){let{hls:r,details:n,media:a}=this;if(!a||n===null)return;if(!this.sourceBufferCount)return;let l=r.config,o=a.currentTime,u=n.levelTargetDuration;t=n.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let d=-1/0;if(H(t)&&t>=0){let c=Math.max(t,u);d=Math.floor(o/u)*u-c}if(i){let c=this.getLoopBackBufferFlushEnd(i,s!=null?s:null);if(c>0)d=Math.max(d,c)}if(d>0)this.flushBackBuffer(o,u,d);if(H(e)&&e>0){let c=Math.max(l.maxBufferLength,e),h=Math.max(c,u),g=Math.floor(o/u)*u+h;this.flushFrontBuffer(o,u,g)}}getLoopBackBufferFlushEnd(e,t){var i;let{media:s}=this;if(((i=this.hls)==null?void 0:i.config.loopBackBufferFlush)===!1||!(s!=null&&s.loop)||!t||e.level<=t.level)return 0;let{video:r,audiovideo:n}=e.elementaryStreams;if(r!=null&&r.partial||n!=null&&n.partial)return 0;let a=this.getEarliestElementaryStreamStart(e)-jl;if(a<=0)return 0;return this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${a.toFixed(3)}]`),a}getEarliestElementaryStreamStart(e){let{audio:t,video:i,audiovideo:s}=e.elementaryStreams,r=e.start;if(s)r=Math.min(r,s.startDTS);else{if(t)r=Math.min(r,t.startDTS);if(i)r=Math.min(r,i.startDTS)}return r}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,r])=>{if(r){let o=Z.getBuffered(r);if(o.length>0&&i>o.start(0)){var n,a,l;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:i});let u=this.tracks[s];if((n=this.details)!=null&&n.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(u!=null&&u.ended&&!((a=this.media)!=null&&a.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,r])=>{if(r){let n=Z.getBuffered(r),a=n.length;if(a<2)return;let l=n.start(a-1),o=n.end(a-1);if(i>l||e>=l&&e<=o)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||(i==null?void 0:i.readyState)!=="open")return null;let s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&!!i.setLiveSeekableRange){let o=Math.max(0,t.fragmentStart),u=Math.max(o,s);return{duration:1/0,start:o,end:u}}return{duration:1/0}}let r=(e=this.overrides)==null?void 0:e.duration;if(r){if(!H(r))return null;return{duration:r}}let n=this.media.duration,a=H(i.duration)?i.duration:0;if(s>a&&s>n||!H(n))return{duration:s};return null}updateMediaSource({duration:e,start:t,end:i}){let s=this.mediaSource;if(!s||!this.media||s.readyState!=="open")return;if(s.duration!==e){if(H(e))this.log(`Updating MediaSource duration to ${e.toFixed(3)}`);s.duration=e}if(t!==void 0&&i!==void 0)this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${De(i)}`),this.tracksReady){var s;let r=(s=this.transferData)==null?void 0:s.tracks;if(r&&Object.keys(r).length)this.attachTransferred();else this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(y.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let r in e){let n=r,a=e[n];if(this.isPending(a)){let l=this.getTrackCodec(a,n),o=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${o})${this.currentOp(n)?" Queued":""} ${De(a)}`);try{let u=i.addSourceBuffer(o),d=zi(n),c=[n,u];t[d]=c,a.buffer=u}catch(u){var s;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(n),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[n],this.hls.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:n,mimeType:o,parent:a.id});return}this.trackSourceBuffer(n,a)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){if(!e)return;self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0}getTrackCodec(e,t){let{supplemental:i,codec:s}=e;if(i&&(t==="video"||t==="audiovideo")&&$t(i,"video"))s=ll(s,i);let r=oi(s,e.levelCodec);if(r){if(t.slice(0,5)==="audio")return mi(r,this.appendSource);return r}return""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let s=this.getTrackCodec(t,e);if(this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource)this.addBufferListener(e,"bufferedchange",(r,n)=>{let a=n.removedRanges;if(a!=null&&a.length)this.log(`${r} buffer removed ${cs(a)}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:r,start:a.start(0),end:a.end(a.length-1)})})}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(e){let t=this.currentOp(e);if(!t)return;t.onStart()}onSBUpdateEnd(e){var t,i;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let s=this.currentOp(e);if(!s)return;if(s.onComplete(),(i=this.tracks[e])==null||(i=i.buffer)==null?void 0:i.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var i;let s=(i=this.mediaSource)==null?void 0:i.readyState,r=Error(`${e} SourceBuffer error. MediaSource readyState: ${s}`);this.error(`${r.message}`,t),this.hls.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let n=this.currentOp(e);if(n)n.onError(r)}updateTimestampOffset(e,t,i,s,r,n){let a=t-e.timestampOffset;if(Math.abs(a)>=i)this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t}removeExecutor(e,t,i){let{media:s,mediaSource:r}=this,n=this.tracks[e],a=n==null?void 0:n.buffer;if(!s||!r||!a)throw Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let l=H(s.duration)?s.duration:1/0,o=H(r.duration)?r.duration:1/0,u=Math.max(0,t);if(u>=o){var d;(d=this.currentOp(e))==null||d.onComplete(),this.shiftAndExecuteNext(e);return}let c=Math.min(i,l,o);if(c>u&&(!n.ending||n.ended))n.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),a.remove(u,c);else throw Error(`Cannot remove ${c<=u?`invalid range (${u} >= ${c}) `:""}from the ${e} SourceBuffer${n.ending?" while track ending":""}`)}appendExecutor(e,t){let i=this.tracks[t],s=i==null?void 0:i.buffer;if(!s)throw new Yn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){let r=this.calculateAppendTimeoutTime(s);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,s,r),r)}s.appendBuffer(e)}appendTimeoutHandler(e,t,i){this.log(`Received timeout after ${i}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch(r){this.log(`Failed to abort append on ${e} source buffer after timeout.`)}let s=this.currentOp(e);if(s)s.onError(Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=Dn;if(this.details)t=this.details.levelTargetDuration;let i=2*t*1000;if(this.media===null)return i;let s=Z.bufferInfo(e,this.media.currentTime,0);if(!s.len)return i;return i=Math.max(s.len*1000,i),Math.max(this.hls.config.appendTimeout,i)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((t)=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){if(this.operationQueue)return this.operationQueue.audioBlocking();return!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,r=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map((n)=>this.appendBlocker(n));return Promise.all(r).then((n)=>{if(i!==this.operationQueue)return;e(),this.stepOperationQueue(this.sourceBufferTypes)})}stepOperationQueue(e){e.forEach((t)=>{var i;let s=(i=this.tracks[t])==null?void 0:i.buffer;if(!s||s.updating||t==="audio"&&this.isAudioBlocked())return;this.shiftAndExecuteNext(t)})}append(e,t,i){if(this.operationQueue)this.operationQueue.append(e,t,i)}insertNext(e,t){if(this.operationQueue)this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){if(this.operationQueue)return this.operationQueue.current(e);return null}executeNext(e){if(e&&this.operationQueue)this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){if(this.operationQueue)this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter((e)=>!!e)}addBufferListener(e,t,i){let s=this.tracks[e];if(!s)return;let r=s.buffer;if(!r)return;let n=i.bind(this,e);s.listeners.push({event:t,listener:n}),be(r,t,n)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;if(!i)return;t.listeners.forEach((s)=>{Se(i,s.event,s.listener)}),t.listeners.length=0}};ws=class ws extends Qe{constructor(e){super("content-steering",e.logger);this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;if(!e)return;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.ERROR,this.onError,this)}pathways(){return(this.levels||[]).reduce((e,t)=>{if(e.indexOf(t.pathwayId)===-1)e.push(t.pathwayId);return e},[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1000-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){if(this.started=!1,this.loader)this.loader.destroy(),this.loader=null;this.clearTimeout()}clearTimeout(){if(this.reloadTimer!==-1)self.clearTimeout(this.reloadTimer),this.reloadTimer=-1}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;if(t)this.levels=t.filter((i)=>i!==e)}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;if(i===null)return;if(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started)this.startLoad()}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((i==null?void 0:i.action)===Ee.SendAlternateToPenaltyBox&&i.flags&ye.MoveAllAlternatesMatchingHost){let s=this.levels,r=this._pathwayPriority,n=this.pathwayId;if(t.context){let{groupId:a,pathwayId:l,type:o}=t.context;if(a&&s)n=this.getPathwayForGroupId(a,o,n);else if(l)n=l}if(!(n in this.penalizedPathways))this.penalizedPathways[n]=performance.now();if(!r&&s)r=this.pathways();if(r&&r.length>1){if(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==n,!i.resolved&&(t.details!==R.BUFFER_APPEND_ERROR||t.fatal))this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${s?s.length:s} priorities: ${De(r)} penalized: ${De(this.penalizedPathways)}`)}}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}if(t.length!==e.length)this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`);return t}getLevelsForPathway(e){if(this.levels===null)return[];return this.levels.filter((t)=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach((r)=>{if(s-i[r]>Xl)delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,$n(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});let o=this.hls.levels[a];if(l&&o&&this.levels){if(o.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&o.bitrate!==l.bitrate)this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${o.bitrate}`);this.hls.nextLoadLevel=a}break}}}getPathwayForGroupId(e,t,i){let s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r{let{ID:n,"BASE-ID":a,"URI-REPLACEMENT":l}=r;if(t.some((u)=>u.pathwayId===n))return;let o=this.getLevelsForPathway(a).map((u)=>{let d=new ce(u.attrs);d["PATHWAY-ID"]=n;let c=d.AUDIO&&`${d.AUDIO}_clone_${n}`,h=d.SUBTITLES&&`${d.SUBTITLES}_clone_${n}`;if(c)i[d.AUDIO]=c,d.AUDIO=c;if(h)s[d.SUBTITLES]=h,d.SUBTITLES=h;let g=jn(u.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new _i({attrs:d,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let f=1;f{this.log(`Loaded steering manifest: "${s}"`);let g=u.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;let{"RELOAD-URI":m,"PATHWAY-CLONES":f,"PATHWAY-PRIORITY":v}=g;if(m)try{this.uri=new self.URL(m,s).href}catch(p){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}if(this.scheduleRefresh(this.uri||c.url),f)this.clonePathways(f);let E={steeringManifest:g,url:s.toString()};if(this.hls.trigger(y.STEERING_MANIFEST_LOADED,E),v)this.updatePathwayPriority(v)},onError:(u,d,c,h)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${d.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let g=this.timeToLoad*1000;if(u.code===429){let m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)==="function"){let f=m.getResponseHeader("Retry-After");if(f)g=parseFloat(f)*1000}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,g)},onTimeout:(u,d,c)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,o)}scheduleRefresh(e,t=this.timeToLoad*1000){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1000)},t)}};Qi={exports:{}};Zl=Ql(),qn=nn(Zl);zn=class zn extends Cs{constructor(e,t){super("gap-controller",e.logger);this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;if((i=this.media)!=null&&i.seeking)return;this.waiting=self.performance.now(),this.tick()},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;if(e)e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this)}unregisterListeners(){let{hls:e}=this;if(e)e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this)}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Jl),this.mediaSource=t.mediaSource;let i=this.media=t.media;be(i,"playing",this.onMediaPlaying),be(i,"waiting",this.onMediaWaiting),be(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;if(i)Se(i,"playing",this.onMediaPlaying),Se(i,"waiting",this.onMediaWaiting),Se(i,"ended",this.onMediaEnded),this.media=null;this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;let t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;if(this.media)return Math.max(this.media.currentTime,t);return t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.getCurrentTime();if(this.media.currentTimet)this.nudgeOnVideoHole(e,t)}if(this.waiting===0)this.stallResolved(e);return}if(o||l){if(l)this.stallResolved(e);return}if(u){if(this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls)this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1});return}if(!Z.getBuffered(n).length){this.skipRetry=this.nudgeRetry=0;return}let d=Z.bufferInfo(n,e,0),c=this.fragmentTracker;if(c&&this.hls)Yr(d,e,c,this.hls);let h=d.nextStart||0;if(a&&c&&this.hls){let L=Kr(this.hls.inFlightFragments,e),x=d.len>ui,b=!h||L||h-e>ui&&!c.getPartialFragment(e);if(x||b)return;this.moved=!1}let g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&c){if(!(d.len>0)&&!h)return;let x=Math.max(h,d.start||0)-e,I=g!=null&&g.live?g.targetduration*2:ui,A=Ct(e,c);if(x>0&&(x<=I||A)){if(!n.paused)this._trySkipBufferHole(A);return}}let m=r.detectStallWithCurrentTimeMs,f=self.performance.now(),v=this.waiting,E=this.stalled;if(E===null)if(v>0&&f-v=m||v&&this.moved)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return;if(n.currentTime!==e){let L=e;e=n.currentTime,this.moved=!0,this.log(`currentTime changed ${L} > ${e}`);return}}let T=Z.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(T,p,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls){if(this.stalled=null,this.stallReported){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}}nudgeOnVideoHole(e,t){var i;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){let r=Z.bufferedInfo(Z.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){let n=Z.timeRangesToArray(s),a=Z.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&aa)&&u-o<1&&e-o<2){let d=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${o} -> ${u} buffered index: ${l}`);this.warn(d.message),this.media.currentTime+=0.000001;let c=Ct(e,this.fragmentTracker);if(c&&"fragment"in c)c=c.fragment;else if(!c)c=void 0;let h=Z.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:c,buffer:h.len,bufferInfo:h})}}}}}_tryFixBufferStall(e,t,i){var s,r;let{fragmentTracker:n,media:a}=this,l=(s=this.hls)==null?void 0:s.config;if(!a||!n||!l)return;let o=(r=this.hls)==null?void 0:r.latestLevelDetails,u=Ct(i,n);if(u||o!=null&&o.live&&i1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-il.highBufferWatchdogPeriod*1000||this.waiting))this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e)}adjacentTraversal(e,t){let i=this.fragmentTracker,s=e.nextStart;if(i&&s){let r=i.getFragAtPos(t,J.MAIN),n=i.getFragAtPos(s,J.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&r!==null&&i&&t){this.stallReported=!0;let n=Error(`Playback stalling at @${i.currentTime} due to low buffer (${De(e)})`);this.warn(n.message),t.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:i,hls:s}=this,r=s==null?void 0:s.config;if(!i||!t||!r)return 0;let n=i.currentTime,a=Z.bufferInfo(i,n,0);Yr(a,n,t,s);let l=n0&&a.len<1&&i.readyState<3,c=l-n;if(c>0&&(u||d)){if(c>r.maxBufferHole){let v=!1;if(n===0){let E=t.getAppendedFrag(0,J.MAIN);if(E&&l0)S+=L;else{p=!0;break}}if(p)return 0}}let{nudgeMaxRetry:h,skipBufferHolePadding:g}=r,m=++this.skipRetry>h,f=Math.max(l,n)+g;if(!m)this.warn(`skipping hole, adjusting currentTime from ${n} to ${f}`),this.moved=!0,i.currentTime=f;if(!(e!=null&&e.gap)||m){let v=Error(m?`Playhead still not moving after seeking over buffer hole from ${n} to ${f} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${n} to ${f}`),E={type:Q.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:m,error:v,reason:v.message,buffer:a.len,bufferInfo:a};if(e)if("fragment"in e)E.part=e;else E.frag=e;s.trigger(y.ERROR,E)}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:s}=this,r=t==null?void 0:t.config;if(!i||!r)return 0;let n=i.currentTime;if(this.nudgeRetry++,s{let e=fs();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();Lt={};mu=[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],pu=[44100,48000,32000,22050,24000,16000,11025,12000,8000],vu=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],yu=[0,1,1,4];oa=class oa extends Ms{constructor(e,t){super();this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:90000,dropped:0}}static probe(e,t){if(!e)return!1;let i=hi(e,0),s=(i==null?void 0:i.length)||0;if(aa(e,s))return!1;for(let r=e.length;s{r.decryptAacSamples(s.audioTrack.samples,0,()=>{n(s)})})}};la=class la extends Ms{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:90000,dropped:0}}static probe(e){if(!e)return!1;let t=hi(e,0),i=(t==null?void 0:t.length)||0;if(t&&e[i]===11&&e[i+1]===119&&mn(t)!==void 0&&Su(e,i)<=16)return!1;for(let s=e.length;i{var c,h;switch(d.type){case 1:{if(n)break;let v=!1;o=!0;let E=d.data;if(u&&E.length>4){let p=this.readSliceType(E);if(p===2||p===4||p===7||p===9)v=!0}if(v){var g;if((g=l)!=null&&g.frame&&!l.key)this.pushAccessUnit(l,e),l=this.VideoSample=null}if(!l)l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts);l.frame=!0,l.key=v;break}case 5:if(o=!0,(c=l)!=null&&c.frame&&!l.key)this.pushAccessUnit(l,e),l=this.VideoSample=null;if(!l)l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts);l.key=!0,l.frame=!0;break;case 6:{if(n)break;o=!0,fi(d.data,1,i.pts,t.samples);break}case 7:{var m,f;o=!0,u=!0;let v=d.data,E=this.readSPS(v);if(!e.sps||e.width!==E.width||e.height!==E.height||((m=e.pixelRatio)==null?void 0:m[0])!==E.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[v];let p=v.subarray(1,4),S="avc1.";for(let T=0;T<3;T++){let L=p[T].toString(16);if(L.length<2)L="0"+L;S+=L}e.codec=S}break}case 8:o=!0,e.pps=[d.data];break;case 9:if(o=!0,e.audFound=!0,(h=l)!=null&&h.frame)this.pushAccessUnit(l,e),l=null;if(!l)l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts);break;case 12:o=!0;break;default:o=!1;break}if(l&&o)l.units.push(d)}),s&&l)this.pushAccessUnit(l,e),this.VideoSample=null}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new gs(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8,r;for(let n=0;n ${e?Xr(e):e}`);this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e[0].pts,s=e.reduce((r,n)=>{let a=n.pts,l=a-r;if(l<-4294967296)t=!0,a=$e(a,i),l=a-r;if(l>0)return r;return a},i);if(t)this.debug("PTS rollover detected");return s}remux(e,t,i,s,r,n,a,l,o){let u,d,c,h,g,m,f=r,v=r,p=!o.iframe&&e.pid>-1,S=t.pid>-1,T=t.samples.length,L=e.samples.length>0,x=a&&T>0||T>1;if((!p||L)&&(!S||x)||this.ISGenerated||a){if(this.ISGenerated){var I,A,_,P;let C=this.videoTrackConfig;if(C&&(t.width!==C.width||t.height!==C.height||((I=t.pixelRatio)==null?void 0:I[0])!==((A=C.pixelRatio)==null?void 0:A[0])||((_=t.pixelRatio)==null?void 0:_[1])!==((P=C.pixelRatio)==null?void 0:P[1]))||!C&&x||this.nextAudioTs===null&&L)this.resetInitSegment()}if(!this.ISGenerated)c=this.generateIS(e,t,r,n);let w=this.isVideoContiguous,Y=-1,O;if(x){if(Y=$u(t.samples),!w&&this.config.forceKeyFrameOnDiscontinuity){if(m=!0,Y>0){this.warn(`Dropped ${Y} out of ${T} video samples due to a missing keyframe`);let C=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(Y),t.dropped+=Y,v+=(t.samples[0].pts-C)/t.inputTimeScale,O=v}else if(Y===-1)this.warn(`No keyframe found out of ${T} video samples`),m=!1}}if(this.ISGenerated){if(L&&x&&r){let C=this.getVideoStartPts(t.samples),G=($e(e.samples[0].pts,C)-C)/t.inputTimeScale;f+=Math.max(0,G),v+=Math.max(0,-G)}if(L){if(!e.samplerate)this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n);if(d=this.remuxAudio(e,f,this.isAudioContiguous,n,S||x||l===J.AUDIO?v:void 0,o),x){let C=d?d.endPTS-d.startPTS:0;if(!t.inputTimeScale)this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n);u=this.remuxVideo(t,v,w,C,o)}}else if(x)u=this.remuxVideo(t,v,w,0,o);if(u)u.firstKeyFrame=Y,u.independent=Y!==-1,u.firstKeyFramePTS=O}}if(this.ISGenerated&&this._initPTS&&this._initDTS){if(i.samples.length)g=ga(i,r,this._initPTS,this._initDTS);if(s.samples.length)h=ma(s,r,this._initPTS)}return{audio:d,video:u,initSegment:c,independent:m,text:h,id3:g}}computeInitPts(e,t,i,s){let r=Math.round(i*t),n=$e(e,r);if(n0?F-1:F].dts)p=!0}if(p)a.sort(function(F,M){let q=F.dts-M.dts,X=F.pts-M.pts;return q||X});m=a[0].dts,f=a[a.length-1].dts;let T=f-m,L=T?Math.round(T/(o-1)):g||e.inputTimeScale/30;if(i){let F=m-S,M=F>L,q=F<-1;if(M||q){if(M)this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Dt(F,!0)} ms (${F}dts) hole between fragments detected at ${t.toFixed(3)}`);else this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Dt(-F,!0)} ms (${F}dts) overlapping between fragments detected at ${t.toFixed(3)}`);if(!q||S>=a[0].pts||Pt()){m=S;let X=a[0].pts-F;if(M)a[0].dts=m,a[0].pts=X;else{let z=!0;for(let j=0;jX&&z)break;let oe=a[j].pts;if(a[j].dts-=F,a[j].pts-=F,j0?M.dts-a[F-1].dts:L;if(z=F>0?M.pts-a[F-1].pts:L,oe.stretchShortVideoTrack&&this.nextAudioTs!==null){let te=Math.floor(oe.maxBufferHole*n),re=(s?v+s*n:this.nextAudioTs+d)-M.pts;if(re>te){if(g=re-de,g<0)g=de;else P=!0;this.log(`It is approximately ${re/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)}else g=de}else g=de}let j=Math.round(M.pts-M.dts);if(w=Math.min(w,g),O=Math.max(O,g),Y=Math.min(Y,z),C=Math.max(C,z),!i&&F===0&&j>g){let oe=Math.round(j/L)*L;if(oe-j===1)this.log(`pad first CTS ${j} -> ${oe} of sn: ${r.sn}`),j=oe}l.push(Qr(M.key,g,X,j))}if(l.length){let F=Pt();if(F){if(F<70){let M=l[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(il()){if(C-Y0&&(s&&Math.abs(S-(E+p))<9000||Math.abs($e(f[0].pts,S)-(E+p))<20*d),f.forEach(function(k){k.pts=$e(k.pts,S)}),!i||E<0){let k=f.length;if(f=f.filter((G)=>G.pts>=0),k!==f.length)this.warn(`Removed ${f.length-k} of ${k} samples (initPTS ${p} / ${a})`);if(!f.length)return;if(r===0)E=0;else if(s&&!m)E=Math.max(0,S-p);else E=f[0].pts-p}if(e.segmentCodec==="aac"){let k=this.config.maxAudioFramesDrift;for(let G=0,D=E+p;G=k*d&&q0){b+=v;try{x=new Uint8Array(b)}catch(q){this.observer.emit(y.ERROR,y.ERROR,{type:Q.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:q,bytes:b,reason:`fail allocating audio mdat ${b}`});return}if(!h)mt(x,0,b),mt(x,4,ee.mdat)}else return}if(x)x.set(U,v);let M=U.byteLength;v+=M,g.push(Qr(!0,u,M,0)),L=F}let A=g.length;if(!A)return;let _=g[g.length-1];E=L-p,this.nextAudioTs=E+o*_.duration;let P=h?new Uint8Array(0):V.moof(e.sequenceNumber++,T/o,Te({},e,{samples:g}));e.samples=[];let w=(T-p)/a,Y=this.nextAudioTs/a,C={data1:P,data2:x,startPTS:w,endPTS:Y,startDTS:w,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,C}};pa=class pa extends Qe{constructor(e,t,i,s){super("passthrough-remuxer",s);this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){if(this.observer)this.observer.removeAllListeners();this.observer=null}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;if(t&&e){if(t.baseTime===e.baseTime&&t.timescale===e.timescale)return}this.initPTS=e}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.decryptdata=s,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,i){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=i||Sn(e);if(t)Yo(e,t);else{let o=n||a;if(o!=null&&o.encrypted)this.warn(`Init segment with encrypted track with has no key ("${o.codec}")!`)}if(n)s=Zr(n,he.AUDIO,this);if(a)r=Zr(a,he.VIDEO,this);let l={};if(n&&a)l.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"};else if(n)l.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:e,id:"audio"};else if(a)l.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"};else this.warn("initSegment does not contain moov or trak boxes.");this.initTracks=l}remux(e,t,i,s,r,n,a,l,o,u,d){var c,h;let{initPTS:g,lastEndTime:m}=this,f={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};if(!H(m))m=this.lastEndTime=r||0;let v=t.samples;if(!v.length)return f;let E=this.pendingInitSegment;if(E)this.pendingInitSegment=void 0,this.generateInitSegment(E,this.decryptdata,u);let p={initPTS:void 0,timescale:void 0,trackId:void 0},S=this.initData;if(!((c=S)!=null&&c.length))this.generateInitSegment(v),S=this.initData;if(!((h=S)!=null&&h.length))return this.warn("Failed to generate initSegment."),f;if(this.emitInitSegment)p.tracks=this.initTracks,f.initSegment=p,this.emitInitSegment=!1;let T=!1,L=d&&!T?d.tracks:Qo(v,S,o,this,T),x=S.audio?L[S.audio.id]:null,b=S.video?L[S.video.id]:null,I=!!S.audio,A=!!S.video,_="";if(I)_+="audio";if(A)_+="video";let P=ri(b,1/0),w=ri(x,1/0),Y=ri(b,0,!0),O=ri(x,0,!0),C=r,k=0;if(b&&x&&S.audio&&(w>Y||P>O))this.warn(`audio and video track sample timestamps do not overlap. v: ${P}-${Y} a: ${w}-${O}}`,b,x);let G=!!x&&(!b||!g&&w=0&&Math.abs(1-Be)<0.001,this.log(`${le} timestamps in track ${X} at playlist time: ${n?"":"~"}${r} maps to ${C} with initPTS: ${g.baseTime/g.timescale} (${q/M-g.baseTime/g.timescale}s diff) (${_}) drift estimate: ${Be} ${me?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}if(!me)this.log(`Found initPTS in ${le} track ${X} at playlist time: ${r} offset: ${C-r} (${q}/${M})`),g=null,p.initPTS=q,p.timescale=M,p.trackId=X}if(!g){if(!p.timescale||p.trackId===void 0||p.initPTS===void 0)this.warn("Could not set initPTS"),p.initPTS=C,p.timescale=1,p.trackId=-1;this.initPTS=g={baseTime:p.initPTS,timescale:p.timescale,trackId:p.trackId}}else p.initPTS=g.baseTime,p.timescale=g.timescale,p.trackId=g.trackId;let z=C-g.baseTime/g.timescale,j=z+k,oe=A&&(D==null?void 0:D.ptsMin)!==void 0?D.ptsMin/D.timescale-g.baseTime/g.timescale:z,de=A&&D!=null&&D.ptsMax?D.ptsMax/D.timescale-g.baseTime/g.timescale:j;if(k>0)this.lastEndTime=j;else this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp();let te=(S.audio?S.audio.encrypted:!1)||(S.video?S.video.encrypted:!1),re={data1:U,data2:F,startPTS:oe,startDTS:z,endPTS:de,endDTS:j,type:_,hasAudio:I,hasVideo:A,nb:1,dropped:0,encrypted:te};f.audio=I&&!A?re:void 0,f.video=A?re:void 0;let Le=this.isVideoContiguous,Ne=b==null?void 0:b.sampleCount;if(Ne){let me=b.keyFrameIndex,le=me!==-1;if(re.nb=Ne,re.dropped=me===0||Le?0:le?me:Ne,re.independent=le,re.firstKeyFrame=me,le&&b.keyFrameStart)re.firstKeyFramePTS=(b.keyFrameStart-g.baseTime)/g.timescale;if(!Le)f.independent=le;if(this.isVideoContiguous||(this.isVideoContiguous=le),re.dropped)this.warn(`fmp4 does not start with IDR: firstIDR ${me}/${Ne} dropped: ${re.dropped} start: ${re.firstKeyFramePTS||"NA"}`)}if(f.initSegment=p,f.id3=ga(i,r,g,g),s.samples.length)f.text=ma(s,r,g);return f}};try{at=self.performance.now.bind(self.performance)}catch(e){at=Date.now}ts=[{demux:ua,remux:pa},{demux:et,remux:di},{demux:oa,remux:di},{demux:la,remux:di}];je={DISABLED:0,SWITCHING:1,SWITCHED:2};xa=class xa extends ks{constructor(e,t,i){super(e,t,i,"stream-controller",J.MAIN);this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=je.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let s=this.media,r=s?s.currentTime:null;if(r===null||!H(r))return;if(this.log(`Media seeked to ${r}`),!this.getBufferedFrag(r))return;let n=this.getFwdBufferInfoAtPos(s,r,J.MAIN,0);if(!n||n.len===0){this.log(`Main buffer empty at ${r} on "seeked" event: ${n?n.len:n}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(Vu),this.level=-1,!this.startFragRequested){let r=s.startLevel;if(r===-1)if(s.config.testBandwidth&&this.levels.length>1)r=0,this.bitrateTest=!0;else r=s.firstAutoLevel;s.nextLoadLevel=r,this.level=s.loadLevel,this._hasEnoughToStart=!!t}if(i>0&&e===-1&&!t&&this.initPTS.length)this.log(`Override startPosition with lastCurrentTime @${i}`),e=i;if(this.state=B.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType))this._hasEnoughToStart=this.startFragRequested=!1;this.tick()}else this._forceStartLoad=!0,this.state=B.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case B.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e==null?void 0:e[t],s=i==null?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=B.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=B.IDLE;break}break}case B.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}if(this.state===B.IDLE)this.doTickIdle();this.onTickEnd()}onTickEnd(){var e;if(super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1)this.lastCurrentTime=this.media.currentTime;this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;let r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[r]))return;let n=i[r],a=this.getMainFwdBufferInfo();if(a===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){let m={type:this.targetBufferType()};this.hls.trigger(y.BUFFER_EOS,m),this.state=B.ENDED;return}if(!this.buffering)return;if(e.loadLevel!==r&&e.manualLevel===-1)this.log(`Adapting to level ${r} from level ${this.level}`);this.level=e.nextLoadLevel=r;let o=n.details;if(!o||this.state===B.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=B.WAITING_LEVEL,this.startFragRequested=!1;return}let u=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(u>=d)return;if(this.backtrackFragment&&this.backtrackFragment.start>a.end)this.backtrackFragment=void 0;let c=this.backtrackFragment?this.backtrackFragment.start:a.end,h=this.getNextFragment(c,o);if(this.couldBacktrack&&!this.fragPrevious&&h&&Fe(h)&&this.fragmentTracker.getState(h)!==Ae.OK){var g;let f=((g=this.backtrackFragment)!=null?g:h).sn-o.startSN,v=o.fragments[f-1];if(v&&h.cc===v.cc)h=v,this.fragmentTracker.removeFragment(v)}else if(this.backtrackFragment&&a.len)this.backtrackFragment=void 0;if(h&&this.isLoopLoading(h,c)){if(!h.gap){let f=this.audioOnly&&!this.altAudio?he.AUDIO:he.VIDEO,v=(f===he.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;if(v)this.afterBufferFlushed(v,f)}h=this.getNextFragmentLoopLoading(h,o,a,J.MAIN,d)}if(!h)return;if(this.exceedsMaxBuffer(a,d,h))return;this.loadFragment(h,n,c)}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);if(s===Ae.NOT_LOADED||s===Ae.PARTIAL)if(this.bitrateTest)this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t);else super.loadFragment(e,t,i);else this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==je.DISABLED){var e;if((((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime)super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){if(this.mediaBuffer&&this.altAudio===je.SWITCHED)return this.mediaBuffer;return this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let i=this.fragPlaying;if(i){let s=i.level;if(this.hls.trigger(y.FRAG_CHANGED,{frag:i,previousFrag:e}),(e==null?void 0:e.level)!==s)this.hls.trigger(y.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===je.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;be(i,"playing",this.onMediaPlaying),be(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;if(i)Se(i,"playing",this.onMediaPlaying),Se(i,"seeked",this.onMediaSeeked);if(this.videoBuffer=null,super.onMediaDetaching(e,t),!!t.transferMedia)return;this._hasEnoughToStart=!1}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=je.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let r=0;r{if(g>=a.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let s=this.hls.liveSyncPosition,r=this.playhead,n=e.fragmentStart,a=e.edge,l=r>=n-t.maxFragLookUpTolerance&&r<=a;if(s!==null&&i.duration>s&&(r{if(!this.hls)return;this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),i.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(y.AUDIO_TRACK_SWITCHED,t)}else this.altAudio=je.SWITCHING}onAudioTrackSwitched(e,t){let i=gr(t.url,this.hls);if(i){let s=this.videoBuffer;if(s&&this.mediaBuffer!==s)this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s}this.altAudio=i?je.SWITCHED:je.DISABLED,this.tick()}onBufferCreated(e,t){let i=t.tracks,s,r,n=!1;for(let a in i){let l=i[a];if(l.id==="main"){if(r=a,s=l,a==="video"){let o=i[a];if(o)this.videoBuffer=o.buffer}}else n=!0}if(n&&s)this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer;else this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:s}=t,r=i.type===J.MAIN;if(r){if(this.fragContextChanged(i)){if(this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===B.PARSED)this.state=B.IDLE;return}let l=!1;if(Fe(i))l=!!i.gap&&!i.tagList.some((o)=>o[0]==="GAP");if(this.fragBufferedComplete(i,s),l){var n;i.stats.retry++;let o=(n=this.levels)==null?void 0:n[i.level];if(o)o.fragmentError++}}let a=this.media;if(!a)return;if(!this._hasEnoughToStart&&Z.getBuffered(a).length)this._hasEnoughToStart=!0,this.seekToStartPos();if(r)this.tick()}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=B.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:if(!t.levelRetry&&this.state===B.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===se.LEVEL)this.state=B.IDLE;break;case R.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;if(t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry)this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;if(this.reduceLengthAndFlushBuffer(t))this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;if(this.reduceLengthAndFlushBuffer(t))if(!this.config.interstitialsController&&this.config.assetPlayerId)this._hasEnoughToStart=!0;else this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){if(this.state=B.IDLE,!this._hasEnoughToStart)this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime;this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==he.AUDIO||!this.altAudio){let i=(t===he.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;if(i)this.afterBufferFlushed(i,t),this.tick()}}onLevelsUpdated(e,t){if(this.level>-1&&this.fragCurrent){if(this.level=this.fragCurrent.level,this.level===-1)this.resetWhenMissingContext(this.fragCurrent)}this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t0&&(l{let{hls:s}=this,r=i==null?void 0:i.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=B.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(y.FRAG_LOADED,i),r.bitrateTest=!1}).catch((i)=>{if(this.state===B.STOPPED||this.state===B.ERROR)return;this.warn(i),this.resetFragmentLoading(e)})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}let{frag:a,part:l,level:o}=n,{video:u,text:d,id3:c,initSegment:h}=s,{details:g}=o,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=B.PARSING,h){let f=h.tracks;if(f){let S=a.initSegment||a;if(this.unhandledEncryptionError(h,a))return;this._bufferInitSegment(o,f,S,r),i.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:f})}let{initPTS:v,timescale:E}=h,p=this.initPTS[a.cc];if(H(v)&&(!p||p.baseTime!==v||p.timescale!==E)){let S=h.trackId;this.initPTS[a.cc]={baseTime:v,timescale:E,trackId:S};let T=this.initPTS.slice(0);i.trigger(y.INIT_PTS_FOUND,{timestampOffsets:T,frag:a,id:t,initPTS:v,timescale:E,trackId:S})}}if(u&&g){if(m&&u.type==="audiovideo")this.logMuxedErr(a);let f=g.fragments[a.sn-1-g.startSN],v=a.sn===g.startSN,E=!f||a.cc>f.cc;if(s.independent!==!1){let{startPTS:p,endPTS:S,startDTS:T,endDTS:L}=u;if(l)l.elementaryStreams[u.type]={startPTS:p,endPTS:S,startDTS:T,endDTS:L};else{if(u.firstKeyFrame&&u.independent&&r.id===1&&!E)this.couldBacktrack=!0;if(u.dropped&&u.independent){let x=this.getMainFwdBufferInfo(),b=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:p;if(!v&&bui)a.gap=!0}if(a.setElementaryStreamInfo(u.type,p,S,T,L),this.backtrackFragment)this.backtrackFragment=a;this.bufferFragmentData(u,a,l,r,v||E)}else if(v||E)a.gap=!0;else{this.backtrack(a);return}}if(m){let{startPTS:f,endPTS:v,startDTS:E,endDTS:p}=m;if(l)l.elementaryStreams[he.AUDIO]={startPTS:f,endPTS:v,startDTS:E,endDTS:p};a.setElementaryStreamInfo(he.AUDIO,f,v,E,p),this.bufferFragmentData(m,a,l,r)}if(g&&c!=null&&c.samples.length){let f={id:t,frag:a,details:g,samples:c.samples};i.trigger(y.FRAG_PARSING_METADATA,f)}if(g&&d){let f={id:t,frag:a,details:g,samples:d.samples};i.trigger(y.FRAG_PARSING_USERDATA,f)}}logMuxedErr(e){this.warn(`${Fe(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==B.PARSING)return;if(this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly){if(delete t.audio,t.audiovideo)this.logMuxedErr(i)}let{audio:r,video:n,audiovideo:a}=t;if(r){let o=e.audioCodec,u=oi(r.codec,o);if(u==="mp4a")u="mp4a.40.5";if(this.audioCodecSwitch){if(u)if(u.indexOf("mp4a.40.5")!==-1)u="mp4a.40.2";else u="mp4a.40.5";let d=r.metadata;if(d&&"channelCount"in d&&(d.channelCount||1)!==1&&!sl())u="mp4a.40.5"}if(u&&u.indexOf("mp4a.40.5")!==-1&&nl()&&r.container!=="audio/mpeg")u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`);if(o&&o!==u)this.log(`Swapping manifest audio codec "${o}" for "${u}"`);r.levelCodec=u,r.id=J.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${u||""}/${o||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=J.MAIN;let o=n.codec;if((o==null?void 0:o.length)===4)switch(o){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${o}]${n.codec!==o?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}if(a){if(this.iframesOnly)this.logMuxedErr(i);this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio}let l=Object.keys(t);if(l.length){if(this.hls.trigger(y.BUFFER_CODECS,t),!this.hls)return;l.forEach((o)=>{let d=t[o].initSegment;if(d!=null&&d.byteLength)this.hls.trigger(y.BUFFER_APPENDING,{type:o,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,J.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e==null?void 0:e[t];if(!i)return this.config.maxBufferLength;return this.getMaxBufferLength(i.maxBitrate)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=B.IDLE}get nextLevel(){let e=this.nextBufferedFrag;if(e)return e.level;return-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(H(t))return this.getAppendedFrag(t);return null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(H(t)){let i=this.getLevelDetails(),s=this.currentFrag||(i?Rs(null,i.fragments,t):null);if(s){let r=s.programDateTime;if(r!==null){let n=r+(t-s.start)*1000;return new Date(n)}}}return null}get currentLevel(){let e=this.currentFrag;if(e)return e.level;return-1}get nextBufferedFrag(){let e=this.currentFrag;if(e)return this.followingBufferedFrag(e);return null}get forceStartLoad(){return this._forceStartLoad}};Ku=/(\d+)-(\d+)\/(\d+)/;Li=class Li extends wi{constructor(e){super();this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||qu}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){if(self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end)this.stats.aborted=!0,this.controller.abort()}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:e,context:t,stats:i}=this;if(!e||!t)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;let s=Wu(t,this.controller.signal),r=t.responseType==="arraybuffer",n=r?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=a&&H(a)?a:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(Ut(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((u)=>{var d;this.response=u;let c=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(c-i.loading.start)),!u.ok){let{status:g,statusText:m}=u;throw new ba(m||"fetch, bad network response",g,u)}i.loading.first=c,i.total=ju(u.headers)||i.total;let h=(d=this.callbacks)==null?void 0:d.onProgress;if(h&&H(e.highWaterMark))return this.loadProgressively(u,i,t,e.highWaterMark,h);if(r)return u.arrayBuffer();if(t.responseType==="json")return u.json();return u.text()}).then((u)=>{var d,c;let h=this.response;if(!h)throw Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);let g=u[n];if(g)i.loaded=i.total=g;let m={url:h.url,data:u,code:h.status},f=(d=this.callbacks)==null?void 0:d.onProgress;if(f&&!H(e.highWaterMark))f(i,t,u,h);(c=this.callbacks)==null||c.onSuccess(m,i,t,h)}).catch((u)=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;let d=!u?0:u.code||0,c=!u?null:u.message,h=e.loadPolicy.errorRetry,g=i.retry,m={url:t.url,data:void 0,code:d};if(Mt(h,g,!1,m))this.retry(h);else{var f;ae.error(`${d} while loading ${t.url}`),(f=this.callbacks)==null||f.onError({code:d,text:c},t,u?u.details:null,i)}})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,r){let n=new La,a=e.body.getReader(),l=()=>a.read().then((o)=>{if(o.done){if(n.dataLength)r(t,i,n.flush().buffer,e);return Promise.resolve(new ArrayBuffer(0))}let u=o.value,d=u.length;if(t.loaded+=d,d=s)r(t,i,n.flush().buffer,e)}else r(t,i,u.buffer,e);return l()}).catch(()=>Promise.reject());return l()}};ba=class ba extends Error{constructor(e,t,i){super(e);this.code=void 0,this.details=void 0,this.code=t,this.details=i}};Xu=/^age:\s*[\d.]+\s*$/im;Oi=class Oi extends wi{constructor(e){super();this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let e=this.loader;if(self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e){if(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4)this.stats.aborted=!0,e.abort()}}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let r=this.xhrSetup;if(r)Promise.resolve().then(()=>{if(this.loader!==i||this.stats.aborted)return;return r.call(this,i,t.url,t)}).catch((n)=>{if(this.loader!==i||this.stats.aborted)return;return i.open("GET",t.url,!0),r.call(this,i,t.url,t)}).then(()=>{if(this.loader!==i||this.stats.aborted)return;this.openAndSendXhr(i,t,e)}).catch((n)=>{var a;(a=this.callbacks)==null||a.onError({code:i.status,text:n.message},t,i,s);return});else this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){if(!e.readyState)e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(let a in s)e.setRequestHeader(a,s[a]);if(t.rangeEnd)e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`);e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&H(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let s=t.readyState,r=this.config;if(i.aborted)return;if(s>=2){if(i.loading.first===0){if(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs)self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start))}if(s===4){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let o=t.status,u=t.responseType==="text"?t.responseText:null;if(o>=200&&o<300){let g=u!=null?u:t.response;if(g!=null){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);let m=t.responseType==="arraybuffer"?g.byteLength:g.length;i.loaded=i.total=m,i.bwEstimate=i.total*8000/(i.loading.end-i.loading.first);let f=(n=this.callbacks)==null?void 0:n.onProgress;if(f)f(i,e,g,t);let v={url:t.responseURL,data:g,code:o};if(e.rangeEnd&&m!==e.rangeEnd-e.rangeStart)ae.warn(`Payload length ${m} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`);(a=this.callbacks)==null||a.onSuccess(v,i,e,t);return}}let d=r.loadPolicy.errorRetry,c=i.retry,h={url:e.url,data:void 0,code:o};if(Mt(d,c,!1,h))this.retry(d);else{var l;ae.error(`${o} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:o,text:t.statusText},e,t,i)}}}}loadprogress(e){let t=this.stats;if(t.loaded=e.loaded,e.lengthComputable)t.total=e.total}getCacheAge(){let e=null;if(this.loader&&Xu.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){if(this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders()))return this.loader.getResponseHeader(e);return null}};en={maxTimeToFirstByteMs:8000,maxLoadTimeMs:20000,timeoutRetry:null,errorRetry:null},Qu=Me(Me({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:0.25,maxBufferSize:60000000,maxFragLookUpTolerance:0.25,maxBufferHole:0.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:0.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:0.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5000,fpsDroppedMonitoringThreshold:0.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Oi,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:500000,abrEwmaDefaultEstimateMax:5000000,abrBandWidthFactor:0.95,abrBandWidthUpFactor:0.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!1,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:en},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8000,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:20000,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1000,maxRetryDelayMs:20000,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:8000}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1000,maxRetryDelayMs:8000}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:120000,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1000,maxRetryDelayMs:8000}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:8000}}},interstitialAssetListLoadPolicy:{default:en},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1000,manifestLoadingMaxRetryTimeout:64000,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1000,levelLoadingMaxRetryTimeout:64000,fragLoadingTimeOut:20000,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1000,fragLoadingMaxRetryTimeout:64000,streamController:xa,abrController:bs,bufferController:Ps,capLevelController:Pi,errorController:Is,fpsController:Os,id3TrackController:Xn,gapController:zn,latencyController:Qn},Zu()),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:ws,iframeController:void 0,interstitialsController:void 0});Ra=class Ra extends Ds{constructor(e,t){super(e,"level-controller");this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t)=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,s=[],r={},n={},a=!1,l=!1,o=!1,u=!1;t.levels.forEach((d)=>{let c=d.attrs,h=tn(d,i),{audioCodec:g,videoCodec:m,imageCodec:f,width:v,height:E}=d;if(!h){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}a||(a=!!(v&&E)),l||(l=!!m),o||(o=!!g),u||(u=!!f);let{CODECS:p,"FRAME-RATE":S,"HDCP-LEVEL":T,"PATHWAY-ID":L,RESOLUTION:x,"VIDEO-RANGE":b}=c,A=`${`${L||"."}-`}${d.bitrate}-${x}-${S}-${p}-${b}-${T}`;if(!r[A]){let _=this.createLevel(d);r[A]=_,n[A]=1,s.push(_)}else if(r[A].uri!==d.url&&!d.attrs["PATHWAY-ID"]){let _=n[A]+=1;d.attrs["PATHWAY-ID"]=Array(_+1).join(".");let P=this.createLevel(d);r[A]=P,s.push(P)}else if(!d.iframes)r[A].addGroupId("audio",c.AUDIO),r[A].addGroupId("text",c.SUBTITLES)}),this.filterAndSortMediaOptions(s,t,a,l,o,u)}createLevel(e){let t=new _i(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!_a(i.videoCodec,this.hls.config.preferManagedMediaSource)){let s=Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=st.getUnsupportedResult(s,[])}return t}filterAndSortMediaOptions(e,t,i,s,r,n){var a;let l=[],o=[],u=e,d=((a=t.stats)==null?void 0:a.parsing)||{},c=this.hls.config.preferManagedMediaSource;if((i||s)&&r)u=u.filter(({videoCodec:T,videoRange:L,width:x,height:b})=>(!!T||!!(x&&b))&&hl(L));if(s&&n)u=u.filter((T)=>!T.imageCodec);if(u.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",L=T;if(t.levels.length)L=`one or more CODECS in variant not supported: ${De(t.levels.map((b)=>b.attrs.CODECS).filter((b,I,A)=>A.indexOf(b)===I))}`,this.warn(L),T+=` (${L})`;let x=Error(T);this.hls.trigger(y.ERROR,{type:Q.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:x,reason:L})}}),d.end=performance.now();return}if(t.audioTracks)l=t.audioTracks.filter((T)=>!T.audioCodec||Ia(T.audioCodec,c)),sn(l);if(t.subtitles)o=t.subtitles,sn(o);let h=u.slice(0);u.sort((T,L)=>{if(T.attrs["HDCP-LEVEL"]!==L.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(L.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&T.height!==L.height)return T.height-L.height;if(T.frameRate!==L.frameRate)return T.frameRate-L.frameRate;if(T.videoRange!==L.videoRange)return pi.indexOf(T.videoRange)-pi.indexOf(L.videoRange);if(T.videoCodec!==L.videoCodec){let x=ur(T.videoCodec),b=ur(L.videoCodec);if(x!==b)return b-x}if(T.uri===L.uri&&T.codecSet!==L.codecSet){let x=gi(T.codecSet),b=gi(L.codecSet);if(x!==b)return b-x}if(T.averageBitrate!==L.averageBitrate)return T.averageBitrate-L.averageBitrate;return 0});let g=h[0];if(this.steering){if(u=this.steering.filterParsedLevels(u),u.length!==h.length){for(let T=0;Tx&&x===this.hls.abrEwmaDefaultEstimate)this.hls.bandwidthEstimate=b}break}let f=t.iframeVariants.filter((T)=>tn(T,c));this._iframeVariants=f;let v=r&&!s,E=this.hls.config,p=!!(E.audioStreamController&&E.audioTrackController),S={levels:u,audioTracks:l,subtitleTracks:o,iframeVariants:f,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:p&&!v&&l.some((T)=>!!T.url)};d.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,S)}get iframeVariants(){if(this._iframeVariants.length===0)return null;return this._iframeVariants}get levels(){if(this._levels.length===0)return null;return this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let u=Error("invalid level idx"),d=e<0;if(this.hls.trigger(y.ERROR,{type:Q.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:u,reason:u.message}),d)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&s&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);let l={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);let o=n.details;if(!o||o.live){let u=this.switchParams(n.uri,s==null?void 0:s.details,o);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){if(this.manualLevelIndex=e,this._startLevel===void 0)this._startLevel=e;if(e!==-1)this.level=e}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;if(e!==void 0)return e;return this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){if(this.steering)return this.steering.pathways();return[]}get pathwayPriority(){if(this.steering)return this.steering.pathwayPriority;return null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter((s)=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){if(t.fatal||!t.context)return;if(t.context.type===se.LEVEL&&t.context.level===this.level)this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===J.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some((r)=>!!i[r]))return;let s=this._levels[t.level];if(s!=null&&s.loadError)this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0}}onLevelLoaded(e,t){var i;let{level:s,details:r}=t,n=t.levelInfo;if(!n){var a;if(this.warn(`Invalid level index ${s}`),(a=t.deliveryDirectives)!=null&&a.skip)r.deltaUpdateFailed=!0;return}if(n===this.currentLevel||t.withoutMultiVariant){if(n.fragmentError===0)n.loadError=0;let l=n.details;if(l===t.details&&l.advanced)l=void 0;this.playlistLoaded(s,t,l)}else if((i=t.deliveryDirectives)!=null&&i.skip)r.deltaUpdateFailed=!0}loadPlaylist(e){if(super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel))this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=n==null?void 0:n.age;this.log(`Loading level index ${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||"":""):""} ${i}`),this.hls.trigger(y.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){if(this.manualLevelIndex!==-1)return this.manualLevelIndex;else return this.hls.nextAutoLevel}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let s=this.hls.config.abrSwitchInterval;if(s>0){let r=performance.now(),n=r-this.lastABRSwitchTime,a=s*1000;if(this.lastABRSwitchTime>-1&&n ${e} (${Math.round(n)}ms < ${a}ms / ${s}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(n)}ms >= ${a}ms / ${s}s)`)}}if(this.level=e,this.manualLevelIndex===-1)this.hls.nextAutoLevel=e}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((r,n)=>{if(n!==e)return!0;if(this.steering)this.steering.removeLevel(r);if(r===this.currentLevel){if(this.currentLevel=null,this.currentLevelIndex=-1,r.details)r.details.fragments.forEach((a)=>a.level=-1)}return!1});if($n(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details)this.currentLevelIndex=this.currentLevel.details.fragments[0].level;if(this.manualLevelIndex>-1)this.manualLevelIndex=this.currentLevelIndex;let s=i.length-1;if(this._firstLevel=Math.min(this._firstLevel,s),this._startLevel)this._startLevel=Math.min(this._startLevel,s);this.hls.trigger(y.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;if(this._maxAutoLevel!==t)this._maxAutoLevel=t,this.hls.trigger(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i})}};Da=class Da extends Qe{constructor(e,t){super("key-loader",t);this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyLoaderInfo){let s=this.keyLoaderInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;if(t)t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,i){if(this.emeController)return this.emeController.loadClear(e,t,i);return null}load(e,t){if(!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled)return this.emeController.selectKeySystemFormat(e).then((i)=>this.loadInternal(e,t,i));return this.loadInternal(e,t)}loadInternal(e,t,i){let s=e.decryptdata;if(!s){let n=Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(rt(e,R.KEY_LOAD_ERROR,n))}let r=e;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":if(s.keyFormat==="identity")return this.loadKeyHTTP(r);return t?t.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(rt(e,R.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let i=jo(e.initSegment.data);if(i.length){let s=i[0],r=e.decryptdata.uri;if(s.some((n)=>n!==0))this.log(`Using keyId found in init segment ${Et(s)} keyUri: ${r}`),xt.setKeyIdForUri(r,s);else{let n=xt.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Et(n)} keyUri: ${r}`),s=n}e.decryptdata.keyId=s}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(rt(e,R.KEY_LOAD_ERROR,Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,i=t.uri;if(!i)return Promise.reject(rt(e,R.KEY_LOAD_ERROR,Error(`Invalid key URI: "${i}"`)));let s=this.keyLoaderInfo[i];if(s){if(s.decryptdata.key)return t.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then((o)=>(t.key=s.decryptdata.key,Me(Me({},o),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Et(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);let r=this.config,a=new r.loader(r);e.keyLoader=a;let l=this.keyLoaderInfo[i]={decryptdata:t,keyLoadPromise:null,loader:a};return l.keyLoadPromise=new Promise((o,u)=>{let d={type:se.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:i},c=r.keyLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,f,v,E)=>{let{frag:p,keyInfo:S,url:T}=v;if(!p.decryptdata||S!==this.keyLoaderInfo[T])return u(rt(p,R.KEY_LOAD_ERROR,Error("after key load, decryptdata unset or changed"),E));S.decryptdata.key=p.decryptdata.key=new Uint8Array(m.data),p.keyLoader=S.loader=S.keyLoadPromise=null,o({frag:p,keyInfo:S})},onError:(m,f,v,E)=>{this.resetLoader(f),u(rt(e,R.KEY_LOAD_ERROR,Error(`HTTP Error ${m.code} loading key ${m.text}`),v,Me({url:i,data:void 0},m)))},onTimeout:(m,f,v)=>{this.resetLoader(f),u(rt(e,R.KEY_LOAD_TIMEOUT,Error("key loading timed out"),v))},onAbort:(m,f,v)=>{this.resetLoader(f),u(rt(e,R.INTERNAL_ABORTED,Error("key loading aborted"),v))}};a.load(d,h,g)})}resetLoader(e){let{frag:t,keyInfo:i,url:s}=e,r=i.loader;if(t.keyLoader===r)t.keyLoader=i.loader=i.keyLoadPromise=null;if(delete this.keyLoaderInfo[s],r)r.destroy()}};tt.defaultConfig=void 0;td=st.KeySystemFormats,id=st.KeySystems,sd=st.SubtitleStreamController,rd=st.TimelineController,nd=st.requestMediaKeySystemAccess});var wa={};qt(wa,{createHlsEngine:()=>od});async function od(e){let{media:t,src:i,isTv:s}=e,{default:r}=await Promise.resolve().then(() => (Pa(),ka));if(!r.isSupported())return e.onError("This browser cannot play HLS streams."),{destroy:()=>{return},levels:()=>[]};let n=new r({...s?{maxBufferLength:60,maxMaxBufferLength:120,backBufferLength:30,liveSyncDurationCount:4}:{backBufferLength:90},enableWorker:!0}),a=0,l=!1;n.on(r.Events.ERROR,(u,d)=>{if(l)return;if(!d.fatal)return;if(a>=ad){e.onError("This stream kept failing and has been stopped."),n.destroy();return}switch(a+=1,d.type){case r.ErrorTypes.NETWORK_ERROR:e.onNotice("Reconnecting…"),n.startLoad();break;case r.ErrorTypes.MEDIA_ERROR:e.onNotice("Recovering…"),n.recoverMediaError();break;default:e.onError("This stream could not be played."),n.destroy()}}),n.on(r.Events.MANIFEST_PARSED,()=>{if(l)return;e.onNotice(null),e.onReady?.({live:n.levels.length>0&&!Number.isFinite(t.duration),levels:o()})}),n.on(r.Events.LEVEL_LOADED,(u,d)=>{if(l)return;e.onReady?.({live:d.details.live,levels:o()})}),n.on(r.Events.FRAG_BUFFERED,()=>{if(!l)e.onNotice(null)});function o(){return n.levels.map((u,d)=>({index:d,height:u.height||null,bitrate:u.bitrate||null,label:u.height?`${String(u.height)}p`:`${String(Math.round((u.bitrate||0)/1000))}k`}))}return n.loadSource(i),n.attachMedia(t),{destroy(){l=!0,n.destroy()},levels:o,setLevel(u){n.currentLevel=u},currentLevel:()=>n.autoLevelEnabled?-1:n.currentLevel}}var ad=3;var Oa=()=>{};function ud(e){if(!e)return null;for(let[t,i]of ld)if(t.test(e))return i;return e}function dd(e,t){if(!t||!e)return[];if(e==="audio"){if(/^mp4a\.40\./i.test(t))return['audio/mp4; codecs="mp4a.40.2"'];if(/^mp3$/i.test(t))return["audio/mpeg",'audio/mp4; codecs="mp3"'];if(/^opus$/i.test(t))return['audio/mp4; codecs="opus"','audio/mp4; codecs="Opus"']}return[`${e}/mp4; codecs="${t}"`]}function Fa(e,t,i="",s="stream"){if(!e||typeof t!=="function")return null;let r=[["video",e.videoCodec],["audio",e.audioCodec]],n=[];for(let[l,o]of r){if(!o)continue;if(!dd(l,o).some((d)=>{try{return t(d)}catch{return!1}})){let d=ud(o);if(d)n.push(d)}}if(n.length===0)return null;let a=n.length===1?n[0]:`${String(n[0])} and ${String(n[1])}`;return`This ${s} is ${String(a)}, which this browser cannot decode.${i?` ${i}`:""}`}var ld;var Ma=It(()=>{ld=[[/^(hvc1|hev1)/i,"H.265"],[/^av01/i,"AV1"],[/^(vp09|vp9)/i,"VP9"],[/^(ec-3|ec3)/i,"Dolby Digital Plus audio"],[/^(ac-3|ac3)/i,"Dolby Digital audio"],[/^dts/i,"DTS audio"],[/^(mp4a\.69|mp4a\.6b)/i,"MP2 audio"],[/^mp3$/i,"MP3 audio"],[/^mp4a\.40\./i,"AAC audio"]]});var $a={};qt($a,{MAX_RESTARTS:()=>Us,configFor:()=>Na,createMpegtsEngine:()=>gd});function Na(e,t={}){return{enableWorker:t.enableWorker??!1,enableStashBuffer:!0,stashInitialSize:393216,liveBufferLatencyChasing:!1,liveBufferLatencyMaxLatency:5,liveBufferLatencyMinRemain:1,autoCleanupSourceBuffer:!0,autoCleanupMaxBackwardDuration:30,autoCleanupMinBackwardDuration:10,lazyLoad:!1,lazyLoadMaxDuration:60,lazyLoadRecoverDuration:30,seekType:"range"}}async function gd(e,t={}){let{media:i,src:s,isTv:r}=e,n=await import("mpegts.js"),a=n.default??n;if(!a.getFeatureList().mseLivePlayback)return e.onError("This browser cannot play transport streams."),{destroy:()=>{return},levels:()=>[]};let l=Na(r,t),o=null,u=!1,d=0,c=null,h=null,g=-1,m=0,f=()=>{if(c)clearTimeout(c);if(h)clearInterval(h);c=null,h=null},v=()=>{if(!o)return;let x=o;o=null;try{x.destroy()}catch{}},E=(x)=>{if(u)return;u=!0,f(),v(),e.onError(x)},p=(x)=>{if(u)return;if(d>=Us){E(x);return}d+=1,f(),v(),e.onNotice(`Reconnecting… (${String(d)}/${String(Us)})`),c=setTimeout(()=>{if(c=null,!u)T()},cd*2**(d-1))},S=()=>{if(h)clearInterval(h);g=i.currentTime,m=0,h=setInterval(()=>{if(u||!o)return;if(i.paused||i.ended||i.seeking){m=0,g=i.currentTime;return}if(i.currentTime===g){if(m+=1,m>=fd)m=0,p("The stream stopped sending.");return}g=i.currentTime,m=0},hd)};function T(){o=a.createPlayer({type:"mpegts",isLive:e.live,url:s,withCredentials:t.withCredentials??!1},l),o.on(a.Events.MEDIA_INFO??"media_info",(...x)=>{let b=x[0],I=Fa(b,(A)=>globalThis.MediaSource?.isTypeSupported?.(A)??!1,t.unplayableAdvice??"");if(I)E(I)}),o.on(a.Events.ERROR??"error",(...x)=>{let b=String(x[1]??"");p(`This stream could not be played (${b}).`)}),o.attachMediaElement(i),o.load(),S(),e.onReady?.({live:e.live,levels:[]})}let L=()=>{d=0,e.onNotice(null)};return i.addEventListener("playing",L),T(),{destroy(){u=!0,f(),i.removeEventListener("playing",L),v()},levels:()=>[]}}var Us=5,cd=2000,hd=5000,fd=3;var Ba=It(()=>{Ma()});var Ua={};qt(Ua,{createNativeEngine:()=>md});async function md(e){let{media:t,src:i}=e;if(t.src=i,!t.preload)t.preload="metadata";t.load();let s=()=>{e.onReady?.({live:e.live||!Number.isFinite(t.duration),levels:[]})};return t.addEventListener("loadedmetadata",s,{once:!0}),Promise.resolve({destroy(){t.removeEventListener("loadedmetadata",s),t.removeAttribute("src"),t.load()},levels:()=>[]})}var Ga=()=>{};function Ha(e,t){if(!e||e.length===0)return[];if(!Number.isFinite(t)||t<=0)return[];let i=new Set,s=e.filter((r)=>Boolean(r)&&typeof r.title==="string").map((r)=>({start:Math.floor(r.start),title:r.title.trim()})).filter((r)=>Number.isFinite(r.start)&&r.start>=0).filter((r)=>r.startr.title!=="").sort((r,n)=>r.start-n.start).filter((r)=>{if(i.has(r.start))return!1;return i.add(r.start),!0});return s.map((r,n)=>({...r,end:s[n+1]?.start??t,position:r.start/t}))}function Ka(e,t){if(!Number.isFinite(t))return null;let i=null;for(let s of e)if(s.start<=t)i=s;else break;return i}var Wa="profullstack.player.prefs",Hs="profullstack.player.positions",pd=60,Vt={volume:1,muted:!1,rate:1};function Ht(e){if(e!==void 0)return e;try{return typeof window>"u"?null:window.localStorage}catch{return null}}function Ya(e,t){if(!e)return null;try{let i=e.getItem(t);if(i===null)return null;return JSON.parse(i)}catch{return null}}function Ks(e,t,i){if(!e)return;try{e.setItem(t,JSON.stringify(i))}catch{}}function Va(e,t,i,s){return typeof e==="number"&&Number.isFinite(e)?Math.min(i,Math.max(t,e)):s}function ja(e){let t=Ya(Ht(e),Wa);if(!t)return{...Vt};return{volume:Va(t.volume,0,1,Vt.volume),muted:typeof t.muted==="boolean"?t.muted:Vt.muted,rate:Va(t.rate,0.25,4,Vt.rate)}}function Gs(e,t){Ks(Ht(t),Wa,e)}function Ws(e){let t=Ya(e,Hs);if(!t||typeof t!=="object")return{};let i={};for(let[s,r]of Object.entries(t)){if(!r||typeof r!=="object")continue;let n=r;if(typeof n.t!=="number"||!Number.isFinite(n.t))continue;i[s]={t:n.t,d:typeof n.d==="number"&&Number.isFinite(n.d)?n.d:0,at:typeof n.at==="number"&&Number.isFinite(n.at)?n.at:0}}return i}function qa(e,t){return Ws(Ht(t))[e]??null}function za(e,t,i,s=Date.now){let r=Ht(i);if(!r)return;let n=Ws(r);n[e]={t:t.t,d:t.d,at:s()};let a=Object.entries(n).sort(([,l],[,o])=>o.at-l.at).slice(0,pd);Ks(r,Hs,Object.fromEntries(a))}function Vs(e,t){let i=Ht(t);if(!i)return;let s=Ws(i);if(!(e in s))return;let r=Object.entries(s).filter(([n])=>n!==e);Ks(i,Hs,Object.fromEntries(r))}var vd=15,yd=20;function Xa(e,t){if(!e)return!1;if(!Number.isFinite(t)||t<=0)return!1;if(Number.isFinite(e.d)&&e.d>0&&Math.abs(e.d-t)>1)return!1;return e.t>=vd&&e.t<=t-yd}function Ze(e){if(!Number.isFinite(e)||e<0)return"--:--";let t=Math.floor(e),i=Math.floor(t/3600),s=Math.floor(t%3600/60),r=t%60,n=(a)=>String(a).padStart(2,"0");return i>0?`${String(i)}:${n(s)}:${n(r)}`:`${String(s)}:${n(r)}`}var Ed=[[/\bAFT[A-Z0-9]+\b/i,"firetv"],[/\bKF[A-Z]+\b/,"silk"],[/\bSilk\b/i,"silk"],[/\bAndroid TV\b/i,"androidtv"],[/\bGoogleTV\b/i,"googletv"],[/\bTizen\b/i,"tizen"],[/\bWeb0S\b/i,"webos"],[/\bRoku\b/i,"roku"],[/AppleTV/i,"appletv"],[/\bCrKey\b/i,"chromecast"],[/\bSMART-TV\b/i,"smarttv"],[/\bSmartTV\b/i,"smarttv"]];function Qa(e){if(!e)return null;for(let[t,i]of Ed)if(t.test(e))return i;return null}function Za(e){return Qa(e)!==null}function Ja(e){return e?{hideAfterMs:6000,seekStep:10,alwaysShowFocus:!0}:{hideAfterMs:2800,seekStep:5,alwaysShowFocus:!1}}var Sd=[[/\.m3u8$/i,"hls"],[/\.(ts|mts|m2ts|mpegts)$/i,"mpegts"],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,"audio"],[/\.(mp4|m4v|webm|mov|ogv)$/i,"mp4"]],Td=[[/mpegurl/i,"hls"],[/mp2t|mpeg-?ts/i,"mpegts"],[/^audio\//i,"audio"],[/^video\//i,"mp4"]];function eo(e){if(e.kind)return e.kind;if(e.mimeType){for(let[i,s]of Td)if(i.test(e.mimeType))return s}let t=xd(e.src);for(let[i,s]of Sd)if(i.test(t))return s;return"unknown"}function xd(e){try{return new URL(e,"https://placeholder.invalid").pathname}catch{return e.split(/[?#]/)[0]??e}}function Ys(e=globalThis,t=null){let i=typeof e.MediaSource<"u",s=!1;try{let r=t??(typeof document>"u"?null:document.createElement("video"));s=r?r.canPlayType("application/vnd.apple.mpegurl")!==""||r.canPlayType("application/x-mpegURL")!=="":!1}catch{s=!1}return{mediaSource:i,nativeHls:s}}function js(e,t){let i=eo(e);switch(i){case"hls":if(t.mediaSource)return{engine:"hls",kind:i};if(t.nativeHls)return{engine:"native",kind:i};return{engine:"native",kind:i,unplayable:"This browser cannot play HLS streams."};case"mpegts":if(!t.mediaSource)return{engine:"mpegts",kind:i,unplayable:"This browser cannot play transport streams."};return{engine:"mpegts",kind:i};default:return{engine:"native",kind:i}}}function to(e){return e==="audio"}async function io(e,t){let i=t.capabilities??Ys(),s=js({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},i),r=()=>{return},n={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??s.kind==="mpegts",onError:t.onError??r,onNotice:t.onNotice??r,...t.onReady?{onReady:t.onReady}:{}};if(s.unplayable)return t.onError?.(s.unplayable),{destroy:r,engine:s.engine,kind:s.kind,levels:()=>[],unplayable:s.unplayable};let a,l=t.engines?.[s.engine];if(l)a=await l(n);else if(s.engine==="hls"){let{createHlsEngine:o}=await Promise.resolve().then(() => (Oa(),wa));a=await o(n)}else if(s.engine==="mpegts"){let{createMpegtsEngine:o}=await Promise.resolve().then(() => (Ba(),$a));a=await o(n,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??""})}else{let{createNativeEngine:o}=await Promise.resolve().then(() => (Ga(),Ua));a=await o(n)}return{destroy:()=>{a.destroy()},engine:s.engine,kind:s.kind,levels:a.levels,...a.setLevel?{setLevel:a.setLevel}:{},...a.currentLevel?{currentLevel:a.currentLevel}:{}}}var Fi=[1,1.25,1.5,1.75,2,0.75],Ld=5000,At=10,Ce={play:'',pause:'',replay:'',back10:'',fwd10:'',volume:'',muted:'',pip:'',link:'',enterFullscreen:'',exitFullscreen:''};function fe(e,t,i={}){let s=document.createElement(e);s.className=t;for(let[r,n]of Object.entries(i))s.setAttribute(r,n);return s}function lt(e,t,i,s){let r=fe("button",e,{type:"button","aria-label":t,title:t,"data-control":s});return r.innerHTML=i,r}function Ad(e){let t=e.error,i=t?.message??"";if(/URL safety check/i.test(i))return"This was blocked before it could load. That is a configuration problem on our side, not on yours — please report it.";switch(t?.code){case 1:return"Playback was stopped before it started.";case 2:return"The connection dropped while loading. Check your network and try again.";case 3:return"This could not be decoded by your browser.";case 4:return"This is missing, or in a format your browser cannot play.";default:return"This could not be played."}}function qs(e,t){let{src:i,mediaId:s,startAt:r=null,shareUrl:n=null,storage:a,now:l=Date.now,userAgent:o=typeof navigator>"u"?"":navigator.userAgent}=t,u=Za(o),d=Ja(u),c=t.capabilities??Ys(),h=js({src:i,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},c),g=t.audio??(typeof HTMLAudioElement<"u"&&t.media instanceof HTMLAudioElement?!0:to(h.kind)),m=t.live??h.kind==="mpegts",f=t.media??document.createElement(g?"audio":"video");if(!t.media)e.append(f);if(!g&&t.poster&&f instanceof HTMLVideoElement)f.poster=t.poster;if(f instanceof HTMLVideoElement)f.playsInline=!0;if(f.controls=!1,e.classList.add("pux-player"),u)e.classList.add("pux-player--tv");if(g)e.classList.add("pux-player--audio");if(!e.hasAttribute("tabindex"))e.setAttribute("tabindex","0");let v=lt("pux-player__overlay","Play",Ce.play,"overlay"),E=fe("div","pux-player__spinner",{"aria-hidden":"true"}),p=fe("div","pux-player__notice",{role:"status","aria-live":"polite"});p.hidden=!0;let S=fe("span","pux-player__notice-text"),T=fe("button","pux-player__notice-action",{type:"button"});T.hidden=!0,p.append(S,T);let L=fe("div","pux-player__bar"),x=fe("div","pux-player__scrub",{role:"slider",tabindex:"0","aria-label":"Seek","aria-valuemin":"0","aria-valuenow":"0"}),b=fe("div","pux-player__track"),I=fe("div","pux-player__buffered"),A=fe("div","pux-player__played"),_=fe("div","pux-player__marks",{"aria-hidden":"true"}),P=fe("div","pux-player__handle",{"aria-hidden":"true"}),w=fe("div","pux-player__tooltip",{"aria-hidden":"true"});b.append(I,A,_,P),x.append(b,w);let Y=fe("div","pux-player__row"),O=lt("pux-player__btn","Play",Ce.play,"play"),C=lt("pux-player__btn",`Back ${String(At)} seconds`,Ce.back10,"back"),k=lt("pux-player__btn",`Forward ${String(At)} seconds`,Ce.fwd10,"forward"),G=fe("div","pux-player__volume"),D=lt("pux-player__btn","Mute",Ce.volume,"mute"),U=fe("input","pux-player__volume-input",{type:"range",min:"0",max:"1",step:"0.05","aria-label":"Volume","data-control":"volume"});G.append(D,U);let F=fe("div","pux-player__live",{"data-control":"live"});F.textContent="LIVE";let M=fe("div","pux-player__time"),q=fe("div","pux-player__chapter"),X=fe("div","pux-player__spacer"),z=fe("button","pux-player__btn pux-player__btn--text",{type:"button","aria-label":"Playback speed",title:"Playback speed","data-control":"rate"}),j=fe("button","pux-player__btn pux-player__btn--text",{type:"button","aria-label":"Quality",title:"Quality","data-control":"quality"});j.hidden=!0;let oe=lt("pux-player__btn","Copy link at this time",Ce.link,"share"),de=lt("pux-player__btn","Picture in picture",Ce.pip,"pip"),te=lt("pux-player__btn","Fullscreen",Ce.enterFullscreen,"fullscreen");if(Y.append(O,C,k,G,F,M,q,X,z,j,oe,de,te),L.append(x,Y),e.append(v,E,p,L),u)U.hidden=!0,de.hidden=!0;if(g)te.hidden=!0,de.hidden=!0,v.hidden=!0;if(!n)oe.hidden=!0;if(typeof document>"u"||!document.pictureInPictureEnabled)de.hidden=!0;let re=[],Le=t.chapters??[],Ne=[],me=null,le=null,Be=0,Ke=!1,ke=!1,xe=null,ge=[];function ie(N,K,ue,Oe){N.addEventListener(K,ue,Oe),Ne.push(()=>N.removeEventListener(K,ue,Oe))}function Ie(N,K){if(S.textContent=N,p.hidden=!1,le)clearTimeout(le);if(K)T.hidden=!1,T.textContent=K.label,T.onclick=()=>{K.run(),ut()};else T.hidden=!0,T.onclick=null;le=setTimeout(ut,K?9000:4000)}function ut(){p.hidden=!0,T.onclick=null}function Kt(){e.classList.toggle("pux-player--live",m),x.hidden=m,C.hidden=m,k.hidden=m,z.hidden=m,oe.hidden=m||!n,F.hidden=!m,M.hidden=m,q.hidden=m}function Wt(){_.replaceChildren();for(let N of re){let K=fe("button","pux-player__mark",{type:"button","aria-label":`${N.title}, ${Ze(N.start)}`,title:N.title});K.style.left=`${String(N.position*100)}%`,K.addEventListener("click",(ue)=>{ue.stopPropagation(),f.currentTime=N.start}),_.append(K)}}function _e(){re=m?[]:Ha(Le,f.duration),Wt(),ve()}function ve(){if(m)return;let{duration:N,currentTime:K}=f,ue=Number.isFinite(N)&&N>0,Oe=ue?Math.min(1,Math.max(0,K/N)):0;if(A.style.width=`${String(Oe*100)}%`,P.style.left=`${String(Oe*100)}%`,f.buffered.length>0&&ue){let Js=0;for(let Rt=0;Rt=K){Js=f.buffered.end(Rt);break}I.style.width=`${String(Math.min(1,Js/N)*100)}%`}if(M.textContent=`${Ze(K)} / ${Ze(N)}`,x.setAttribute("aria-valuenow",String(Math.floor(K))),ue)x.setAttribute("aria-valuemax",String(Math.floor(N)));x.setAttribute("aria-valuetext",ue?`${Ze(K)} of ${Ze(N)}`:Ze(K));let bt=Ka(re,K);q.textContent=bt?bt.title:""}function We(){let N=!f.paused&&!f.ended,K=f.ended,ue=K?Ce.replay:N?Ce.pause:Ce.play,Oe=K?"Play again":N?"Pause":"Play";if(O.innerHTML=ue,O.setAttribute("aria-label",Oe),O.title=Oe,v.innerHTML=ue,v.setAttribute("aria-label",Oe),e.classList.toggle("pux-player--playing",N),e.classList.toggle("pux-player--ended",K),!N)we(!1)}function dt(){let N=f.muted||f.volume===0;D.innerHTML=N?Ce.muted:Ce.volume,D.setAttribute("aria-label",N?"Unmute":"Mute"),D.setAttribute("aria-pressed",N?"true":"false"),U.value=String(N?0:f.volume)}function Pe(){z.textContent=`${String(f.playbackRate)}×`,z.setAttribute("aria-label",`Playback speed, ${String(f.playbackRate)} times`)}function pt(){if(j.hidden=ge.length<2||!xe?.setLevel,j.hidden)return;let N=xe?.currentLevel?.()??-1,K=ge.find((ue)=>ue.index===N);j.textContent=N===-1?"Auto":K?.label??"Auto"}function we(N=!0){if(e.classList.add("pux-player--controls"),me)clearTimeout(me);if(!N)return;me=setTimeout(()=>{if(!f.paused)e.classList.remove("pux-player--controls")},d.hideAfterMs)}function ct(){if(f.paused||f.ended)f.play().catch(()=>{return});else f.pause()}function ht(N){if(m)return;let K=Number.isFinite(f.duration)?f.duration:1/0;f.currentTime=Math.min(K,Math.max(0,f.currentTime+N)),ve(),we()}function Mi(N){if(m)return;if(!Number.isFinite(f.duration)||f.duration<=0)return;f.currentTime=Math.min(1,Math.max(0,N))*f.duration,ve()}function zs(N){let K=b.getBoundingClientRect();if(K.width===0)return 0;return(N-K.left)/K.width}function Ni(N){let K=Fi.indexOf(f.playbackRate),ue=Fi[(K+N+Fi.length)%Fi.length]??1;f.playbackRate=ue}function so(){if(!xe?.setLevel)return;let N=[-1,...ge.map((bt)=>bt.index)],K=xe.currentLevel?.()??-1,ue=N.indexOf(K),Oe=N[(ue+1)%N.length]??-1;xe.setLevel(Oe),pt(),we()}async function Xs(){try{if(document.fullscreenElement){await document.exitFullscreen();return}await e.requestFullscreen()}catch{f.webkitEnterFullscreen?.()}}async function Qs(){try{if(document.pictureInPictureElement)await document.exitPictureInPicture();else if(f instanceof HTMLVideoElement)await f.requestPictureInPicture()}catch{Ie("Picture in picture is not available here.")}}async function ro(){if(!n)return;let N=Math.floor(f.currentTime),K=n(N);try{await navigator.clipboard.writeText(K),Ie(`Link copied, starting at ${Ze(N)}.`)}catch{Ie(K)}}ie(f,"loadedmetadata",()=>{if(_e(),ve(),m)return;let N=typeof r==="number"&&r>0?r:null;if(N!==null&&Number.isFinite(f.duration)&&N{f.currentTime=0,Vs(s,a)}})});function Yt(){if(m||!s)return;if(Number.isFinite(f.duration)&&f.duration>0&&!f.ended)za(s,{t:f.currentTime,d:f.duration},a,l)}ie(f,"timeupdate",()=>{if(!Ke)ve();if(l()-Be{We(),Yt()}),ie(f,"ended",()=>{if(We(),s)Vs(s,a)}),ie(f,"volumechange",()=>{dt(),Gs({volume:f.volume,muted:f.muted,rate:f.playbackRate},a)}),ie(f,"ratechange",()=>{Pe(),Gs({volume:f.volume,muted:f.muted,rate:f.playbackRate},a)}),ie(f,"waiting",()=>e.classList.add("pux-player--buffering")),ie(f,"playing",()=>e.classList.remove("pux-player--buffering")),ie(f,"canplay",()=>e.classList.remove("pux-player--buffering")),ie(f,"error",()=>{e.classList.remove("pux-player--buffering"),e.classList.add("pux-player--failed"),Ie(Ad(f))}),ie(v,"click",ct),ie(O,"click",ct),ie(C,"click",()=>{ht(-At)}),ie(k,"click",()=>{ht(At)}),ie(D,"click",()=>{f.muted=!f.muted}),ie(U,"input",()=>{f.volume=Number(U.value),f.muted=Number(U.value)===0}),ie(z,"click",()=>{Ni(1)}),ie(j,"click",so),ie(oe,"click",()=>void ro()),ie(de,"click",()=>void Qs()),ie(te,"click",()=>void Xs()),ie(document,"fullscreenchange",()=>{let N=document.fullscreenElement===e;e.classList.toggle("pux-player--fullscreen",N),te.innerHTML=N?Ce.exitFullscreen:Ce.enterFullscreen,te.setAttribute("aria-label",N?"Exit fullscreen":"Fullscreen")}),ie(x,"pointerdown",(N)=>{let K=N;Ke=!0,x.setPointerCapture(K.pointerId),Mi(zs(K.clientX))}),ie(x,"pointermove",(N)=>{let ue=zs(N.clientX);if(Number.isFinite(f.duration)&&f.duration>0)w.textContent=Ze(Math.max(0,Math.min(1,ue))*f.duration),w.style.left=`${String(Math.max(0,Math.min(1,ue))*100)}%`;if(!Ke)return;Mi(ue)});let Zs=(N)=>{if(!Ke)return;Ke=!1;let K=N;if(x.hasPointerCapture(K.pointerId))x.releasePointerCapture(K.pointerId)};ie(x,"pointerup",Zs),ie(x,"pointercancel",Zs),ie(e,"pointermove",()=>{we()}),ie(e,"pointerleave",()=>{if(!f.paused)e.classList.remove("pux-player--controls")}),ie(e,"focusin",()=>{we()}),ie(e,"keydown",(N)=>{let{key:K,target:ue}=N,Oe=ue?Y.contains(ue):!1;if(Oe&&["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(K))return;switch(K){case" ":case"k":case"Enter":if(K==="Enter"&&ue?.closest("button"))return;N.preventDefault(),ct();break;case"ArrowLeft":N.preventDefault(),ht(-d.seekStep);break;case"ArrowRight":N.preventDefault(),ht(d.seekStep);break;case"j":ht(-At);break;case"l":ht(At);break;case"ArrowUp":N.preventDefault(),f.volume=Math.min(1,f.volume+0.1),f.muted=!1,we();break;case"ArrowDown":N.preventDefault(),f.volume=Math.max(0,f.volume-0.1),we();break;case"m":f.muted=!f.muted,we();break;case"f":if(!te.hidden)Xs();break;case"p":if(!de.hidden)Qs();break;case"Home":if(N.preventDefault(),!m)f.currentTime=0;break;case"End":if(N.preventDefault(),!m&&Number.isFinite(f.duration))f.currentTime=f.duration;break;case"<":case",":if(!m)Ni(-1),we();break;case">":case".":if(!m)Ni(1),we();break;default:if(/^[0-9]$/.test(K)&&!Oe&&!m)N.preventDefault(),Mi(Number(K)/10)}}),ie(window,"pagehide",Yt);let jt=ja(a);if(f.volume=jt.volume,f.muted=t.autoplay?!0:jt.muted,f.playbackRate=jt.rate===0?Vt.rate:jt.rate,Kt(),We(),dt(),Pe(),ve(),_e(),we(!1),h.unplayable)e.classList.add("pux-player--failed"),Ie(h.unplayable);let no=ao();async function ao(){if(h.unplayable)return;try{let N=await io(f,{src:i,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{},live:m,isTv:u,capabilities:c,withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??"",...t.engines?{engines:t.engines}:{},onError:(K)=>{e.classList.add("pux-player--failed"),Ie(K)},onNotice:(K)=>{if(K===null)ut();else Ie(K)},onReady:(K)=>{if(ke)return;if(K.live!==m)m=K.live,Kt(),_e();ge=K.levels,pt()}});if(xe=N,ke){N.destroy(),xe=null;return}if(pt(),t.autoplay)f.play().catch(()=>{return})}catch{e.classList.add("pux-player--failed"),Ie("The player could not be loaded. Please reload the page.")}}return{media:f,destroy(){if(ke)return;if(ke=!0,Yt(),me)clearTimeout(me);if(le)clearTimeout(le);for(let N of Ne)N();if(no.then(()=>{xe?.destroy(),xe=null}),v.remove(),E.remove(),p.remove(),L.remove(),!t.media)f.remove();e.classList.remove("pux-player","pux-player--tv","pux-player--audio","pux-player--live","pux-player--controls","pux-player--playing","pux-player--ended","pux-player--buffering","pux-player--failed","pux-player--fullscreen")},setChapters(N){Le=N,_e()}}}function bd(){try{return typeof MediaSource<"u"&&MediaSource.isTypeSupported('audio/mp4; codecs="mp4a.40.2"')}catch{return!1}}function Rd(e,t,i){if(!("mediaSession"in navigator))return()=>{return};try{navigator.mediaSession.metadata=new MediaMetadata({title:t.title??"SiriusXM",artist:"SiriusXM",album:t.album??"Live radio",artwork:t.artwork?[{src:t.artwork,sizes:"300x300"}]:[]}),navigator.mediaSession.setActionHandler("play",()=>e.play().catch(()=>{return})),navigator.mediaSession.setActionHandler("pause",()=>e.pause()),navigator.mediaSession.setActionHandler("stop",i)}catch{}return()=>{try{navigator.mediaSession.metadata=null;for(let s of["play","pause","stop"])navigator.mediaSession.setActionHandler(s,null)}catch{}}}function Id(e,t,i){let s=document.createElement("audio");s.autoplay=!0,e.append(s);let r=qs(e,{src:t,kind:"hls",audio:!0,live:!0,media:s,autoplay:!0,withCredentials:!0,unplayableAdvice:"",mediaId:void 0}),n=Rd(s,i,i.onStop);return s.addEventListener("error",()=>{if(s.error&&s.error.code!==MediaError.MEDIA_ERR_ABORTED)i.onError("That station could not be played. Try again in a moment.")}),()=>{n(),r.destroy(),s.remove()}}window.__tipoffRadio={supported:bd,play:Id}; diff --git a/apps/web/src/app.js b/apps/web/src/app.js index 5c70275..5358177 100644 --- a/apps/web/src/app.js +++ b/apps/web/src/app.js @@ -22,6 +22,7 @@ import { verdictToStore, } from '@tipoff/playlists'; import { connection } from '@tipoff/queue'; +import * as radio from '@tipoff/radio'; import { oneChannelM3u, searchEverything } from '@tipoff/sports'; import { Hono } from 'hono'; import { getCookie, setCookie } from 'hono/cookie'; @@ -54,6 +55,7 @@ import { } from './views/pages.jsx'; import { Inbox, PeopleListPage, ProfilePage, Thread } from './views/people.jsx'; import { InvitePage, PremiumPage } from './views/premium.jsx'; +import { RadioPage, RadioRows } from './views/radio.jsx'; export const app = new Hono(); @@ -543,8 +545,11 @@ app.get('/events/:id', async (c) => { * named still had to go and find it. Returns null when they have no list or * nothing matched, which is what makes the section render as it always did. */ - const [marketChannels, sharedChannels] = await Promise.all([ + const [marketChannels, sharedChannels, radioSession] = await Promise.all([ marketChannelsForEvent({ userId: user?.id, markets: marketsOf(event) }), + // Whether the "On SiriusXM" section is drawn at all. A row read, no upstream + // call: the lookup itself waits for the button. + user && config.radio.enabled ? radio.storedSession(user.id) : null, // Other people's open lists. Signed-in only, and it returns no URLs at all -- // a shared channel is playable through the proxy and nowhere else, because // every other route hands over the address and the address is the owner's @@ -567,6 +572,7 @@ app.get('/events/:id', async (c) => { marketChannels={marketChannels} sharedChannels={sharedChannels} streamDead={c.req.query('stream_dead') ?? null} + radioConnected={Boolean(radioSession && !radioSession.unreadable)} />, ), ); @@ -2126,11 +2132,12 @@ app.post('/api/timezone', async (c) => { app.get('/settings', async (c) => { const user = requireUser(c); - const [prefs, passkeys, playlist, member, shareCandidates] = await Promise.all([ + const [prefs, passkeys, playlist, member, shareCandidates, radioSession] = await Promise.all([ q.getPrefs(user.id), q.listPasskeys(user.id), q.getPlaylist(user.id), isMember(user), + config.radio.enabled ? radio.storedSession(user.id) : null, // Fetched unconditionally rather than only for a member: the picker has to be // populated the instant somebody joins, and a second round trip after the // upgrade is how it renders empty on the one page view that matters. @@ -2186,11 +2193,334 @@ app.get('/settings', async (c) => { passwordMinLength={auth.PASSWORD_MIN_LENGTH} member={member} shareCandidates={shareCandidates} + radio={ + config.radio.enabled + ? { + session: radioSession, + pending: radio.peekPending(user.id), + notice: radioNoticeFor(c.req.query('siriusxm')), + error: c.req.query('siriusxm_error') ?? null, + } + : null + } + />, + ), + ); +}); + +/* --------------------------------------------------------------- radio -- */ + +/** + * A reader's own SiriusXM, connected in settings and played on /radio. + * + * The same BYO rail as the playlist, with the same rule about what leaves the + * server: nothing. The session is minted here with the code SiriusXM emails + * the reader, stored sealed, and every byte of audio is fetched by us as that + * reader and handed to that reader's browser. There is no address to copy + * because the addresses only work with the bearer. + */ + +function radioNoticeFor(state) { + switch (state) { + case 'code': + return 'SiriusXM has sent a code to that address. Enter it below.'; + case 'connected': + return 'SiriusXM connected. The lineup is on the Radio page.'; + case 'removed': + return 'SiriusXM disconnected.'; + default: + return null; + } +} + +const radioBack = (query) => `/settings?${query}#siriusxm`; + +/** + * The reader's problem or ours, in the status. A SiriusXmError knows which; + * anything else is ours and must not read as "wrong code". + */ +function radioFailure(err) { + if (err instanceof radio.SiriusXmError) return { message: err.message, status: err.status }; + console.error('[radio]', err); + return { message: 'SiriusXM did not answer. Try again in a moment.', status: 502 }; +} + +app.post('/api/radio/connect', async (c) => { + const user = requireUser(c); + if (!config.radio.enabled) return c.json({ error: 'radio is off' }, 404); + const body = await c.req.parseBody(); + const email = String(body.email ?? '').trim(); + if (!email.includes('@')) { + return respond(c, { + json: { error: 'Enter the email on your SiriusXM account.' }, + status: 400, + redirectTo: radioBack('siriusxm_error=Enter%20the%20email%20on%20your%20SiriusXM%20account.'), + }); + } + try { + const state = await radio.startOtpLogin(email, { + proxy: radio.proxyFor(user.id), + deviceGrant: config.radio.deviceGrant || null, + }); + radio.putPending(user.id, { ...state, email }); + return respond(c, { json: { ok: true, step: 'code' }, redirectTo: radioBack('siriusxm=code') }); + } catch (err) { + const { message, status } = radioFailure(err); + return respond(c, { + json: { error: message }, + status, + redirectTo: radioBack(`siriusxm_error=${encodeURIComponent(message)}`), + }); + } +}); + +app.post('/api/radio/connect/verify', async (c) => { + const user = requireUser(c); + if (!config.radio.enabled) return c.json({ error: 'radio is off' }, 404); + const body = await c.req.parseBody(); + // Pasted codes arrive as "1 2 3 4 5 6" or wrapped from an email; SXM wants digits. + const otp = String(body.otp ?? '').replace(/\s+/g, ''); + const pending = radio.takePending(user.id); + if (!pending) { + const message = 'That code has expired. Send a new one.'; + return respond(c, { + json: { error: message }, + status: 400, + redirectTo: radioBack(`siriusxm_error=${encodeURIComponent(message)}`), + }); + } + if (!otp) { + // The jar is consumed by takePending; put it back so a blank submit is not + // a restart. + radio.putPending(user.id, pending); + const message = 'Enter the code from the email.'; + return respond(c, { + json: { error: message }, + status: 400, + redirectTo: radioBack(`siriusxm_error=${encodeURIComponent(message)}`), + }); + } + try { + const session = await radio.completeOtpLogin(pending, otp, { proxy: radio.proxyFor(user.id) }); + await radio.saveSession(user.id, { email: pending.email, ...session }); + return respond(c, { + json: { ok: true, connected: true }, + redirectTo: radioBack('siriusxm=connected'), + }); + } catch (err) { + const { message, status } = radioFailure(err); + // A wrong code does not spend the sign-in: the jar goes back so the reader + // can try the code again rather than asking for a new one. + if (status === 400) radio.putPending(user.id, pending); + return respond(c, { + json: { error: message }, + status, + redirectTo: radioBack(`siriusxm_error=${encodeURIComponent(message)}`), + }); + } +}); + +app.post('/api/radio/connect/cancel', async (c) => { + const user = requireUser(c); + radio.dropPending(user.id); + return respond(c, { json: { ok: true }, redirectTo: '/settings#siriusxm' }); +}); + +app.post('/api/radio/disconnect', async (c) => { + const user = requireUser(c); + radio.dropPending(user.id); + await radio.disconnect(user.id); + return respond(c, { json: { ok: true }, redirectTo: radioBack('siriusxm=removed') }); +}); + +/** Rendered per request and never cached: the lineup is the same for everyone, the session is not. */ +app.get('/radio', async (c) => { + const user = c.get('user'); + if (!config.radio.enabled) return c.html(await render(), 404); + const cat = radio.CATEGORIES.includes(c.req.query('cat')) ? c.req.query('cat') : 'sports'; + const qText = (c.req.query('q') ?? '').trim().slice(0, 80); + const session = user ? await radio.storedSession(user.id) : null; + let channels = []; + let error = null; + if (session && !session.unreadable) { + try { + channels = qText ? await radio.search(user.id, qText) : await radio.channels(user.id, cat); + } catch (err) { + error = radioFailure(err).message; + } + } + c.header('cache-control', 'private, no-store'); + return c.html( + await render( + , ), ); }); +/** + * The channels naming either side of a fixture, as rows. + * + * Both names are searched and the union is kept in lineup order, so a game on + * a team channel and one on a league channel both surface. Answered as HTML + * because the row already has one template, on the server. + */ +app.get('/radio/find', async (c) => { + const user = requireUser(c); + if (!config.radio.enabled) return c.text('radio is off', 404); + const event = await q.getEvent(Number(c.req.query('event'))); + if (!event) return c.text('no such fixture', 404); + const names = [event.home_team_name, event.away_team_name, event.league_name] + .map((n) => String(n ?? '').trim()) + .filter((n) => n.length >= 3); + if (names.length === 0) return c.text('This fixture has no names to look up.', 404); + try { + const found = await Promise.all(names.map((n) => radio.search(user.id, n))); + const seen = new Set(); + const channels = found.flat().filter((ch) => { + if (seen.has(ch.stationId)) return false; + seen.add(ch.stationId); + return true; + }); + c.header('cache-control', 'private, no-store'); + // A fragment, not a page: no doctype, no Layout, so not render(). It is + // dropped into a section app.js already has on the page. + const fragment = + channels.length === 0 + ? '

SiriusXM has no channel naming this fixture right now. Game channels usually appear close to kickoff.

' + : await ().toString(); + return c.body(fragment, 200, { 'content-type': 'text/html; charset=utf-8' }); + } catch (err) { + const { message, status } = radioFailure(err); + return c.text(message, status); + } +}); + +/** + * Where a same-origin address for an SXM resource is minted. Root-relative so + * the browser resolves it against the page it is on; nothing here needs to + * know the public hostname. + */ +const radioProxyUrl = (target, quality) => + `/radio/proxy?u=${encodeURIComponent(target)}&quality=${encodeURIComponent(quality)}`; + +const radioQuality = (value) => (radio.QUALITIES.includes(value) ? value : radio.DEFAULT_QUALITY); + +/** + * Fetch one SXM resource as the reader, at most once for everyone asking. + * + * Through the reader's pinned proxy, because the tune URL was minted from + * that IP and the key endpoint checks. Manifests and keys are small; a segment + * is a few seconds of audio; all are buffered so `sharedFetch` can hand the + * same bytes to a second tab without a second upstream request. + */ +async function radioFetch(userId, target) { + return radio.sharedFetch(target, async () => { + const res = await radio.sxmFetch( + target, + { + headers: { + ...radio.API_HEADERS, + Accept: 'application/vnd.apple.mpegurl, application/x-mpegURL, */*', + Authorization: `Bearer ${await radio.bearerFor(userId)}`, + }, + }, + { proxy: radio.proxyFor(userId) }, + ); + return { + status: res.status, + contentType: res.headers.get('content-type'), + body: await res.arrayBuffer(), + }; + }); +} + +/** The reply for a manifest, a key or a segment, from what SXM sent. */ +function radioResource(c, target, quality, upstream) { + if (upstream.status < 200 || upstream.status >= 300) { + if (upstream.status === 401 || upstream.status === 403) radio.forget(c.get('user').id); + return c.text(`SiriusXM answered ${upstream.status}`, upstream.status === 404 ? 404 : 502); + } + const ct = upstream.contentType ?? ''; + if (radio.isKeyUrl(target)) { + // The AES key arrives as JSON; the player needs the sixteen bytes. + let key; + try { + key = radio.decodeKeyJson(JSON.parse(new TextDecoder().decode(upstream.body))); + } catch (err) { + return c.text(`key decode failed: ${err.message}`, 502); + } + return c.body(key, 200, { + 'content-type': 'application/octet-stream', + 'cache-control': 'no-store, private', + }); + } + if (radio.looksLikePlaylist(target, ct)) { + const text = new TextDecoder().decode(upstream.body); + const rewritten = radio.rewritePlaylist(text, target, quality, (u) => + radioProxyUrl(u, quality), + ); + return c.body(rewritten, 200, { + 'content-type': 'application/vnd.apple.mpegurl', + 'cache-control': 'no-store, private', + }); + } + return c.body(upstream.body, 200, { + 'content-type': ct || 'application/octet-stream', + 'cache-control': 'no-store, private', + 'x-accel-buffering': 'no', + }); +} + +/** + * The playlist the player is handed: a station id in, a rewritten manifest out. + * + * The tune URL never reaches the browser. It is minted here, held for its own + * lifetime, and every address inside the manifest it fetches is rewritten to + * /radio/proxy before the bytes leave. + */ +app.get('/radio/stream.m3u8', async (c) => { + const user = requireUser(c); + if (!config.radio.enabled) return c.json({ error: 'radio is off' }, 404); + const parsed = radio.parseStationId(c.req.query('id') ?? ''); + if (!parsed) return c.json({ error: 'no such station' }, 400); + const quality = radioQuality(c.req.query('quality')); + try { + const target = await radio.tune(user.id, parsed); + const upstream = await radioFetch(user.id, target); + return radioResource(c, target, quality, upstream); + } catch (err) { + const { message, status } = radioFailure(err); + return c.json({ error: message }, status); + } +}); + +/** + * Everything the manifest points at. The target is checked against SXM's own + * hosts before anything is fetched: this route carries a bearer, and a bearer + * sent to an address a reader chose is a bearer handed to that reader. + */ +app.get('/radio/proxy', async (c) => { + const user = requireUser(c); + if (!config.radio.enabled) return c.json({ error: 'radio is off' }, 404); + const target = c.req.query('u') ?? ''; + if (!radio.isSiriusXmUrl(target)) return c.text('forbidden target', 403); + const quality = radioQuality(c.req.query('quality')); + try { + const upstream = await radioFetch(user.id, target); + return radioResource(c, target, quality, upstream); + } catch (err) { + const { message, status } = radioFailure(err); + return c.text(message, status); + } +}); + /** * Notification self-check. * @@ -3057,6 +3387,10 @@ const STATIC_FILES = [ // Fetched by app.js on the first press of Play, not linked by the Layout: it is // a quarter of a megabyte of demuxer that most readers never need. ['/vendor-mpegts.js', 'vendor-mpegts.js', 'text/javascript'], + // Same again for the radio player and its stylesheet: fetched on the first + // press of Play on a station, by app.js. + ['/vendor-player.js', 'vendor-player.js', 'text/javascript'], + ['/vendor-player.css', 'vendor-player.css', 'text/css'], ['/sw.js', 'sw.js', 'text/javascript'], ['/logo.png', 'logo.png', 'image/png'], ]; diff --git a/apps/web/src/client/radio-entry.js b/apps/web/src/client/radio-entry.js new file mode 100644 index 0000000..45d33a0 --- /dev/null +++ b/apps/web/src/client/radio-entry.js @@ -0,0 +1,100 @@ +/** + * The radio player, bundled as a global. + * + * The house player -- @profullstack/player -- with its compact audio bar, its + * hls.js engine and its recovery ladder. It is the same package the codec table + * and the playlist parser already come from; this is the first place on the + * site that draws its control bar, because the live TV player predates it and + * keeps its own. + * + * Loaded on demand like the transport stream demuxer: hls.js is a couple of + * hundred kilobytes and most readers on a page with a Play button never press + * it. app.js injects the tag on the first press. + */ + +import { createPlayer } from '@profullstack/player'; + +/** Can this browser play HLS through Media Source? iPhone Safari cannot, and has no fallback we can offer. */ +function supported() { + try { + return ( + typeof MediaSource !== 'undefined' && + MediaSource.isTypeSupported('audio/mp4; codecs="mp4a.40.2"') + ); + } catch { + return false; + } +} + +/** + * Tell the OS what is playing, so the lock screen and the headset buttons + * work. The player owns the element; this only decorates it. + */ +function mediaSession(media, meta, onStop) { + if (!('mediaSession' in navigator)) return () => undefined; + try { + navigator.mediaSession.metadata = new MediaMetadata({ + title: meta.title ?? 'SiriusXM', + artist: 'SiriusXM', + album: meta.album ?? 'Live radio', + artwork: meta.artwork ? [{ src: meta.artwork, sizes: '300x300' }] : [], + }); + navigator.mediaSession.setActionHandler('play', () => media.play().catch(() => undefined)); + navigator.mediaSession.setActionHandler('pause', () => media.pause()); + navigator.mediaSession.setActionHandler('stop', onStop); + } catch { + // An older browser with the property and none of the constructors. + } + return () => { + try { + navigator.mediaSession.metadata = null; + for (const action of ['play', 'pause', 'stop']) + navigator.mediaSession.setActionHandler(action, null); + } catch { + // nothing to clear + } + }; +} + +/** + * Play one station into a stage element. + * + * @param {HTMLElement} stage an empty block the bar is built into + * @param {string} src the same-origin playlist URL + * @param {{title?: string, album?: string, artwork?: string, + * onError: (message: string) => void, onNotice: (message: string|null) => void, + * onStop: () => void}} meta + * @returns {() => void} teardown + */ +function play(stage, src, meta) { + const media = document.createElement('audio'); + media.autoplay = true; + stage.append(media); + const player = createPlayer(stage, { + src, + kind: 'hls', + audio: true, + live: true, + media, + autoplay: true, + withCredentials: true, + unplayableAdvice: '', + // A live station has no position worth remembering. + mediaId: undefined, + }); + const clearSession = mediaSession(media, meta, meta.onStop); + media.addEventListener('error', () => { + // hls.js reports its own failures through the bar; this is the element + // itself giving up, which the bar does not always see. + if (media.error && media.error.code !== MediaError.MEDIA_ERR_ABORTED) { + meta.onError('That station could not be played. Try again in a moment.'); + } + }); + return () => { + clearSession(); + player.destroy(); + media.remove(); + }; +} + +window.__tipoffRadio = { supported, play }; diff --git a/apps/web/src/lib/security-headers.js b/apps/web/src/lib/security-headers.js index 8701ef2..f0923b3 100644 --- a/apps/web/src/lib/security-headers.js +++ b/apps/web/src/lib/security-headers.js @@ -36,6 +36,7 @@ const sha256 = (src) => `'sha256-${createHash('sha256').update(src, 'utf8').dige * media-src blob:, which is what MediaSource hands the